def test_point_coercion(self): """ Geocoder._coerce_point_to_string """ ok = "40.74113,-73.989656" coords = (40.74113, -73.989656) geocoder = Geocoder() self.assertEqual(geocoder._coerce_point_to_string(coords), ok) # pylint: disable=W0212 self.assertEqual(geocoder._coerce_point_to_string(Point(*coords)), ok) # pylint: disable=W0212
def test_point_coercion(self): """ Geocoder._coerce_point_to_string """ ok = "40.74113,-73.989656" coords = (40.74113, -73.989656) geocoder = Geocoder() self.assertEqual(geocoder._coerce_point_to_string(coords), ok) # pylint: disable=W0212 self.assertEqual(geocoder._coerce_point_to_string( # pylint: disable=W0212 Point(*coords)), ok )
def test_ssl_context_for_old_python(self): # Before (exclusive) 2.7.9 and 3.4.3. # Keep the reference, because `geopy.compat.HTTPSHandler` will be # mocked below. orig_HTTPSHandler = geopy.compat.HTTPSHandler class HTTPSHandlerStub(geopy.compat.HTTPSHandler): def __init__(self): # No `context` arg. orig_HTTPSHandler.__init__(self) if hasattr(geopy.compat, '__warningregistry__'): # If running tests on an old Python, the warning we are going # to test might have been already issued and recorded in # the registry. Clean it up, so we could receive the warning again. del geopy.compat.__warningregistry__ with patch('geopy.compat._URLLIB_SUPPORTS_SSL_CONTEXT', geopy.compat._is_urllib_context_supported(HTTPSHandlerStub)), \ patch('geopy.compat.HTTPSHandler', HTTPSHandlerStub), \ warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') self.assertFalse(geopy.compat._URLLIB_SUPPORTS_SSL_CONTEXT) self.assertEqual(0, len(w)) Geocoder() self.assertEqual(1, len(w))
def test_ssl_context_for_newer_python(self): # From (inclusive) 2.7.9 and 3.4.3. # Keep the reference, because `geopy.compat.HTTPSHandler` will be # mocked below. orig_HTTPSHandler = geopy.compat.HTTPSHandler class HTTPSHandlerStub(geopy.compat.HTTPSHandler): def __init__(self, context=None): orig_HTTPSHandler.__init__(self) if hasattr(geopy.compat, '__warningregistry__'): # If running tests on an old Python, the warning we are going # to test might have been already issued and recorded in # the registry. Clean it up, so we could receive the warning again. del geopy.compat.__warningregistry__ with patch('geopy.compat._URLLIB_SUPPORTS_SSL_CONTEXT', geopy.compat._is_urllib_context_supported(HTTPSHandlerStub)), \ patch('geopy.compat.HTTPSHandler', HTTPSHandlerStub), \ patch.object(HTTPSHandlerStub, '__init__', autospec=True, side_effect=HTTPSHandlerStub.__init__ ) as mock_https_handler_init, \ warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') self.assertTrue(geopy.compat._URLLIB_SUPPORTS_SSL_CONTEXT) for ssl_context in (None, sentinel.some_ssl_context): mock_https_handler_init.reset_mock() Geocoder(ssl_context=ssl_context) args, kwargs = mock_https_handler_init.call_args self.assertIs(kwargs['context'], ssl_context) self.assertEqual(0, len(w))
def test_deprecated_format_string(self): format_string = '%s Los Angeles, CA USA' with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') geocoder = Geocoder(format_string=format_string, ) self.assertEqual(format_string, geocoder.format_string) self.assertEqual(1, len(w))
def test_user_agent_default(self): with patch('geopy.geocoders.base.DEFAULT_USER_AGENT', 'mocked_user_agent/0.0.0'): self.assertEqual(geopy.geocoders.base.DEFAULT_USER_AGENT, 'mocked_user_agent/0.0.0') geocoder = Geocoder() self.assertEqual(geocoder.headers['User-Agent'], 'mocked_user_agent/0.0.0')
def geocode(geocoder: Geocoder, location: str) -> Union[Tuple[float, float], Tuple[None, None]]: try: loc = geocoder.geocode(location) except GeopyError as e: return None, None else: lat = loc.latitude if loc else None lon = loc.longitude if loc else None return lat, lon
async def test_synchronize_decorator_sync_exception(adapter_factory): geocoder = Geocoder(adapter_factory=adapter_factory) @_synchronized def f(self, one, *, two): raise RuntimeError("test") with pytest.raises(RuntimeError): res = f(geocoder, 1, two=2) if adapter_factory is DummyAsyncAdapter: await res
async def test_synchronize_decorator_async_exception(): geocoder = Geocoder(adapter_factory=DummyAsyncAdapter) @_synchronized def f(self, one, *, two): async def coro(): raise RuntimeError("test") return coro() with pytest.raises(RuntimeError): await f(geocoder, 1, two=2)
def test_init(self): """ Geocoder() """ format_string = '%s Los Angeles, CA USA' scheme = 'http' timeout = DEFAULT_TIMEOUT + 1 proxies = {'https': '192.0.2.0'} geocoder = Geocoder(format_string=format_string, scheme=scheme, timeout=timeout, proxies=proxies) for attr in ('format_string', 'scheme', 'timeout', 'proxies'): self.assertEqual(locals()[attr], getattr(geocoder, attr))
async def test_synchronize_decorator_async_simple(): geocoder = Geocoder(adapter_factory=DummyAsyncAdapter) calls = [] @_synchronized def f(self, one, *, two): async def coro(): calls.append((one, two)) return 42 return coro() assert 42 == await f(geocoder, 1, two=2) assert calls == [(1, 2)]
async def test_synchronize_decorator_sync_simple(adapter_factory): geocoder = Geocoder(adapter_factory=adapter_factory) calls = [] @_synchronized def f(self, one, *, two): calls.append((one, two)) return 42 res = f(geocoder, 1, two=2) if adapter_factory is DummyAsyncAdapter: res = await res assert 42 == res assert calls == [(1, 2)]
def test_ssl_context(self): with ExitStack() as stack: mock_adapter = stack.enter_context( patch.object( geopy.geocoders.base.options, 'default_adapter_factory', return_value=DummySyncAdapter(proxies=None, ssl_context=None), )) for ssl_context in (None, sentinel.some_ssl_context): Geocoder(ssl_context=ssl_context) args, kwargs = mock_adapter.call_args assert kwargs['ssl_context'] is ssl_context
def test_init_with_defaults(self): attr_to_option = { 'scheme': 'default_scheme', 'timeout': 'default_timeout', 'proxies': 'default_proxies', 'ssl_context': 'default_ssl_context', } geocoder = Geocoder() for geocoder_attr, options_attr in attr_to_option.items(): assert (getattr(geopy.geocoders.options, options_attr) == getattr(geocoder, geocoder_attr)) assert (geopy.geocoders.options.default_user_agent == geocoder.headers['User-Agent']) assert DummySyncAdapter is type(geocoder.adapter) # noqa
def test_init_with_defaults(self): attr_to_option = { 'format_string': 'default_format_string', 'scheme': 'default_scheme', 'timeout': 'default_timeout', 'proxies': 'default_proxies', 'ssl_context': 'default_ssl_context', } geocoder = Geocoder() for geocoder_attr, options_attr in attr_to_option.items(): self.assertEqual(getattr(geopy.geocoders.options, options_attr), getattr(geocoder, geocoder_attr)) self.assertEqual(geopy.geocoders.options.default_user_agent, geocoder.headers['User-Agent'])
def test_init_with_args(self): scheme = 'http' timeout = 942 proxies = {'https': '192.0.2.0'} user_agent = 'test app' ssl_context = sentinel.some_ssl_context geocoder = Geocoder( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, ) for attr in ('scheme', 'timeout', 'proxies', 'ssl_context'): self.assertEqual(locals()[attr], getattr(geocoder, attr)) self.assertEqual(user_agent, geocoder.headers['User-Agent'])
def test_call_geocoder_timeout(self): url = 'spam://ham/eggs' g = Geocoder(adapter_factory=DummySyncAdapter) assert g.timeout == 12 with ExitStack() as stack: mock_get_json = stack.enter_context( patch.object(g.adapter, 'get_json')) g._call_geocoder(url, lambda res: res) args, kwargs = mock_get_json.call_args assert kwargs['timeout'] == 12 g._call_geocoder(url, lambda res: res, timeout=7) args, kwargs = mock_get_json.call_args assert kwargs['timeout'] == 7 g._call_geocoder(url, lambda res: res, timeout=None) args, kwargs = mock_get_json.call_args assert kwargs['timeout'] is None
def test_init_with_args(self): scheme = 'http' timeout = 942 proxies = {'https': '192.0.2.0'} user_agent = 'test app' ssl_context = sentinel.some_ssl_context adapter = DummySyncAdapter(proxies=None, ssl_context=None) geocoder = Geocoder( scheme=scheme, timeout=timeout, proxies=proxies, user_agent=user_agent, ssl_context=ssl_context, adapter_factory=lambda **kw: adapter, ) for attr in ('scheme', 'timeout', 'proxies', 'ssl_context'): assert locals()[attr] == getattr(geocoder, attr) assert user_agent == geocoder.headers['User-Agent'] assert adapter is geocoder.adapter
def test_call_geocoder_timeout(self): url = 'spam://ham/eggs' g = Geocoder() self.assertEqual(g.timeout, 12) # Suppress another (unrelated) warning when running tests on an old Python. with patch('geopy.compat._URLLIB_SUPPORTS_SSL_CONTEXT', True), \ patch.object(g, 'urlopen') as mock_urlopen: g._call_geocoder(url, raw=True) args, kwargs = mock_urlopen.call_args self.assertEqual(kwargs['timeout'], 12) g._call_geocoder(url, timeout=7, raw=True) args, kwargs = mock_urlopen.call_args self.assertEqual(kwargs['timeout'], 7) with warnings.catch_warnings(record=True) as w: warnings.simplefilter('always') g._call_geocoder(url, timeout=None, raw=True) args, kwargs = mock_urlopen.call_args self.assertEqual(kwargs['timeout'], 12) self.assertEqual(1, len(w))
def geocode(q: str = Query(..., description="The location you want to geocode"), geocode_service: Geocoder = Depends(build_geocode_service)): try: location = geocode_service.geocode(q) except GeocoderQueryError as e: raise HTTPException(status_code=400, detail=str(e)) except GeopyError as e: raise HTTPException(status_code=500, detail=str(e)) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) if location is None: raise HTTPException( status_code=400, detail="No result found for query \"{}\"".format(q)) return { 'address': location.address, 'lat': location.latitude, 'lng': location.longitude, 'raw': location.raw }
def test_user_agent_custom(self): geocoder = Geocoder(user_agent='my_user_agent/1.0') assert geocoder.headers['User-Agent'] == 'my_user_agent/1.0'
def test_user_agent_custom(self): geocoder = Geocoder(user_agent='my_user_agent/1.0') self.assertEqual(geocoder.headers['User-Agent'], 'my_user_agent/1.0')
def test_user_agent_default(self): geocoder = Geocoder() self.assertEqual(geocoder.headers['User-Agent'], 'mocked_user_agent/0.0.0')
def test_init_with_none_overrides_default(self): geocoder = Geocoder(proxies=None, timeout=None, ssl_context=None) self.assertIsNone(geocoder.proxies) self.assertIsNone(geocoder.timeout) self.assertIsNone(geocoder.ssl_context)
def setUp(self): self.method = Geocoder()._coerce_point_to_string
def setUpClass(cls): cls.geocoder = Geocoder()
def setUp(self): self.method = Geocoder()._format_bounding_box
def __init__(self, **kwargs): Geocoder.__init__(self, **kwargs) self.cached = pickle.load(open(self.cache, 'rb')) if os.path.exists(self.cache) else {}
def setUpClass(cls): cls.geocoder = Geocoder() cls.coordinates = (40.74113, -73.989656) cls.coordinates_str = "40.74113,-73.989656" cls.coordinates_address = "175 5th Avenue, NYC, USA"
def test_init_with_none_overrides_default(self): geocoder = Geocoder(proxies=None, timeout=None, ssl_context=None) assert geocoder.proxies is None assert geocoder.timeout is None assert geocoder.ssl_context is None
def test_user_agent_default(self): geocoder = Geocoder() assert geocoder.headers['User-Agent'] == 'mocked_user_agent/0.0.0'