You are here

public function Ip2CountryTest::testIpLookup in IP-based Determination of a Visitor's Country 8

Tests IP lookup for addresses in / not in the database.

File

tests/src/Functional/Ip2CountryTest.php, line 92

Class

Ip2CountryTest
Tests operations of the IP to Country module.

Namespace

Drupal\Tests\ip2country\Functional

Code

public function testIpLookup() {
  \Drupal::service('ip2country.manager')
    ->updateDatabase('arin');
  $count = \Drupal::service('ip2country.manager')
    ->getRowCount();
  $this
    ->assertNotEquals(0, $count, 'Database has been updated with ' . $count . ' rows.');

  // Real working IPs.
  $ip_array = [
    '125.29.33.201' => 'JP',
    '212.58.224.138' => 'GB',
    '184.51.240.110' => 'US',
    '210.87.9.66' => 'AU',
    '93.184.216.119' => 'EU',
  ];
  foreach ($ip_array as $ip_address => $country) {

    // Test dotted quad string form of address.
    $lookup = \Drupal::service('ip2country.lookup')
      ->getCountry($ip_address);
    $this
      ->assertEquals($country, $lookup, $ip_address . ' found, resolved to ' . $lookup . '.');

    // Test 32-bit unsigned long form of address.
    $usl_lookup = \Drupal::service('ip2country.lookup')
      ->getCountry(ip2long($ip_address));
    $this
      ->assertEquals($lookup, $usl_lookup, 'Unsigned long lookup found same country code.');
    $this
      ->assertTrue(TRUE, 'Valid IP found in database.');
  }

  // Invalid and reserved IPs.
  $ip_array = [
    '127.0.0.1',
    '358.1.1.0',
  ];
  foreach ($ip_array as $ip_address) {
    $country = \Drupal::service('ip2country.lookup')
      ->getCountry($ip_address);
    $this
      ->assertFalse($country, $ip_address . ' not found in database.');
    $this
      ->assertTrue(TRUE, 'Invalid IP not found in database.');
  }
  \Drupal::service('ip2country.manager')
    ->emptyDatabase();
  $count = \Drupal::service('ip2country.manager')
    ->getRowCount();
  $this
    ->assertEquals(0, $count, 'Database is empty.');
}