def city(self, address):
     if address == '128.101.101.101':
         return MockResponse(
             location=MockLocation(latitude=44.9759, longitude=-93.2166))
     if address == '1.2.3.4':
         return MockResponse(
             location=MockLocation(latitude=47.913, longitude=-122.3042))
     if address == '1.1.1.123':
         return MockResponse(
             location=MockLocation(latitude=-37.7, longitude=145.1833))
     if address == '255.255.255.255':
         return MockResponse(
             location=MockLocation(latitude=0.0, longitude=0.0))
     if address == '192.0.2.16':
         return MockResponse(
             location=MockLocation(latitude=1.1, longitude=1.1))
     if address == '1234:1234:abcd:abcd:1234:1234:abcd:abcd':
         return MockResponse(
             location=MockLocation(latitude=2.1, longitude=2.1))
     if address == '2001:db8:0:0:8d3::':
         return MockResponse(
             location=MockLocation(latitude=3.1, longitude=3.1))
     if address == '127.101.101.101':
         return MockResponse(
             location=MockLocation(latitude=4.1, longitude=4.1))
     if address == '1.1.2.345':
         raise AddressNotFoundError()
     if address == 'aaa':
         raise ValueError()
Exemple #2
0
    def test_geolocation(self):
        """The GeoIP database is not available in CI."""
        self.request.ip_address = "invalid-ip"
        geolocation = get_geolocation(self.request)
        self.assertIsNone(geolocation.country)

        with mock.patch("adserver.utils.geoip") as geoip:
            geoip.city.return_value = {
                "country_code": "FR",
                "region": None,
                "dma_code": None,
            }
            self.request.ip_address = "8.8.8.8"
            geolocation = get_geoipdb_geolocation(self.request)
            self.assertIsNotNone(geolocation)
            self.assertEqual(geolocation.country, "FR")

        with mock.patch("adserver.utils.geoip") as geoip:
            geoip.city.side_effect = AddressNotFoundError()
            geolocation = get_geoipdb_geolocation(self.request)
            self.assertIsNone(geolocation.country)

        with mock.patch("adserver.utils.geoip") as geoip:
            geoip.city.side_effect = GeoIP2Exception()
            geolocation = get_geoipdb_geolocation(self.request)
            self.assertIsNone(geolocation.country)
    def test_replace_ip_address(self):
        """ Test replacing ip address with geographical information mocking the geolite database """
        latitude = ("23.1194",)
        longitude = ("-82.392",)
        city = ("Suva",)
        country = ("Peru",)
        country_iso_code = "PE"

        geoip_client = Mock(spec=geoip2.database.Reader)
        geoip_client.city.return_value = SimpleNamespace(
            location=SimpleNamespace(latitude=latitude, longitude=longitude),
            city=SimpleNamespace(name=city),
            country=SimpleNamespace(name=country, iso_code=country_iso_code),
        )
        client_lat, client_lon, client_city, client_country, client_country_code = replace_ip_address(
            "100.229.139.139", geoip_client
        )

        self.assertEqual(latitude, client_lat)
        self.assertEqual(longitude, client_lon)
        self.assertEqual(city, client_city)
        self.assertEqual(country, client_country)
        self.assertEqual(country_iso_code, client_country_code)

        # Test AddressNotFoundError
        geoip_client.city.side_effect = AddressNotFoundError()
        client_lat, client_lon, client_city, client_country, client_country_code = replace_ip_address(
            "72.59.232.155", geoip_client
        )
        self.assertEqual("", client_lat)
        self.assertEqual("", client_lon)
        self.assertEqual("", client_city)
        self.assertEqual("", client_country)
        self.assertEqual("", client_country_code)
Exemple #4
0
    def _exception_for_web_service_error(
        message: str, code: str, status: int, uri: str
    ) -> Union[
        AuthenticationError,
        AddressNotFoundError,
        PermissionRequiredError,
        OutOfQueriesError,
        InvalidRequestError,
    ]:
        if code in ("IP_ADDRESS_NOT_FOUND", "IP_ADDRESS_RESERVED"):
            return AddressNotFoundError(message)
        if code in (
            "ACCOUNT_ID_REQUIRED",
            "ACCOUNT_ID_UNKNOWN",
            "AUTHORIZATION_INVALID",
            "LICENSE_KEY_REQUIRED",
            "USER_ID_REQUIRED",
            "USER_ID_UNKNOWN",
        ):
            return AuthenticationError(message)
        if code in ("INSUFFICIENT_FUNDS", "OUT_OF_QUERIES"):
            return OutOfQueriesError(message)
        if code == "PERMISSION_REQUIRED":
            return PermissionRequiredError(message)

        return InvalidRequestError(message, code, status, uri)
 def city(self, address):  # pylint: disable=too-complex,inconsistent-return-statements,no-self-use,too-many-return-statements
     if address == '128.101.101.101':
         return MockResponse(
             location=MockLocation(latitude=44.9759, longitude=-93.2166))
     if address == '1.2.3.4':
         return MockResponse(
             location=MockLocation(latitude=47.913, longitude=-122.3042))
     if address == '1.1.1.123':
         return MockResponse(
             location=MockLocation(latitude=-37.7, longitude=145.1833))
     if address == '255.255.255.255':
         return MockResponse(
             location=MockLocation(latitude=0.0, longitude=0.0))
     if address == '192.0.2.16':
         return MockResponse(
             location=MockLocation(latitude=1.1, longitude=1.1))
     if address == '1234:1234:abcd:abcd:1234:1234:abcd:abcd':
         return MockResponse(
             location=MockLocation(latitude=2.1, longitude=2.1))
     if address == '2001:db8:0:0:8d3::':
         return MockResponse(
             location=MockLocation(latitude=3.1, longitude=3.1))
     if address == '127.101.101.101':
         return MockResponse(
             location=MockLocation(latitude=4.1, longitude=4.1))
     if address == '1.1.2.345':
         raise AddressNotFoundError()
     if address == 'aaa':
         raise ValueError()
Exemple #6
0
def _lookup_remote_addr(method,
                        num_proxies=1,
                        raise_on_not_found=True,
                        **kwargs):
    ctx = _request_ctx_stack.top
    if ctx is not None:
        if not hasattr(ctx, '_geoip2'):
            addr = get_remote_addr(num_proxies)
            try:
                ctx._geoip2 = method(addr, **kwargs)
            except AddressNotFoundError:
                ctx._geoip2 = None
                if raise_on_not_found:
                    raise
        if raise_on_not_found and not ctx._geoip2:
            raise AddressNotFoundError(
                'The address {} is not in the database.'.format(addr))
        return ctx._geoip2
Exemple #7
0
class GeoIPTestCase(TestCase):
    """
    Tests the get_lng_lat function.
    """
    def test_known_ip(self):
        """
        Test case for a known IP address.
        """
        actual = geoip.get_lng_lat('128.101.101.101')
        expected = (-93.2166, 44.9759)
        self.assertEqual(actual, expected)

    def test_no_ip(self):
        """
        Test case for no IP address.
        """
        self.assertEqual(geoip.get_lng_lat(None), None)

    def test_private_ip(self):
        """
        Test case for a private IP address.
        """
        self.assertEqual(geoip.get_lng_lat('10.195.193.80'), None)

    def test_invalid_ip(self):
        """
        Test case for an invalid IP address.
        """
        with LogCapture() as log_capture:
            self.assertEqual(geoip.get_lng_lat('abc'), None)
            log_capture.check(
                ('lab.geoip.geoip', 'WARNING',
                 '"abc" does not appear to be an IPv4 or IPv6 address.'))

    @patch('lab.geoip.geoip.Reader.city', side_effect=AddressNotFoundError())
    def test_unknown_ip(self, mock_reader):
        """
        Test case for an unknown IP address.
        """
        with LogCapture() as log_capture:
            self.assertEqual(geoip.get_lng_lat('99.99.99.99'), None)
            log_capture.check(
                ('lab.geoip.geoip', 'WARNING',
                 'The address 99.99.99.99 is not in the GeoLite2 database.'))
    def test__geoip2(self, mock_city):
        mock_city.return_value = self.test_city
        data = self.middleware._geoip2(self.test_ip, mock_city)
        self.assertEqual(data.ip_address, "8.8.8.8")
        self.assertEqual(data.city, "Los Angeles")
        self.assertEqual(data.country_code, "US")
        self.assertEqual(data.country_name, "United States")
        self.assertEqual(data.dma_code, None)
        self.assertEqual(data.latitude, 37.751)
        self.assertEqual(data.longitude, -97.822)
        self.assertEqual(data.postal_code, 90210)
        self.assertEqual(data.region, "CA")
        mock_city.side_effect = AddressNotFoundError()
        data = self.middleware.city(self.test_ip)
        self.assertTrue(data.is_unknown)

        mock_city.side_effect = GeoIP2Exception()
        self.assertIsNone(self.middleware.city(self.test_ip))

        mock_city.side_effect = Exception()
        self.assertIsNone(self.middleware.city(self.test_ip))
Exemple #9
0
 def test_geo_data__address_not_found(self, mock_get, mock_city_or_country) -> None:
     middleware = GeoIP2Middleware(lambda r: HttpResponse())
     mock_get.return_value = None
     mock_city_or_country.side_effect = AddressNotFoundError()
     assert middleware.geo_data("1.2.3.4") == unknown_address("1.2.3.4")