class Test_country_code(asynctest.TestCase): def setUp(self): self.geoip = GeoIP() self.geoip.enabled = True self.mock_maxminddb = mock.patch.object(self.geoip, '_db').start() self.mock_download_db = mock.patch(__name__ + '.GeoIP._download_db', asynctest.CoroutineMock()).start() self.mock_load = mock.patch(__name__ + '.GeoIP.load', asynctest.CoroutineMock()).start() def tearDown(self): mock.patch.stopall() def test_not_enabled(self): self.geoip.enabled = False self.assertIs(self.geoip.country_code('asdf'), None) def test_cache(self): self.geoip._lookup_cache = {'1.2.3.4': ('AB', time.time())} self.assertEqual(self.geoip.country_code('1.2.3.4'), 'AB') self.mock_maxminddb.get.assert_not_called() self.mock_load.assert_not_called() def test_maxminddb_raises_InvalidDatabaseError(self): self.mock_maxminddb.get.side_effect = maxminddb.InvalidDatabaseError() self.assertEqual(self.geoip.country_code('1.2.3.4'), None) self.mock_maxminddb.get.assert_called_once_with('1.2.3.4') self.mock_load.assert_called_once_with(force_update=True, ignore_errors=True) def test_maxminddb_raises_UnicodeDecodeError(self): self.mock_maxminddb.get.side_effect = UnicodeDecodeError( 'mockcodec', b'', 0, 0, 'Oh no!') self.assertEqual(self.geoip.country_code('1.2.3.4'), None) self.mock_maxminddb.get.assert_called_once_with('1.2.3.4') self.mock_load.assert_called_once_with(force_update=True, ignore_errors=True) def test_maxminddb_returns_non_dictinary(self): self.mock_maxminddb.get.return_value = 'not a dict' self.assertEqual(self.geoip.country_code('1.2.3.4'), None) self.mock_maxminddb.get.assert_called_once_with('1.2.3.4') self.mock_load.assert_called_once_with(force_update=True, ignore_errors=True) def test_country_key_maps_to_non_dictionary(self): self.mock_maxminddb.get.return_value = {'country': 'not a dict'} self.assertEqual(self.geoip.country_code('1.2.3.4'), None) self.mock_maxminddb.get.assert_called_once_with('1.2.3.4') self.mock_load.assert_called_once_with(force_update=True, ignore_errors=True)
class TestGeoIPBase(asynctest.TestCase): def setUp(self): class GeoIP(GeoIPBase): pass self.geoip = GeoIP() def test_cachedir(self): self.assertEqual(self.geoip.cachedir, '') self.geoip.cachedir = '/foo/bar/baz/' self.assertEqual(self.geoip.cachedir, '/foo/bar/baz/') def test_enabled(self): self.assertEqual(self.geoip.enabled, False) self.geoip.enabled = 'yes' self.assertEqual(self.geoip.enabled, True) async def test_load(self): self.assertEqual(await self.geoip.load(), None) def test_country_code(self): self.assertEqual(self.geoip.country_code('1.2.3.4'), None)