| 1 |
import ipaddress |
| 2 |
import itertools |
| 3 |
import pathlib |
| 4 |
from unittest import mock, skipUnless |
| 5 |
|
| 6 |
from django.conf import settings |
| 7 |
from django.contrib.gis.geoip2 import HAS_GEOIP2 |
| 8 |
from django.contrib.gis.geos import GEOSGeometry |
| 9 |
from django.test import SimpleTestCase, override_settings |
| 10 |
from django.utils.deprecation import RemovedInDjango60Warning |
| 11 |
|
| 12 |
if HAS_GEOIP2: |
| 13 |
import geoip2 |
| 14 |
|
| 15 |
from django.contrib.gis.geoip2 import GeoIP2, GeoIP2Exception |
| 16 |
|
| 17 |
|
| 18 |
def build_geoip_path(*parts): |
| 19 |
return pathlib.Path(__file__).parent.joinpath("data/geoip2", *parts).resolve() |
| 20 |
|
| 21 |
|
| 22 |
@skipUnless(HAS_GEOIP2, "GeoIP2 is required.") |
| 23 |
@override_settings( |
| 24 |
GEOIP_CITY="GeoLite2-City-Test.mmdb", |
| 25 |
GEOIP_COUNTRY="GeoLite2-Country-Test.mmdb", |
| 26 |
) |
| 27 |
class GeoLite2Test(SimpleTestCase): |
| 28 |
fqdn = "sky.uk" |
| 29 |
ipv4_str = "2.125.160.216" |
| 30 |
ipv6_str = "::ffff:027d:a0d8" |
| 31 |
ipv4_addr = ipaddress.ip_address(ipv4_str) |
| 32 |
ipv6_addr = ipaddress.ip_address(ipv6_str) |
| 33 |
query_values = (fqdn, ipv4_str, ipv6_str, ipv4_addr, ipv6_addr) |
| 34 |
|
| 35 |
expected_city = { |
| 36 |
"accuracy_radius": 100, |
| 37 |
"city": "Boxford", |
| 38 |
"continent_code": "EU", |
| 39 |
"continent_name": "Europe", |
| 40 |
"country_code": "GB", |
| 41 |
"country_name": "United Kingdom", |
| 42 |
"is_in_european_union": False, |
| 43 |
"latitude": 51.75, |
| 44 |
"longitude": -1.25, |
| 45 |
"metro_code": None, |
| 46 |
"postal_code": "OX1", |
| 47 |
"region_code": "ENG", |
| 48 |
"region_name": "England", |
| 49 |
"time_zone": "Europe/London", |
| 50 |
# Kept for backward compatibility. |
| 51 |
"dma_code": None, |
| 52 |
"region": "ENG", |
| 53 |
} |
| 54 |
expected_country = { |
| 55 |
"continent_code": "EU", |
| 56 |
"continent_name": "Europe", |
| 57 |
"country_code": "GB", |
| 58 |
"country_name": "United Kingdom", |
| 59 |
"is_in_european_union": False, |
| 60 |
} |
| 61 |
|
| 62 |
@classmethod |
| 63 |
def setUpClass(cls): |
| 64 |
# Avoid referencing __file__ at module level. |
| 65 |
cls.enterClassContext(override_settings(GEOIP_PATH=build_geoip_path())) |
| 66 |
# Always mock host lookup to avoid test breakage if DNS changes. |
| 67 |
cls.enterClassContext( |
| 68 |
mock.patch("socket.gethostbyname", return_value=cls.ipv4_str) |
| 69 |
) |
| 70 |
|
| 71 |
super().setUpClass() |
| 72 |
|
| 73 |
def test_init(self): |
| 74 |
# Everything inferred from GeoIP path. |
| 75 |
g1 = GeoIP2() |
| 76 |
# Path passed explicitly. |
| 77 |
g2 = GeoIP2(settings.GEOIP_PATH, GeoIP2.MODE_AUTO) |
| 78 |
# Path provided as a string. |
| 79 |
g3 = GeoIP2(str(settings.GEOIP_PATH)) |
| 80 |
# Only passing in the location of one database. |
| 81 |
g4 = GeoIP2(settings.GEOIP_PATH / settings.GEOIP_CITY, country="") |
| 82 |
g5 = GeoIP2(settings.GEOIP_PATH / settings.GEOIP_COUNTRY, city="") |
| 83 |
for g in (g1, g2, g3, g4, g5): |
| 84 |
self.assertTrue(g._reader) |
| 85 |
|
| 86 |
# Improper parameters. |
| 87 |
bad_params = (23, "foo", 15.23) |
| 88 |
for bad in bad_params: |
| 89 |
with self.assertRaises(GeoIP2Exception): |
| 90 |
GeoIP2(cache=bad) |
| 91 |
if isinstance(bad, str): |
| 92 |
e = GeoIP2Exception |
| 93 |
else: |
| 94 |
e = TypeError |
| 95 |
with self.assertRaises(e): |
| 96 |
GeoIP2(bad, GeoIP2.MODE_AUTO) |
| 97 |
|
| 98 |
def test_no_database_file(self): |
| 99 |
invalid_path = pathlib.Path(__file__).parent.joinpath("data/invalid").resolve() |
| 100 |
msg = "Path must be a valid database or directory containing databases." |
| 101 |
with self.assertRaisesMessage(GeoIP2Exception, msg): |
| 102 |
GeoIP2(invalid_path) |
| 103 |
|
| 104 |
def test_bad_query(self): |
| 105 |
g = GeoIP2(city="<invalid>") |
| 106 |
|
| 107 |
functions = (g.city, g.geos, g.lat_lon, g.lon_lat) |
| 108 |
msg = "Invalid GeoIP city data file: " |
| 109 |
for function in functions: |
| 110 |
with self.subTest(function=function.__qualname__): |
| 111 |
with self.assertRaisesMessage(GeoIP2Exception, msg): |
| 112 |
function("example.com") |
| 113 |
|
| 114 |
functions += (g.country, g.country_code, g.country_name) |
| 115 |
values = (123, 123.45, b"", (), [], {}, set(), frozenset(), GeoIP2) |
| 116 |
msg = ( |
| 117 |
"GeoIP query must be a string or instance of IPv4Address or IPv6Address, " |
| 118 |
"not type" |
| 119 |
) |
| 120 |
for function, value in itertools.product(functions, values): |
| 121 |
with self.subTest(function=function.__qualname__, type=type(value)): |
| 122 |
with self.assertRaisesMessage(TypeError, msg): |
| 123 |
function(value) |
| 124 |
|
| 125 |
def test_country(self): |
| 126 |
g = GeoIP2(city="<invalid>") |
| 127 |
self.assertIs(g.is_city, False) |
| 128 |
self.assertIs(g.is_country, True) |
| 129 |
for query in self.query_values: |
| 130 |
with self.subTest(query=query): |
| 131 |
self.assertEqual(g.country(query), self.expected_country) |
| 132 |
self.assertEqual( |
| 133 |
g.country_code(query), self.expected_country["country_code"] |
| 134 |
) |
| 135 |
self.assertEqual( |
| 136 |
g.country_name(query), self.expected_country["country_name"] |
| 137 |
) |
| 138 |
|
| 139 |
def test_country_using_city_database(self): |
| 140 |
g = GeoIP2(country="<invalid>") |
| 141 |
self.assertIs(g.is_city, True) |
| 142 |
self.assertIs(g.is_country, False) |
| 143 |
for query in self.query_values: |
| 144 |
with self.subTest(query=query): |
| 145 |
self.assertEqual(g.country(query), self.expected_country) |
| 146 |
self.assertEqual( |
| 147 |
g.country_code(query), self.expected_country["country_code"] |
| 148 |
) |
| 149 |
self.assertEqual( |
| 150 |
g.country_name(query), self.expected_country["country_name"] |
| 151 |
) |
| 152 |
|
| 153 |
def test_city(self): |
| 154 |
g = GeoIP2(country="<invalid>") |
| 155 |
self.assertIs(g.is_city, True) |
| 156 |
self.assertIs(g.is_country, False) |
| 157 |
for query in self.query_values: |
| 158 |
with self.subTest(query=query): |
| 159 |
self.assertEqual(g.city(query), self.expected_city) |
| 160 |
|
| 161 |
geom = g.geos(query) |
| 162 |
self.assertIsInstance(geom, GEOSGeometry) |
| 163 |
self.assertEqual(geom.srid, 4326) |
| 164 |
|
| 165 |
expected_lat = self.expected_city["latitude"] |
| 166 |
expected_lon = self.expected_city["longitude"] |
| 167 |
self.assertEqual(geom.tuple, (expected_lon, expected_lat)) |
| 168 |
self.assertEqual(g.lat_lon(query), (expected_lat, expected_lon)) |
| 169 |
self.assertEqual(g.lon_lat(query), (expected_lon, expected_lat)) |
| 170 |
|
| 171 |
# Country queries should still work. |
| 172 |
self.assertEqual(g.country(query), self.expected_country) |
| 173 |
self.assertEqual( |
| 174 |
g.country_code(query), self.expected_country["country_code"] |
| 175 |
) |
| 176 |
self.assertEqual( |
| 177 |
g.country_name(query), self.expected_country["country_name"] |
| 178 |
) |
| 179 |
|
| 180 |
def test_not_found(self): |
| 181 |
g1 = GeoIP2(city="<invalid>") |
| 182 |
g2 = GeoIP2(country="<invalid>") |
| 183 |
for function, query in itertools.product( |
| 184 |
(g1.country, g2.city), ("127.0.0.1", "::1") |
| 185 |
): |
| 186 |
with self.subTest(function=function.__qualname__, query=query): |
| 187 |
msg = f"The address {query} is not in the database." |
| 188 |
with self.assertRaisesMessage(geoip2.errors.AddressNotFoundError, msg): |
| 189 |
function(query) |
| 190 |
|
| 191 |
def test_del(self): |
| 192 |
g = GeoIP2() |
| 193 |
reader = g._reader |
| 194 |
self.assertIs(reader._db_reader.closed, False) |
| 195 |
del g |
| 196 |
self.assertIs(reader._db_reader.closed, True) |
| 197 |
|
| 198 |
def test_repr(self): |
| 199 |
g = GeoIP2() |
| 200 |
m = g._metadata |
| 201 |
version = f"{m.binary_format_major_version}.{m.binary_format_minor_version}" |
| 202 |
self.assertEqual(repr(g), f"<GeoIP2 [v{version}] _path='{g._path}'>") |
| 203 |
|
| 204 |
def test_coords_deprecation_warning(self): |
| 205 |
g = GeoIP2() |
| 206 |
msg = "GeoIP2.coords() is deprecated. Use GeoIP2.lon_lat() instead." |
| 207 |
with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx: |
| 208 |
e1, e2 = g.coords(self.ipv4_str) |
| 209 |
self.assertIsInstance(e1, float) |
| 210 |
self.assertIsInstance(e2, float) |
| 211 |
self.assertEqual(ctx.filename, __file__) |
| 212 |
|
| 213 |
def test_open_deprecation_warning(self): |
| 214 |
msg = "GeoIP2.open() is deprecated. Use GeoIP2() instead." |
| 215 |
with self.assertWarnsMessage(RemovedInDjango60Warning, msg) as ctx: |
| 216 |
g = GeoIP2.open(settings.GEOIP_PATH, GeoIP2.MODE_AUTO) |
| 217 |
self.assertTrue(g._reader) |
| 218 |
self.assertEqual(ctx.filename, __file__) |
| 219 |
|
| 220 |
|
| 221 |
@skipUnless(HAS_GEOIP2, "GeoIP2 is required.") |
| 222 |
@override_settings( |
| 223 |
GEOIP_CITY="GeoIP2-City-Test.mmdb", |
| 224 |
GEOIP_COUNTRY="GeoIP2-Country-Test.mmdb", |
| 225 |
) |
| 226 |
class GeoIP2Test(GeoLite2Test): |
| 227 |
"""Non-free GeoIP2 databases are supported.""" |
| 228 |
|
| 229 |
|
| 230 |
@skipUnless(HAS_GEOIP2, "GeoIP2 is required.") |
| 231 |
@override_settings( |
| 232 |
GEOIP_CITY="dbip-city-lite-test.mmdb", |
| 233 |
GEOIP_COUNTRY="dbip-country-lite-test.mmdb", |
| 234 |
) |
| 235 |
class DBIPLiteTest(GeoLite2Test): |
| 236 |
"""DB-IP Lite databases are supported.""" |
| 237 |
|
| 238 |
expected_city = GeoLite2Test.expected_city | { |
| 239 |
"accuracy_radius": None, |
| 240 |
"city": "London (Shadwell)", |
| 241 |
"latitude": 51.5181, |
| 242 |
"longitude": -0.0714189, |
| 243 |
"postal_code": None, |
| 244 |
"region_code": None, |
| 245 |
"time_zone": None, |
| 246 |
# Kept for backward compatibility. |
| 247 |
"region": None, |
| 248 |
} |
| 249 |
|
| 250 |
|
| 251 |
@skipUnless(HAS_GEOIP2, "GeoIP2 is required.") |
| 252 |
class ErrorTest(SimpleTestCase): |
| 253 |
def test_missing_path(self): |
| 254 |
msg = "GeoIP path must be provided via parameter or the GEOIP_PATH setting." |
| 255 |
with self.settings(GEOIP_PATH=None): |
| 256 |
with self.assertRaisesMessage(GeoIP2Exception, msg): |
| 257 |
GeoIP2() |
| 258 |
|
| 259 |
def test_unsupported_database(self): |
| 260 |
msg = "Unable to handle database edition: GeoLite2-ASN" |
| 261 |
with self.settings(GEOIP_PATH=build_geoip_path("GeoLite2-ASN-Test.mmdb")): |
| 262 |
with self.assertRaisesMessage(GeoIP2Exception, msg): |
| 263 |
GeoIP2() |