diff --git a/Pipfile b/Pipfile new file mode 100644 index 00000000..25405323 --- /dev/null +++ b/Pipfile @@ -0,0 +1,11 @@ +[[source]] +name = "pypi" +verify_ssl = true +url = "https://pypi.org/simple" + +[dev-packages] +nose = "*" +responses = "==0.3" + +[packages] +tox = "*" diff --git a/Pipfile.lock b/Pipfile.lock new file mode 100644 index 00000000..73c5d5dc --- /dev/null +++ b/Pipfile.lock @@ -0,0 +1,129 @@ +{ + "_meta": { + "hash": { + "sha256": "c680e82b5ac6d45670e63818b448528a04422dcaba192bdac4c9d6c68ee290df" + }, + "pipfile-spec": 6, + "requires": {}, + "sources": [ + { + "name": "pypi", + "url": "https://pypi.org/simple", + "verify_ssl": true + } + ] + }, + "default": { + "pluggy": { + "hashes": [ + "sha256:7f8ae7f5bdf75671a718d2daf0a64b7885f74510bcd98b1a0bb420eb9a9d0cff", + "sha256:d345c8fe681115900d6da8d048ba67c25df42973bda370783cd58826442dcd7c", + "sha256:e160a7fcf25762bb60efc7e171d4497ff1d8d2d75a3d0df7a21b76821ecbf5c5" + ], + "version": "==0.6.0" + }, + "py": { + "hashes": [ + "sha256:29c9fab495d7528e80ba1e343b958684f4ace687327e6f789a94bf3d1915f881", + "sha256:983f77f3331356039fdd792e9220b7b8ee1aa6bd2b25f567a963ff1de5a64f6a" + ], + "version": "==1.5.3" + }, + "six": { + "hashes": [ + "sha256:70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9", + "sha256:832dc0e10feb1aa2c68dcc57dbb658f1c7e65b9b61af69048abc87a2db00a0eb" + ], + "version": "==1.11.0" + }, + "tox": { + "hashes": [ + "sha256:96efa09710a3daeeb845561ebbe1497641d9cef2ee0aea30db6969058b2bda2f", + "sha256:9ee7de958a43806402a38c0d2aa07fa8553f4d2c20a15b140e9f771c2afeade0" + ], + "index": "pypi", + "version": "==3.0.0" + }, + "virtualenv": { + "hashes": [ + "sha256:2ce32cd126117ce2c539f0134eb89de91a8413a29baac49cbab3eb50e2026669", + "sha256:ca07b4c0b54e14a91af9f34d0919790b016923d157afda5efdde55c96718f752" + ], + "version": "==16.0.0" + } + }, + "develop": { + "certifi": { + "hashes": [ + "sha256:13e698f54293db9f89122b0581843a782ad0934a4fe0172d2a980ba77fc61bb7", + "sha256:9fa520c1bacfb634fa7af20a76bcbd3d5fb390481724c597da32c719a7dca4b0" + ], + "version": "==2018.4.16" + }, + "chardet": { + "hashes": [ + "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae", + "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691" + ], + "version": "==3.0.4" + }, + "idna": { + "hashes": [ + "sha256:156a6814fb5ac1fc6850fb002e0852d56c0c8d2531923a51032d1b70760e186e", + "sha256:684a38a6f903c1d71d6d5fac066b58d7768af4de2b832e426ec79c30daa94a16" + ], + "version": "==2.7" + }, + "mock": { + "hashes": [ + "sha256:5ce3c71c5545b472da17b72268978914d0252980348636840bd34a00b5cc96c1", + "sha256:b158b6df76edd239b8208d481dc46b6afd45a846b7812ff0ce58971cf5bc8bba" + ], + "version": "==2.0.0" + }, + "nose": { + "hashes": [ + "sha256:9ff7c6cc443f8c51994b34a667bbcf45afd6d945be7477b52e97516fd17c53ac", + "sha256:dadcddc0aefbf99eea214e0f1232b94f2fa9bd98fa8353711dacb112bfcbbb2a", + "sha256:f1bffef9cbc82628f6e7d7b40d7e255aefaa1adb6a1b1d26c69a8b79e6208a98" + ], + "index": "pypi", + "version": "==1.3.7" + }, + "pbr": { + "hashes": [ + "sha256:3747c6f017f2dc099986c325239661948f9f5176f6880d9fdef164cb664cd665", + "sha256:a9c27eb8f0e24e786e544b2dbaedb729c9d8546342b5a6818d8eda098ad4340d" + ], + "version": "==4.0.4" + }, + "requests": { + "hashes": [ + "sha256:63b52e3c866428a224f97cab011de738c36aec0185aa91cfacd418b5d58911d1", + "sha256:ec22d826a36ed72a7358ff3fe56cbd4ba69dd7a6718ffd450ff0e9df7a47ce6a" + ], + "version": "==2.19.1" + }, + "responses": { + "hashes": [ + "sha256:6c5eb915bcf763b677b8e51cdb68c8474127a9b60e49e6e240b05ec5e449c43b" + ], + "index": "pypi", + "version": "==0.3" + }, + "six": { + "hashes": [ + "sha256:70e8a77beed4562e7f14fe23a786b54f6296e34344c23bc42f07b15018ff98e9", + "sha256:832dc0e10feb1aa2c68dcc57dbb658f1c7e65b9b61af69048abc87a2db00a0eb" + ], + "version": "==1.11.0" + }, + "urllib3": { + "hashes": [ + "sha256:a68ac5e15e76e7e5dd2b8f94007233e01effe3e50e8daddf69acfd81cb686baf", + "sha256:b5725a0bd4ba422ab0e66e89e030c806576753ea3ee08554382c14e685d117b5" + ], + "version": "==1.23" + } + } +} diff --git a/docs/conf.py b/docs/conf.py index 19cdfef5..1a7babca 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -16,33 +16,34 @@ # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. -sys.path.insert(0, os.path.abspath('..')) +sys.path.insert(0, os.path.abspath("..")) # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. -#needs_sphinx = '1.0' +# needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.autodoc'] +extensions = ["sphinx.ext.autodoc"] # Add any paths that contain templates here, relative to this directory. -templates_path = ['_templates'] +templates_path = ["_templates"] # The suffix of source filenames. -source_suffix = '.rst' +source_suffix = ".rst" # The encoding of source files. -#source_encoding = 'utf-8-sig' +# source_encoding = 'utf-8-sig' # The master toctree document. -master_doc = 'index' +master_doc = "index" # General information about the project. from datetime import datetime -project = u'Python Client for Google Maps Services' -copyright = u'%s, Google Inc.' % datetime.now().year + +project = u"Python Client for Google Maps Services" +copyright = u"%s, Google Inc." % datetime.now().year # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -50,74 +51,75 @@ # # The short X.Y version. from googlemaps import __version__ + version = __version__ # The full version, including alpha/beta/rc tags. release = version # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. -#language = None +# language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: -#today = '' +# today = '' # Else, today_fmt is used as the format for a strftime call. -#today_fmt = '%B %d, %Y' +# today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ['_build'] +exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all documents. -#default_role = None +# default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. -#add_function_parentheses = True +# add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). -#add_module_names = True +# add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. -#show_authors = False +# show_authors = False # The name of the Pygments (syntax highlighting) style to use. -pygments_style = 'sphinx' +pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. -#modindex_common_prefix = [] +# modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. -html_theme = 'default' +html_theme = "default" # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. -#html_theme_options = {} +# html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. -#html_theme_path = [] +# html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". -#html_title = None +# html_title = None # A shorter title for the navigation bar. Default is the same as html_title. -#html_short_title = None +# html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. -#html_logo = None +# html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. -#html_favicon = None +# html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, @@ -126,47 +128,47 @@ # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. -#html_last_updated_fmt = '%b %d, %Y' +# html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. -#html_use_smartypants = True +# html_use_smartypants = True # Custom sidebar templates, maps document names to template names. -#html_sidebars = {} +# html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. -#html_additional_pages = {} +# html_additional_pages = {} # If false, no module index is generated. -#html_domain_indices = True +# html_domain_indices = True # If false, no index is generated. -#html_use_index = True +# html_use_index = True # If true, the index is split into individual pages for each letter. -#html_split_index = False +# html_split_index = False # If true, links to the reST sources are added to the pages. -#html_show_sourcelink = True +# html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. -#html_show_sphinx = True +# html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. -#html_show_copyright = True +# html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. -#html_use_opensearch = '' +# html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). -#html_file_suffix = None +# html_file_suffix = None # Output file base name for HTML help builder. -htmlhelp_basename = 'MapsAPIdoc' +htmlhelp_basename = "MapsAPIdoc" # Ensure class constructors are added to the docs. -autoclass_content = 'both' +autoclass_content = "both" diff --git a/googlemaps/client.py b/googlemaps/client.py index 11d15071..e72ee5fb 100644 --- a/googlemaps/client.py +++ b/googlemaps/client.py @@ -34,9 +34,9 @@ import googlemaps -try: # Python 3 +try: # Python 3 from urllib.parse import urlencode -except ImportError: # Python 2 +except ImportError: # Python 2 from urllib import urlencode @@ -45,14 +45,24 @@ _RETRIABLE_STATUSES = set([500, 503, 504]) + class Client(object): """Performs requests to the Google Maps API web services.""" - def __init__(self, key=None, client_id=None, client_secret=None, - timeout=None, connect_timeout=None, read_timeout=None, - retry_timeout=60, requests_kwargs=None, - queries_per_second=50, channel=None, - retry_over_query_limit=True): + def __init__( + self, + key=None, + client_id=None, + client_secret=None, + timeout=None, + connect_timeout=None, + read_timeout=None, + retry_timeout=60, + requests_kwargs=None, + queries_per_second=50, + channel=None, + retry_over_query_limit=True, + ): """ :param key: Maps API key. Required, unless "client_id" and "client_secret" are set. @@ -112,34 +122,41 @@ def __init__(self, key=None, client_id=None, client_secret=None, """ if not key and not (client_secret and client_id): - raise ValueError("Must provide API key or enterprise credentials " - "when creating client.") + raise ValueError( + "Must provide API key or enterprise credentials " + "when creating client." + ) if key and not key.startswith("AIza"): raise ValueError("Invalid API key provided.") if channel: if not client_id: - raise ValueError("The channel argument must be used with a " - "client ID") + raise ValueError( + "The channel argument must be used with a " "client ID" + ) if not re.match("^[a-zA-Z0-9._-]*$", channel): - raise ValueError("The channel argument must be an ASCII " + raise ValueError( + "The channel argument must be an ASCII " "alphanumeric string. The period (.), underscore (_)" - "and hyphen (-) characters are allowed.") + "and hyphen (-) characters are allowed." + ) self.session = requests.Session() self.key = key if timeout and (connect_timeout or read_timeout): - raise ValueError("Specify either timeout, or connect_timeout " - "and read_timeout") + raise ValueError( + "Specify either timeout, or connect_timeout " "and read_timeout" + ) if connect_timeout and read_timeout: # Check that the version of requests is >= 2.4.0 chunks = requests.__version__.split(".") if int(chunks[0]) < 2 or (int(chunks[0]) == 2 and int(chunks[1]) < 4): - raise NotImplementedError("Connect/Read timeouts require " - "requests v2.4.0 or higher") + raise NotImplementedError( + "Connect/Read timeouts require " "requests v2.4.0 or higher" + ) self.timeout = (connect_timeout, read_timeout) else: self.timeout = timeout @@ -149,19 +166,30 @@ def __init__(self, key=None, client_id=None, client_secret=None, self.channel = channel self.retry_timeout = timedelta(seconds=retry_timeout) self.requests_kwargs = requests_kwargs or {} - self.requests_kwargs.update({ - "headers": {"User-Agent": _USER_AGENT}, - "timeout": self.timeout, - "verify": True, # NOTE(cbro): verify SSL certs. - }) + self.requests_kwargs.update( + { + "headers": {"User-Agent": _USER_AGENT}, + "timeout": self.timeout, + "verify": True, # NOTE(cbro): verify SSL certs. + } + ) self.queries_per_second = queries_per_second self.retry_over_query_limit = retry_over_query_limit self.sent_times = collections.deque("", queries_per_second) - def _request(self, url, params, first_request_time=None, retry_counter=0, - base_url=_DEFAULT_BASE_URL, accepts_clientid=True, - extract_body=None, requests_kwargs=None, post_json=None): + def _request( + self, + url, + params, + first_request_time=None, + retry_counter=0, + base_url=_DEFAULT_BASE_URL, + accepts_clientid=True, + extract_body=None, + requests_kwargs=None, + post_json=None, + ): """Performs HTTP GET/POST with credentials, returning the body as JSON. @@ -232,8 +260,7 @@ def _request(self, url, params, first_request_time=None, retry_counter=0, final_requests_kwargs["json"] = post_json try: - response = requests_method(base_url + authed_url, - **final_requests_kwargs) + response = requests_method(base_url + authed_url, **final_requests_kwargs) except requests.exceptions.Timeout: raise googlemaps.exceptions.Timeout() except Exception as e: @@ -241,9 +268,17 @@ def _request(self, url, params, first_request_time=None, retry_counter=0, if response.status_code in _RETRIABLE_STATUSES: # Retry request. - return self._request(url, params, first_request_time, - retry_counter + 1, base_url, accepts_clientid, - extract_body, requests_kwargs, post_json) + return self._request( + url, + params, + first_request_time, + retry_counter + 1, + base_url, + accepts_clientid, + extract_body, + requests_kwargs, + post_json, + ) # Check if the time of the nth previous query (where n is # queries_per_second) is under a second ago - if so, sleep for @@ -261,13 +296,24 @@ def _request(self, url, params, first_request_time=None, retry_counter=0, self.sent_times.append(time.time()) return result except googlemaps.exceptions._RetriableRequest as e: - if isinstance(e, googlemaps.exceptions._OverQueryLimit) and not self.retry_over_query_limit: + if ( + isinstance(e, googlemaps.exceptions._OverQueryLimit) + and not self.retry_over_query_limit + ): raise # Retry request. - return self._request(url, params, first_request_time, - retry_counter + 1, base_url, accepts_clientid, - extract_body, requests_kwargs, post_json) + return self._request( + url, + params, + first_request_time, + retry_counter + 1, + base_url, + accepts_clientid, + extract_body, + requests_kwargs, + post_json, + ) def _get(self, *args, **kwargs): # Backwards compatibility. return self._request(*args, **kwargs) @@ -284,10 +330,10 @@ def _get_body(self, response): if api_status == "OVER_QUERY_LIMIT": raise googlemaps.exceptions._OverQueryLimit( - api_status, body.get("error_message")) + api_status, body.get("error_message") + ) - raise googlemaps.exceptions.ApiError(api_status, - body.get("error_message")) + raise googlemaps.exceptions.ApiError(api_status, body.get("error_message")) def _generate_auth_url(self, path, params, accepts_clientid): """Returns the path and query string portion of the request URL, first @@ -308,7 +354,7 @@ def _generate_auth_url(self, path, params, accepts_clientid): if type(params) is dict: params = sorted(dict(extra_params, **params).items()) else: - params = sorted(extra_params.items()) + params[:] # Take a copy. + params = sorted(extra_params.items()) + params[:] # Take a copy. if accepts_clientid and self.client_id and self.client_secret: if self.channel: @@ -323,8 +369,10 @@ def _generate_auth_url(self, path, params, accepts_clientid): params.append(("key", self.key)) return path + "?" + urlencode_params(params) - raise ValueError("Must provide API key for this API. It does not accept " - "enterprise credentials.") + raise ValueError( + "Must provide API key for this API. It does not accept " + "enterprise credentials." + ) from googlemaps.directions import directions @@ -358,6 +406,7 @@ def make_api_method(func): Please note that this is an unsupported feature for advanced use only. It's also currently incompatibile with multiple threads, see GH #160. """ + @functools.wraps(func) def wrapper(*args, **kwargs): args[0]._extra_params = kwargs.pop("extra_params", None) @@ -367,6 +416,7 @@ def wrapper(*args, **kwargs): except AttributeError: pass return result + return wrapper @@ -402,11 +452,11 @@ def sign_hmac(secret, payload): :rtype: string """ - payload = payload.encode('ascii', 'strict') - secret = secret.encode('ascii', 'strict') + payload = payload.encode("ascii", "strict") + secret = secret.encode("ascii", "strict") sig = hmac.new(base64.urlsafe_b64decode(secret), payload, hashlib.sha1) out = base64.urlsafe_b64encode(sig.digest()) - return out.decode('utf-8') + return out.decode("utf-8") def urlencode_params(params): @@ -434,14 +484,16 @@ def urlencode_params(params): def normalize_for_urlencode(value): """(Python 2) Converts the value to a `str` (raw bytes).""" if isinstance(value, unicode): - return value.encode('utf8') + return value.encode("utf8") if isinstance(value, str): return value return normalize_for_urlencode(str(value)) + except NameError: + def normalize_for_urlencode(value): """(Python 3) No-op.""" # urlencode in Python 3 handles all the types we are passing it. diff --git a/googlemaps/convert.py b/googlemaps/convert.py index a20e3a32..73579cd2 100644 --- a/googlemaps/convert.py +++ b/googlemaps/convert.py @@ -103,8 +103,8 @@ def normalize_lat_lng(arg): return arg[0], arg[1] raise TypeError( - "Expected a lat/lng dict or tuple, " - "but got %s" % type(arg).__name__) + "Expected a lat/lng dict or tuple, " "but got %s" % type(arg).__name__ + ) def location_list(arg): @@ -157,11 +157,13 @@ def _is_list(arg): """Checks if arg is list-like. This excludes strings and dicts.""" if isinstance(arg, dict): return False - if isinstance(arg, str): # Python 3-only, as str has __iter__ + if isinstance(arg, str): # Python 3-only, as str has __iter__ return False - return (not _has_method(arg, "strip") - and _has_method(arg, "__getitem__") - or _has_method(arg, "__iter__")) + return ( + not _has_method(arg, "strip") + and _has_method(arg, "__getitem__") + or _has_method(arg, "__iter__") + ) def is_string(val): @@ -233,8 +235,8 @@ def expand(arg): return "|".join(sorted(expand(arg))) raise TypeError( - "Expected a dict for components, " - "but got %s" % type(arg).__name__) + "Expected a dict for components, " "but got %s" % type(arg).__name__ + ) def bounds(arg): @@ -269,12 +271,12 @@ def bounds(arg): return arg elif isinstance(arg, dict): if "southwest" in arg and "northeast" in arg: - return "%s|%s" % (latlng(arg["southwest"]), - latlng(arg["northeast"])) + return "%s|%s" % (latlng(arg["southwest"]), latlng(arg["northeast"])) raise TypeError( "Expected a bounds (southwest/northeast) dict, " - "but got %s" % type(arg).__name__) + "but got %s" % type(arg).__name__ + ) def decode_polyline(polyline): @@ -343,9 +345,9 @@ def encode_polyline(points): for v in [d_lat, d_lng]: v = ~(v << 1) if v < 0 else v << 1 while v >= 0x20: - result += (chr((0x20 | (v & 0x1f)) + 63)) + result += chr((0x20 | (v & 0x1f)) + 63) v >>= 5 - result += (chr(v + 63)) + result += chr(v + 63) last_lat = lat last_lng = lng diff --git a/googlemaps/directions.py b/googlemaps/directions.py index f1713dfb..bee2a004 100644 --- a/googlemaps/directions.py +++ b/googlemaps/directions.py @@ -20,11 +20,24 @@ from googlemaps import convert -def directions(client, origin, destination, - mode=None, waypoints=None, alternatives=False, avoid=None, - language=None, units=None, region=None, departure_time=None, - arrival_time=None, optimize_waypoints=False, transit_mode=None, - transit_routing_preference=None, traffic_model=None): +def directions( + client, + origin, + destination, + mode=None, + waypoints=None, + alternatives=False, + avoid=None, + language=None, + units=None, + region=None, + departure_time=None, + arrival_time=None, + optimize_waypoints=False, + transit_mode=None, + transit_routing_preference=None, + traffic_model=None, +): """Get directions between an origin point and a destination point. :param origin: The address or latitude/longitude value from which you wish @@ -98,7 +111,7 @@ def directions(client, origin, destination, params = { "origin": convert.latlng(origin), - "destination": convert.latlng(destination) + "destination": convert.latlng(destination), } if mode: @@ -136,8 +149,7 @@ def directions(client, origin, destination, params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: - raise ValueError("Should not specify both departure_time and" - "arrival_time.") + raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) diff --git a/googlemaps/distance_matrix.py b/googlemaps/distance_matrix.py index f6a85e8c..b61505e2 100755 --- a/googlemaps/distance_matrix.py +++ b/googlemaps/distance_matrix.py @@ -21,10 +21,21 @@ from googlemaps.convert import as_list -def distance_matrix(client, origins, destinations, - mode=None, language=None, avoid=None, units=None, - departure_time=None, arrival_time=None, transit_mode=None, - transit_routing_preference=None, traffic_model=None, region=None): +def distance_matrix( + client, + origins, + destinations, + mode=None, + language=None, + avoid=None, + units=None, + departure_time=None, + arrival_time=None, + transit_mode=None, + transit_routing_preference=None, + traffic_model=None, + region=None, +): """ Gets travel distance and time for a matrix of origins and destinations. :param origins: One or more locations and/or latitude/longitude values, @@ -92,7 +103,7 @@ def distance_matrix(client, origins, destinations, params = { "origins": convert.location_list(origins), - "destinations": convert.location_list(destinations) + "destinations": convert.location_list(destinations), } if mode: @@ -120,8 +131,7 @@ def distance_matrix(client, origins, destinations, params["arrival_time"] = convert.time(arrival_time) if departure_time and arrival_time: - raise ValueError("Should not specify both departure_time and" - "arrival_time.") + raise ValueError("Should not specify both departure_time and" "arrival_time.") if transit_mode: params["transit_mode"] = convert.join_list("|", transit_mode) diff --git a/googlemaps/elevation.py b/googlemaps/elevation.py index 8eb6b14a..4b0beba7 100644 --- a/googlemaps/elevation.py +++ b/googlemaps/elevation.py @@ -57,9 +57,6 @@ def elevation_along_path(client, path, samples): else: path = convert.shortest_path(path) - params = { - "path": path, - "samples": samples - } + params = {"path": path, "samples": samples} return client._request("/maps/api/elevation/json", params).get("results", []) diff --git a/googlemaps/exceptions.py b/googlemaps/exceptions.py index 679b26c3..da2fdd91 100644 --- a/googlemaps/exceptions.py +++ b/googlemaps/exceptions.py @@ -19,8 +19,10 @@ Defines exceptions that are thrown by the Google Maps client. """ + class ApiError(Exception): """Represents an exception returned by the remote API.""" + def __init__(self, status, message=None): self.status = status self.message = message @@ -31,6 +33,7 @@ def __str__(self): else: return "%s (%s)" % (self.status, self.message) + class TransportError(Exception): """Something went wrong while trying to execute the request.""" @@ -43,26 +46,34 @@ def __str__(self): return "An unknown error occurred." + class HTTPError(TransportError): """An unexpected HTTP error occurred.""" + def __init__(self, status_code): self.status_code = status_code def __str__(self): return "HTTP Error: %d" % self.status_code + class Timeout(Exception): """The request timed out.""" + pass + class _RetriableRequest(Exception): """Signifies that the request can be retried.""" + pass + class _OverQueryLimit(ApiError, _RetriableRequest): """Signifies that the request failed because the client exceeded its query rate limit. Normally we treat this as a retriable condition, but we allow the calling code to specify that these requests should not be retried. """ + pass diff --git a/googlemaps/geocoding.py b/googlemaps/geocoding.py index a2913cf9..c46a9a70 100644 --- a/googlemaps/geocoding.py +++ b/googlemaps/geocoding.py @@ -19,8 +19,9 @@ from googlemaps import convert -def geocode(client, address=None, components=None, bounds=None, region=None, - language=None): +def geocode( + client, address=None, components=None, bounds=None, region=None, language=None +): """ Geocoding is the process of converting addresses (like ``"1600 Amphitheatre Parkway, Mountain View, CA"``) into geographic @@ -68,8 +69,9 @@ def geocode(client, address=None, components=None, bounds=None, region=None, return client._request("/maps/api/geocode/json", params).get("results", []) -def reverse_geocode(client, latlng, result_type=None, location_type=None, - language=None): +def reverse_geocode( + client, latlng, result_type=None, location_type=None, language=None +): """ Reverse geocoding is the process of converting geographic coordinates into a human-readable address. @@ -92,7 +94,7 @@ def reverse_geocode(client, latlng, result_type=None, location_type=None, # Check if latlng param is a place_id string. # place_id strings do not contain commas; latlng strings do. - if convert.is_string(latlng) and ',' not in latlng: + if convert.is_string(latlng) and "," not in latlng: params = {"place_id": latlng} else: params = {"latlng": convert.latlng(latlng)} diff --git a/googlemaps/geolocation.py b/googlemaps/geolocation.py index c8db15ec..c2a98a52 100644 --- a/googlemaps/geolocation.py +++ b/googlemaps/geolocation.py @@ -42,9 +42,16 @@ def _geolocation_extract(response): raise exceptions.ApiError(response.status_code, error) -def geolocate(client, home_mobile_country_code=None, - home_mobile_network_code=None, radio_type=None, carrier=None, - consider_ip=None, cell_towers=None, wifi_access_points=None): +def geolocate( + client, + home_mobile_country_code=None, + home_mobile_network_code=None, + radio_type=None, + carrier=None, + consider_ip=None, + cell_towers=None, + wifi_access_points=None, +): """ The Google Maps Geolocation API returns a location and accuracy radius based on information about cell towers and WiFi nodes given. @@ -101,7 +108,10 @@ def geolocate(client, home_mobile_country_code=None, if wifi_access_points is not None: params["wifiAccessPoints"] = wifi_access_points - return client._request("/geolocation/v1/geolocate", {}, # No GET params - base_url=_GEOLOCATION_BASE_URL, - extract_body=_geolocation_extract, - post_json=params) + return client._request( + "/geolocation/v1/geolocate", + {}, # No GET params + base_url=_GEOLOCATION_BASE_URL, + extract_body=_geolocation_extract, + post_json=params, + ) diff --git a/googlemaps/places.py b/googlemaps/places.py index 4c95dcbd..7b603662 100644 --- a/googlemaps/places.py +++ b/googlemaps/places.py @@ -17,19 +17,61 @@ """Performs requests to the Google Places API.""" +PLACE_DETAILS_FIELDS = { + "basic": [ + "place_id", + "name", + "type", + "address_components", + "formatted_address", + "url", + "utc_offset", + "permanently_closed", + "geometry.location", + "geometry.viewport", + "photo.photo_reference", + "icon", + "types", + "adr_address", + "scope", + "vicinity", + ], + "contact": [ + "opening_hours.weekday_text", + "opening_hours.open_now", + "opening_hours.period", + "website", + "formatted_phone_number", + "international_phone_number", + ], + "atmosphere": ["price_level", "rating", "reviews"], +} + from googlemaps import convert -def places(client, query, location=None, radius=None, language=None, - min_price=None, max_price=None, open_now=False, type=None, region=None, - page_token=None): +def places( + client, + query, + location=None, + radius=None, + language=None, + min_price=None, + max_price=None, + open_now=False, + type=None, + region=None, + page_token=None, +): """ Places search. - :param query: The text string on which to search, for example: "restaurant". + :param query: The text string on which to search, for example: + "restaurant". :type query: string - :param location: The latitude/longitude value for which you wish to obtain the + :param location: The latitude/longitude value for which you wish to + obtain the closest, human-readable address. :type location: string, dict, list, or tuple @@ -40,7 +82,8 @@ def places(client, query, location=None, radius=None, language=None, :type langauge: string :param min_price: Restricts results to only those places with no less than - this price level. Valid values are in the range from 0 (most affordable) + this price level. Valid values are in the range from 0 (most + affordable) to 4 (most expensive). :type min_price: int @@ -71,25 +114,47 @@ def places(client, query, location=None, radius=None, language=None, html_attributions: set of attributions which must be displayed next_page_token: token for retrieving the next page of results """ - return _places(client, "text", query=query, location=location, - radius=radius, language=language, min_price=min_price, - max_price=max_price, open_now=open_now, type=type, region=region, - page_token=page_token) - - -def places_nearby(client, location=None, radius=None, keyword=None, - language=None, min_price=None, max_price=None, name=None, - open_now=False, rank_by=None, type=None, page_token=None): + return _places( + client, + "text", + query=query, + location=location, + radius=radius, + language=language, + min_price=min_price, + max_price=max_price, + open_now=open_now, + type=type, + region=region, + page_token=page_token, + ) + + +def places_nearby( + client, + location=None, + radius=None, + keyword=None, + language=None, + min_price=None, + max_price=None, + name=None, + open_now=False, + rank_by=None, + type=None, + page_token=None, +): """ Performs nearby search for places. - :param location: The latitude/longitude value for which you wish to obtain the + :param location: The latitude/longitude value for which you wish to + obtain the closest, human-readable address. :type location: string, dict, list, or tuple :param radius: Distance in meters within which to bias results. :type radius: int - + :param region: The region code, optional parameter. See more @ https://developers.google.com/places/web-service/search :type region: string @@ -142,24 +207,48 @@ def places_nearby(client, location=None, radius=None, keyword=None, raise ValueError("either a location or page_token arg is required") if rank_by == "distance": if not (keyword or name or type): - raise ValueError("either a keyword, name, or type arg is required " - "when rank_by is set to distance") + raise ValueError( + "either a keyword, name, or type arg is required " + "when rank_by is set to distance" + ) elif radius is not None: - raise ValueError("radius cannot be specified when rank_by is set to " - "distance") - - return _places(client, "nearby", location=location, radius=radius, - keyword=keyword, language=language, min_price=min_price, - max_price=max_price, name=name, open_now=open_now, - rank_by=rank_by, type=type, page_token=page_token) - - -def places_radar(client, location, radius, keyword=None, min_price=None, - max_price=None, name=None, open_now=False, type=None): + raise ValueError( + "radius cannot be specified when rank_by is set to " "distance" + ) + + return _places( + client, + "nearby", + location=location, + radius=radius, + keyword=keyword, + language=language, + min_price=min_price, + max_price=max_price, + name=name, + open_now=open_now, + rank_by=rank_by, + type=type, + page_token=page_token, + ) + + +def places_radar( + client, + location, + radius, + keyword=None, + min_price=None, + max_price=None, + name=None, + open_now=False, + type=None, +): """ Performs radar search for places. - :param location: The latitude/longitude value for which you wish to obtain the + :param location: The latitude/longitude value for which you wish to + obtain the closest, human-readable address. :type location: string, dict, list, or tuple @@ -202,17 +291,40 @@ def places_radar(client, location, radius, keyword=None, min_price=None, raise ValueError("either a keyword, name, or type arg is required") from warnings import warn - warn("places_radar is deprecated, see http://goo.gl/BGiumE", - DeprecationWarning) - - return _places(client, "radar", location=location, radius=radius, - keyword=keyword, min_price=min_price, max_price=max_price, - name=name, open_now=open_now, type=type) - -def _places(client, url_part, query=None, location=None, radius=None, - keyword=None, language=None, min_price=0, max_price=4, name=None, - open_now=False, rank_by=None, type=None, region=None, page_token=None): + warn("places_radar is deprecated, see http://goo.gl/BGiumE", DeprecationWarning) + + return _places( + client, + "radar", + location=location, + radius=radius, + keyword=keyword, + min_price=min_price, + max_price=max_price, + name=name, + open_now=open_now, + type=type, + ) + + +def _places( + client, + url_part, + query=None, + location=None, + radius=None, + keyword=None, + language=None, + min_price=0, + max_price=4, + name=None, + open_now=False, + rank_by=None, + type=None, + region=None, + page_token=None, +): """ Internal handler for ``places``, ``places_nearby``, and ``places_radar``. See each method's docs for arg details. @@ -247,7 +359,7 @@ def _places(client, url_part, query=None, location=None, radius=None, return client._request(url, params) -def place(client, place_id, language=None): +def place(client, place_id, language=None, fields=None, categories=None): """ Comprehensive details for an individual place. @@ -256,15 +368,35 @@ def place(client, place_id, language=None): :type place_id: string :param language: The language in which to return results. - :type langauge: string + :type language: string + + :param fields: The fields that will be returned by Place details. + :type fields: list + https://cloud.google.com/maps-platform/user-guide/product-changes/#places + + :param categories: The invoice categories. Values are "basic", "contact", + "atmosphere" + :type categories: list :rtype: result dict with the following keys: result: dict containing place details html_attributions: set of attributions which must be displayed """ params = {"placeid": place_id} + params["fields"] = [] if language: params["language"] = language + if fields: + params["fields"] = fields + if categories: + for category in categories: + category = category.lower() + fields = PLACE_DETAILS_FIELDS.get(category) + if fields: + params["fields"].extend(fields) + if not params["fields"]: + del params["fields"] + return client._request("/maps/api/place/details/json", params) @@ -307,15 +439,27 @@ def places_photo(client, photo_reference, max_width=None, max_height=None): # "extract_body" and "stream" args here are used to return an iterable # response containing the image file data, rather than converting from # json. - response = client._request("/maps/api/place/photo", params, - extract_body=lambda response: response, - requests_kwargs={"stream": True}) + response = client._request( + "/maps/api/place/photo", + params, + extract_body=lambda response: response, + requests_kwargs={"stream": True}, + ) return response.iter_content() -def places_autocomplete(client, input_text, offset=None, location=None, - radius=None, language=None, types=None, - components=None, strict_bounds=False): +def places_autocomplete( + client, + input_text, + offset=None, + location=None, + radius=None, + language=None, + types=None, + components=None, + strict_bounds=False, + session_token=None, +): """ Returns Place predictions given a textual search string and optional geographic bounds. @@ -329,7 +473,8 @@ def places_autocomplete(client, input_text, offset=None, location=None, service will match on 'Goo'. :type offset: int - :param location: The latitude/longitude value for which you wish to obtain the + :param location: The latitude/longitude value for which you wish to + obtain the closest, human-readable address. :type location: string, dict, list, or tuple @@ -341,10 +486,12 @@ def places_autocomplete(client, input_text, offset=None, location=None, :param types: Restricts the results to places matching the specified type. The full list of supported types is available here: - https://developers.google.com/places/web-service/autocomplete#place_types + https://developers.google.com/places/web-service/autocomplete + #place_types :type types: string - :param components: A component filter for which you wish to obtain a geocode. + :param components: A component filter for which you wish to obtain a + geocode. Currently, you can use components to filter by up to 5 countries for example: ``{'country': ['US', 'AU']}`` :type components: dict @@ -353,17 +500,37 @@ def places_autocomplete(client, input_text, offset=None, location=None, the region defined by location and radius. :type strict_bounds: bool + :param session_token: A random unique string which identifies an + autocomplete session used for billing. + :type session_token: string + :rtype: list of predictions """ - return _autocomplete(client, "", input_text, offset=offset, - location=location, radius=radius, language=language, - types=types, components=components, - strict_bounds=strict_bounds) - - -def places_autocomplete_query(client, input_text, offset=None, location=None, - radius=None, language=None): + return _autocomplete( + client, + "", + input_text, + offset=offset, + location=location, + radius=radius, + language=language, + types=types, + components=components, + strict_bounds=strict_bounds, + session_token=session_token, + ) + + +def places_autocomplete_query( + client, + input_text, + offset=None, + location=None, + radius=None, + language=None, + session_token=None, +): """ Returns Place predictions given a textual search query, such as "pizza near New York", and optional geographic bounds. @@ -376,7 +543,8 @@ def places_autocomplete_query(client, input_text, offset=None, location=None, is 'Google' and the offset is 3, the service will match on 'Goo'. :type offset: int - :param location: The latitude/longitude value for which you wish to obtain the + :param location: The latitude/longitude value for which you wish to + obtain the closest, human-readable address. :type location: string, dict, list, or tuple @@ -386,15 +554,38 @@ def places_autocomplete_query(client, input_text, offset=None, location=None, :param language: The language in which to return results. :type langauge: string - :rtype: list of predictions - """ - return _autocomplete(client, "query", input_text, offset=offset, - location=location, radius=radius, language=language) + :param session_token: A random unique string which identifies an + autocomplete session used for billing. + :type session_token: string -def _autocomplete(client, url_part, input_text, offset=None, location=None, - radius=None, language=None, types=None, components=None, - strict_bounds=False): + :rtype: list of predictions + """ + return _autocomplete( + client, + "query", + input_text, + offset=offset, + location=location, + radius=radius, + language=language, + session_token=session_token, + ) + + +def _autocomplete( + client, + url_part, + input_text, + offset=None, + location=None, + radius=None, + language=None, + types=None, + components=None, + strict_bounds=False, + session_token=None, +): """ Internal handler for ``autocomplete`` and ``autocomplete_query``. See each method's docs for arg details. @@ -419,5 +610,8 @@ def _autocomplete(client, url_part, input_text, offset=None, location=None, if strict_bounds: params["strictbounds"] = "true" + if session_token: + params["session_token"] = session_token + url = "/maps/api/place/%sautocomplete/json" % url_part return client._request(url, params).get("predictions", []) diff --git a/googlemaps/roads.py b/googlemaps/roads.py index edfb8ecb..3f2a08e2 100644 --- a/googlemaps/roads.py +++ b/googlemaps/roads.py @@ -20,7 +20,6 @@ import googlemaps from googlemaps import convert - _ROADS_BASE_URL = "https://roads.googleapis.com" @@ -50,10 +49,14 @@ def snap_to_roads(client, path, interpolate=False): if interpolate: params["interpolate"] = "true" - return client._request("/v1/snapToRoads", params, - base_url=_ROADS_BASE_URL, - accepts_clientid=False, - extract_body=_roads_extract).get("snappedPoints", []) + return client._request( + "/v1/snapToRoads", + params, + base_url=_ROADS_BASE_URL, + accepts_clientid=False, + extract_body=_roads_extract, + ).get("snappedPoints", []) + def nearest_roads(client, points): """Find the closest road segments for each point @@ -72,10 +75,14 @@ def nearest_roads(client, points): params = {"points": convert.location_list(points)} - return client._request("/v1/nearestRoads", params, - base_url=_ROADS_BASE_URL, - accepts_clientid=False, - extract_body=_roads_extract).get("snappedPoints", []) + return client._request( + "/v1/nearestRoads", + params, + base_url=_ROADS_BASE_URL, + accepts_clientid=False, + extract_body=_roads_extract, + ).get("snappedPoints", []) + def speed_limits(client, place_ids): """Returns the posted speed limit (in km/h) for given road segments. @@ -89,10 +96,13 @@ def speed_limits(client, place_ids): params = [("placeId", place_id) for place_id in convert.as_list(place_ids)] - return client._request("/v1/speedLimits", params, - base_url=_ROADS_BASE_URL, - accepts_clientid=False, - extract_body=_roads_extract).get("speedLimits", []) + return client._request( + "/v1/speedLimits", + params, + base_url=_ROADS_BASE_URL, + accepts_clientid=False, + extract_body=_roads_extract, + ).get("speedLimits", []) def snapped_speed_limits(client, path): @@ -110,10 +120,13 @@ def snapped_speed_limits(client, path): params = {"path": convert.location_list(path)} - return client._request("/v1/speedLimits", params, - base_url=_ROADS_BASE_URL, - accepts_clientid=False, - extract_body=_roads_extract) + return client._request( + "/v1/speedLimits", + params, + base_url=_ROADS_BASE_URL, + accepts_clientid=False, + extract_body=_roads_extract, + ) def _roads_extract(resp): @@ -125,16 +138,16 @@ def _roads_extract(resp): if resp.status_code != 200: raise googlemaps.exceptions.HTTPError(resp.status_code) - raise googlemaps.exceptions.ApiError("UNKNOWN_ERROR", - "Received a malformed response.") + raise googlemaps.exceptions.ApiError( + "UNKNOWN_ERROR", "Received a malformed response." + ) if "error" in j: error = j["error"] status = error["status"] if status == "RESOURCE_EXHAUSTED": - raise googlemaps.exceptions._OverQueryLimit(status, - error.get("message")) + raise googlemaps.exceptions._OverQueryLimit(status, error.get("message")) raise googlemaps.exceptions.ApiError(status, error.get("message")) diff --git a/googlemaps/test/__init__.py b/googlemaps/test/__init__.py index 38c70917..15652366 100644 --- a/googlemaps/test/__init__.py +++ b/googlemaps/test/__init__.py @@ -18,14 +18,13 @@ import unittest import codecs -try: # Python 3 +try: # Python 3 from urllib.parse import urlparse, parse_qsl -except ImportError: # Python 2 +except ImportError: # Python 2 from urlparse import urlparse, parse_qsl class TestCase(unittest.TestCase): - def assertURLEqual(self, first, second, msg=None): """Check that two arguments are equivalent URLs. Ignores the order of query arguments. diff --git a/googlemaps/test/test_client.py b/googlemaps/test/test_client.py index 90d83b3e..a8fa8bf2 100644 --- a/googlemaps/test/test_client.py +++ b/googlemaps/test/test_client.py @@ -29,7 +29,6 @@ class ClientTest(_test.TestCase): - def test_no_api_key(self): with self.assertRaises(Exception): client = googlemaps.Client() @@ -54,13 +53,16 @@ def test_queries_per_second(self): queries_per_second = 3 query_range = range(queries_per_second * 2) for _ in query_range: - responses.add(responses.GET, - "https://maps.googleapis.com/maps/api/geocode/json", - body='{"status":"OK","results":[]}', - status=200, - content_type="application/json") - client = googlemaps.Client(key="AIzaasdf", - queries_per_second=queries_per_second) + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) + client = googlemaps.Client( + key="AIzaasdf", queries_per_second=queries_per_second + ) start = time.time() for _ in query_range: client.geocode("Sesame St.") @@ -69,35 +71,43 @@ def test_queries_per_second(self): @responses.activate def test_key_sent(self): - responses.add(responses.GET, - "https://maps.googleapis.com/maps/api/geocode/json", - body='{"status":"OK","results":[]}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) client = googlemaps.Client(key="AIzaasdf") client.geocode("Sesame St.") self.assertEqual(1, len(responses.calls)) - self.assertURLEqual("https://maps.googleapis.com/maps/api/geocode/json?" - "key=AIzaasdf&address=Sesame+St.", - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=AIzaasdf&address=Sesame+St.", + responses.calls[0].request.url, + ) @responses.activate def test_extra_params(self): - responses.add(responses.GET, - "https://maps.googleapis.com/maps/api/geocode/json", - body='{"status":"OK","results":[]}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) client = googlemaps.Client(key="AIzaasdf") client.geocode("Sesame St.", extra_params={"foo": "bar"}) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual("https://maps.googleapis.com/maps/api/geocode/json?" - "key=AIzaasdf&address=Sesame+St.&foo=bar", - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=AIzaasdf&address=Sesame+St.&foo=bar", + responses.calls[0].request.url, + ) def test_hmac(self): """ @@ -108,18 +118,20 @@ def test_hmac(self): """ message = "The quick brown fox jumps over the lazy dog" - key = "a2V5" # "key" -> base64 + key = "a2V5" # "key" -> base64 signature = "3nybhbi3iqa8ino29wqQcBydtNk=" self.assertEqual(signature, _client.sign_hmac(key, message)) @responses.activate def test_url_signed(self): - responses.add(responses.GET, - "https://maps.googleapis.com/maps/api/geocode/json", - body='{"status":"OK","results":[]}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) client = googlemaps.Client(client_id="foo", client_secret="a2V5") client.geocode("Sesame St.") @@ -127,20 +139,25 @@ def test_url_signed(self): self.assertEqual(1, len(responses.calls)) # Check ordering of parameters. - self.assertIn("address=Sesame+St.&client=foo&signature", - responses.calls[0].request.url) - self.assertURLEqual("https://maps.googleapis.com/maps/api/geocode/json?" - "address=Sesame+St.&client=foo&" - "signature=fxbWUIcNPZSekVOhp2ul9LW5TpY=", - responses.calls[0].request.url) + self.assertIn( + "address=Sesame+St.&client=foo&signature", responses.calls[0].request.url + ) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "address=Sesame+St.&client=foo&" + "signature=fxbWUIcNPZSekVOhp2ul9LW5TpY=", + responses.calls[0].request.url, + ) @responses.activate def test_ua_sent(self): - responses.add(responses.GET, - "https://maps.googleapis.com/maps/api/geocode/json", - body='{"status":"OK","results":[]}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) client = googlemaps.Client(key="AIzaasdf") client.geocode("Sesame St.") @@ -161,10 +178,12 @@ def __call__(self, req): return (200, {}, '{"status":"OVER_QUERY_LIMIT"}') return (200, {}, '{"status":"OK","results":[]}') - responses.add_callback(responses.GET, - "https://maps.googleapis.com/maps/api/geocode/json", - content_type='application/json', - callback=request_callback()) + responses.add_callback( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + content_type="application/json", + callback=request_callback(), + ) client = googlemaps.Client(key="AIzaasdf") client.geocode("Sesame St.") @@ -174,10 +193,12 @@ def __call__(self, req): @responses.activate def test_transport_error(self): - responses.add(responses.GET, - "https://maps.googleapis.com/maps/api/geocode/json", - status=404, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + status=404, + content_type="application/json", + ) client = googlemaps.Client(key="AIzaasdf") with self.assertRaises(googlemaps.exceptions.HTTPError) as e: @@ -187,11 +208,13 @@ def test_transport_error(self): @responses.activate def test_host_override(self): - responses.add(responses.GET, - "https://foo.com/bar", - body='{"status":"OK","results":[]}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://foo.com/bar", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) client = googlemaps.Client(key="AIzaasdf") client._get("/bar", {}, base_url="https://foo.com") @@ -203,11 +226,13 @@ def test_custom_extract(self): def custom_extract(resp): return resp.json() - responses.add(responses.GET, - "https://maps.googleapis.com/bar", - body='{"error":"errormessage"}', - status=403, - content_type="application/json") + responses.add( + responses.GET, + "https://maps.googleapis.com/bar", + body='{"error":"errormessage"}', + status=403, + content_type="application/json", + ) client = googlemaps.Client(key="AIzaasdf") b = client._get("/bar", {}, extract_body=custom_extract) @@ -223,13 +248,15 @@ def __init__(self): def __call__(self, req): if self.first_req: self.first_req = False - return (500, {}, 'Internal Server Error.') + return (500, {}, "Internal Server Error.") return (200, {}, '{"status":"OK","results":[]}') - responses.add_callback(responses.GET, - "https://maps.googleapis.com/maps/api/geocode/json", - content_type="application/json", - callback=request_callback()) + responses.add_callback( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + content_type="application/json", + callback=request_callback(), + ) client = googlemaps.Client(key="AIzaasdf") client.geocode("Sesame St.") @@ -245,28 +272,31 @@ def test_invalid_channel(self): # https://developers.google.com/maps/premium/reports # /usage-reports#channels with self.assertRaises(ValueError): - client = googlemaps.Client(client_id="foo", client_secret="a2V5", - channel="auieauie$? ") + client = googlemaps.Client( + client_id="foo", client_secret="a2V5", channel="auieauie$? " + ) def test_auth_url_with_channel(self): - client = googlemaps.Client(key="AIzaasdf", - client_id="foo", - client_secret="a2V5", - channel="MyChannel_1") + client = googlemaps.Client( + key="AIzaasdf", client_id="foo", client_secret="a2V5", channel="MyChannel_1" + ) # Check ordering of parameters + signature. - auth_url = client._generate_auth_url("/test", - {"param": "param"}, - accepts_clientid=True) - self.assertEqual(auth_url, "/test?param=param" - "&channel=MyChannel_1" - "&client=foo" - "&signature=OH18GuQto_mEpxj99UimKskvo4k=") + auth_url = client._generate_auth_url( + "/test", {"param": "param"}, accepts_clientid=True + ) + self.assertEqual( + auth_url, + "/test?param=param" + "&channel=MyChannel_1" + "&client=foo" + "&signature=OH18GuQto_mEpxj99UimKskvo4k=", + ) # Check if added to requests to API with accepts_clientid=False - auth_url = client._generate_auth_url("/test", - {"param": "param"}, - accepts_clientid=False) + auth_url = client._generate_auth_url( + "/test", {"param": "param"}, accepts_clientid=False + ) self.assertEqual(auth_url, "/test?param=param&key=AIzaasdf") def test_requests_version(self): @@ -276,31 +306,32 @@ def test_requests_version(self): "client_secret": "a2V5", "channel": "MyChannel_1", "connect_timeout": 5, - "read_timeout": 5 + "read_timeout": 5, } client_args = client_args_timeout.copy() del client_args["connect_timeout"] del client_args["read_timeout"] - requests.__version__ = '2.3.0' + requests.__version__ = "2.3.0" with self.assertRaises(NotImplementedError): googlemaps.Client(**client_args_timeout) googlemaps.Client(**client_args) - requests.__version__ = '2.4.0' + requests.__version__ = "2.4.0" googlemaps.Client(**client_args_timeout) googlemaps.Client(**client_args) @responses.activate def test_no_retry_over_query_limit(self): - responses.add(responses.GET, - "https://maps.googleapis.com/foo", - body='{"status":"OVER_QUERY_LIMIT"}', - status=200, - content_type="application/json") - - client = googlemaps.Client(key="AIzaasdf", - retry_over_query_limit=False) + responses.add( + responses.GET, + "https://maps.googleapis.com/foo", + body='{"status":"OVER_QUERY_LIMIT"}', + status=200, + content_type="application/json", + ) + + client = googlemaps.Client(key="AIzaasdf", retry_over_query_limit=False) with self.assertRaises(googlemaps.exceptions.ApiError): client._request("/foo", {}) diff --git a/googlemaps/test/test_convert.py b/googlemaps/test/test_convert.py index ed08c84b..0b660acc 100644 --- a/googlemaps/test/test_convert.py +++ b/googlemaps/test/test_convert.py @@ -24,7 +24,6 @@ class ConvertTest(unittest.TestCase): - def test_latlng(self): expected = "1,2" ll = {"lat": 1, "lng": 2} @@ -113,31 +112,33 @@ def test_bounds(self): convert.bounds("test") def test_polyline_decode(self): - syd_mel_route = ("rvumEis{y[`NsfA~tAbF`bEj^h{@{KlfA~eA~`AbmEghAt~D|e@j" - "lRpO~yH_\\v}LjbBh~FdvCxu@`nCplDbcBf_B|wBhIfhCnqEb~D~" - "jCn_EngApdEtoBbfClf@t_CzcCpoEr_Gz_DxmAphDjjBxqCviEf}" - "B|pEvsEzbE~qGfpExjBlqCx}BvmLb`FbrQdpEvkAbjDllD|uDldD" - "j`Ef|AzcEx_Gtm@vuI~xArwD`dArlFnhEzmHjtC~eDluAfkC|eAd" - "hGpJh}N_mArrDlr@h|HzjDbsAvy@~~EdTxpJje@jlEltBboDjJdv" - "KyZpzExrAxpHfg@pmJg[tgJuqBnlIarAh}DbN`hCeOf_IbxA~uFt" - "|A|xEt_ArmBcN|sB|h@b_DjOzbJ{RlxCcfAp~AahAbqG~Gr}AerA" - "`dCwlCbaFo]twKt{@bsG|}A~fDlvBvz@tw@rpD_r@rqB{PvbHek@" - "vsHlh@ptNtm@fkD[~xFeEbyKnjDdyDbbBtuA|~Br|Gx_AfxCt}Cj" - "nHv`Ew\\lnBdrBfqBraD|{BldBxpG|]jqC`mArcBv]rdAxgBzdEb" - "{InaBzyC}AzaEaIvrCzcAzsCtfD~qGoPfeEh]h`BxiB`e@`kBxfA" - "v^pyA`}BhkCdoCtrC~bCxhCbgEplKrk@tiAteBwAxbCwuAnnCc]b" - "{FjrDdjGhhGzfCrlDruBzSrnGhvDhcFzw@n{@zxAf}Fd{IzaDnbD" - "joAjqJjfDlbIlzAraBxrB}K~`GpuD~`BjmDhkBp{@r_AxCrnAjrC" - "x`AzrBj{B|r@~qBbdAjtDnvCtNzpHxeApyC|GlfM`fHtMvqLjuEt" - "lDvoFbnCt|@xmAvqBkGreFm~@hlHw|AltC}NtkGvhBfaJ|~@riAx" - "uC~gErwCttCzjAdmGuF`iFv`AxsJftD|nDr_QtbMz_DheAf~Buy@" - "rlC`i@d_CljC`gBr|H|nAf_Fh{G|mE~kAhgKviEpaQnu@zwAlrA`" - "G~gFnvItz@j{Cng@j{D{]`tEftCdcIsPz{DddE~}PlnE|dJnzG`e" - "G`mF|aJdqDvoAwWjzHv`H`wOtjGzeXhhBlxErfCf{BtsCjpEjtD|" - "}Aja@xnAbdDt|ErMrdFh{CzgAnlCnr@`wEM~mE`bA`uD|MlwKxmB" - "vuFlhB|sN`_@fvBp`CxhCt_@loDsS|eDlmChgFlqCbjCxk@vbGxm" - "CjbMba@rpBaoClcCk_DhgEzYdzBl\\vsA_JfGztAbShkGtEhlDzh" - "C~w@hnB{e@yF}`D`_Ayx@~vGqn@l}CafC") + syd_mel_route = ( + "rvumEis{y[`NsfA~tAbF`bEj^h{@{KlfA~eA~`AbmEghAt~D|e@j" + "lRpO~yH_\\v}LjbBh~FdvCxu@`nCplDbcBf_B|wBhIfhCnqEb~D~" + "jCn_EngApdEtoBbfClf@t_CzcCpoEr_Gz_DxmAphDjjBxqCviEf}" + "B|pEvsEzbE~qGfpExjBlqCx}BvmLb`FbrQdpEvkAbjDllD|uDldD" + "j`Ef|AzcEx_Gtm@vuI~xArwD`dArlFnhEzmHjtC~eDluAfkC|eAd" + "hGpJh}N_mArrDlr@h|HzjDbsAvy@~~EdTxpJje@jlEltBboDjJdv" + "KyZpzExrAxpHfg@pmJg[tgJuqBnlIarAh}DbN`hCeOf_IbxA~uFt" + "|A|xEt_ArmBcN|sB|h@b_DjOzbJ{RlxCcfAp~AahAbqG~Gr}AerA" + "`dCwlCbaFo]twKt{@bsG|}A~fDlvBvz@tw@rpD_r@rqB{PvbHek@" + "vsHlh@ptNtm@fkD[~xFeEbyKnjDdyDbbBtuA|~Br|Gx_AfxCt}Cj" + "nHv`Ew\\lnBdrBfqBraD|{BldBxpG|]jqC`mArcBv]rdAxgBzdEb" + "{InaBzyC}AzaEaIvrCzcAzsCtfD~qGoPfeEh]h`BxiB`e@`kBxfA" + "v^pyA`}BhkCdoCtrC~bCxhCbgEplKrk@tiAteBwAxbCwuAnnCc]b" + "{FjrDdjGhhGzfCrlDruBzSrnGhvDhcFzw@n{@zxAf}Fd{IzaDnbD" + "joAjqJjfDlbIlzAraBxrB}K~`GpuD~`BjmDhkBp{@r_AxCrnAjrC" + "x`AzrBj{B|r@~qBbdAjtDnvCtNzpHxeApyC|GlfM`fHtMvqLjuEt" + "lDvoFbnCt|@xmAvqBkGreFm~@hlHw|AltC}NtkGvhBfaJ|~@riAx" + "uC~gErwCttCzjAdmGuF`iFv`AxsJftD|nDr_QtbMz_DheAf~Buy@" + "rlC`i@d_CljC`gBr|H|nAf_Fh{G|mE~kAhgKviEpaQnu@zwAlrA`" + "G~gFnvItz@j{Cng@j{D{]`tEftCdcIsPz{DddE~}PlnE|dJnzG`e" + "G`mF|aJdqDvoAwWjzHv`H`wOtjGzeXhhBlxErfCf{BtsCjpEjtD|" + "}Aja@xnAbdDt|ErMrdFh{CzgAnlCnr@`wEM~mE`bA`uD|MlwKxmB" + "vuFlhB|sN`_@fvBp`CxhCt_@loDsS|eDlmChgFlqCbjCxk@vbGxm" + "CjbMba@rpBaoClcCk_DhgEzYdzBl\\vsA_JfGztAbShkGtEhlDzh" + "C~w@hnB{e@yF}`D`_Ayx@~vGqn@l}CafC" + ) points = convert.decode_polyline(syd_mel_route) self.assertAlmostEqual(-33.86746, points[0]["lat"]) @@ -146,8 +147,10 @@ def test_polyline_decode(self): self.assertAlmostEqual(144.963180, points[-1]["lng"]) def test_polyline_round_trip(self): - test_polyline = ("gcneIpgxzRcDnBoBlEHzKjBbHlG`@`IkDxIi" - "KhKoMaLwTwHeIqHuAyGXeB~Ew@fFjAtIzExF") + test_polyline = ( + "gcneIpgxzRcDnBoBlEHzKjBbHlG`@`IkDxIi" + "KhKoMaLwTwHeIqHuAyGXeB~Ew@fFjAtIzExF" + ) points = convert.decode_polyline(test_polyline) actual_polyline = convert.encode_polyline(points) diff --git a/googlemaps/test/test_directions.py b/googlemaps/test/test_directions.py index de21dc1e..09bfe3aa 100644 --- a/googlemaps/test/test_directions.py +++ b/googlemaps/test/test_directions.py @@ -28,213 +28,255 @@ class DirectionsTest(_test.TestCase): - def setUp(self): - self.key = 'AIzaasdf' + self.key = "AIzaasdf" self.client = googlemaps.Client(self.key) @responses.activate def test_simple_directions(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) # Simplest directions request. Driving directions by default. routes = self.client.directions("Sydney", "Melbourne") self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json' - '?origin=Sydney&destination=Melbourne&key=%s' % - self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json" + "?origin=Sydney&destination=Melbourne&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_complex_request(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') - - routes = self.client.directions("Sydney", "Melbourne", - mode="bicycling", - avoid=["highways", "tolls", "ferries"], - units="metric", - region="us") + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) + + routes = self.client.directions( + "Sydney", + "Melbourne", + mode="bicycling", + avoid=["highways", "tolls", "ferries"], + units="metric", + region="us", + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?' - 'origin=Sydney&avoid=highways%%7Ctolls%%7Cferries&' - 'destination=Melbourne&mode=bicycling&key=%s' - '&units=metric®ion=us' % - self.key, - responses.calls[0].request.url) - + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?" + "origin=Sydney&avoid=highways%%7Ctolls%%7Cferries&" + "destination=Melbourne&mode=bicycling&key=%s" + "&units=metric®ion=us" % self.key, + responses.calls[0].request.url, + ) def test_transit_without_time(self): # With mode of transit, we need a departure_time or an # arrival_time specified with self.assertRaises(googlemaps.exceptions.ApiError): - self.client.directions("Sydney Town Hall", "Parramatta, NSW", - mode="transit") + self.client.directions( + "Sydney Town Hall", "Parramatta, NSW", mode="transit" + ) @responses.activate def test_transit_with_departure_time(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) now = datetime.now() - routes = self.client.directions("Sydney Town Hall", "Parramatta, NSW", - mode="transit", - traffic_model="optimistic", - departure_time=now) + routes = self.client.directions( + "Sydney Town Hall", + "Parramatta, NSW", + mode="transit", + traffic_model="optimistic", + departure_time=now, + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?origin=' - 'Sydney+Town+Hall&key=%s&destination=Parramatta%%2C+NSW&' - 'mode=transit&departure_time=%d&traffic_model=optimistic' % - (self.key, time.mktime(now.timetuple())), - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?origin=" + "Sydney+Town+Hall&key=%s&destination=Parramatta%%2C+NSW&" + "mode=transit&departure_time=%d&traffic_model=optimistic" + % (self.key, time.mktime(now.timetuple())), + responses.calls[0].request.url, + ) @responses.activate def test_transit_with_arrival_time(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) an_hour_from_now = datetime.now() + timedelta(hours=1) - routes = self.client.directions("Sydney Town Hall", - "Parramatta, NSW", - mode="transit", - arrival_time=an_hour_from_now) + routes = self.client.directions( + "Sydney Town Hall", + "Parramatta, NSW", + mode="transit", + arrival_time=an_hour_from_now, + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?' - 'origin=Sydney+Town+Hall&arrival_time=%d&' - 'destination=Parramatta%%2C+NSW&mode=transit&key=%s' % - (time.mktime(an_hour_from_now.timetuple()), self.key), - responses.calls[0].request.url) - + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?" + "origin=Sydney+Town+Hall&arrival_time=%d&" + "destination=Parramatta%%2C+NSW&mode=transit&key=%s" + % (time.mktime(an_hour_from_now.timetuple()), self.key), + responses.calls[0].request.url, + ) def test_invalid_travel_mode(self): with self.assertRaises(ValueError): - self.client.directions("48 Pirrama Road, Pyrmont, NSW", - "Sydney Town Hall", - mode="crawling") + self.client.directions( + "48 Pirrama Road, Pyrmont, NSW", "Sydney Town Hall", mode="crawling" + ) @responses.activate def test_travel_mode_round_trip(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') - - routes = self.client.directions("Town Hall, Sydney", - "Parramatta, NSW", - mode="bicycling") + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) + + routes = self.client.directions( + "Town Hall, Sydney", "Parramatta, NSW", mode="bicycling" + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?' - 'origin=Town+Hall%%2C+Sydney&destination=Parramatta%%2C+NSW&' - 'mode=bicycling&key=%s' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?" + "origin=Town+Hall%%2C+Sydney&destination=Parramatta%%2C+NSW&" + "mode=bicycling&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_brooklyn_to_queens_by_transit(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) now = datetime.now() - routes = self.client.directions("Brooklyn", - "Queens", - mode="transit", - departure_time=now) + routes = self.client.directions( + "Brooklyn", "Queens", mode="transit", departure_time=now + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?' - 'origin=Brooklyn&key=%s&destination=Queens&mode=transit&' - 'departure_time=%d' % (self.key, time.mktime(now.timetuple())), - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?" + "origin=Brooklyn&key=%s&destination=Queens&mode=transit&" + "departure_time=%d" % (self.key, time.mktime(now.timetuple())), + responses.calls[0].request.url, + ) @responses.activate def test_boston_to_concord_via_charlestown_and_lexington(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') - - routes = self.client.directions("Boston, MA", - "Concord, MA", - waypoints=["Charlestown, MA", - "Lexington, MA"]) + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) + + routes = self.client.directions( + "Boston, MA", "Concord, MA", waypoints=["Charlestown, MA", "Lexington, MA"] + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?' - 'origin=Boston%%2C+MA&destination=Concord%%2C+MA&' - 'waypoints=Charlestown%%2C+MA%%7CLexington%%2C+MA&' - 'key=%s' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?" + "origin=Boston%%2C+MA&destination=Concord%%2C+MA&" + "waypoints=Charlestown%%2C+MA%%7CLexington%%2C+MA&" + "key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_adelaide_wine_tour(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') - - routes = self.client.directions("Adelaide, SA", - "Adelaide, SA", - waypoints=["Barossa Valley, SA", - "Clare, SA", - "Connawarra, SA", - "McLaren Vale, SA"], - optimize_waypoints=True) + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) + + routes = self.client.directions( + "Adelaide, SA", + "Adelaide, SA", + waypoints=[ + "Barossa Valley, SA", + "Clare, SA", + "Connawarra, SA", + "McLaren Vale, SA", + ], + optimize_waypoints=True, + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?' - 'origin=Adelaide%%2C+SA&destination=Adelaide%%2C+SA&' - 'waypoints=optimize%%3Atrue%%7CBarossa+Valley%%2C+' - 'SA%%7CClare%%2C+SA%%7CConnawarra%%2C+SA%%7CMcLaren+' - 'Vale%%2C+SA&key=%s' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?" + "origin=Adelaide%%2C+SA&destination=Adelaide%%2C+SA&" + "waypoints=optimize%%3Atrue%%7CBarossa+Valley%%2C+" + "SA%%7CClare%%2C+SA%%7CConnawarra%%2C+SA%%7CMcLaren+" + "Vale%%2C+SA&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_toledo_to_madrid_in_spain(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) - routes = self.client.directions("Toledo", "Madrid", - region="es") + routes = self.client.directions("Toledo", "Madrid", region="es") self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?' - 'origin=Toledo®ion=es&destination=Madrid&key=%s' % - self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?" + "origin=Toledo®ion=es&destination=Madrid&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_zero_results_returns_response(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"ZERO_RESULTS","routes":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"ZERO_RESULTS","routes":[]}', + status=200, + content_type="application/json", + ) routes = self.client.directions("Toledo", "Madrid") self.assertIsNotNone(routes) @@ -242,37 +284,42 @@ def test_zero_results_returns_response(self): @responses.activate def test_language_parameter(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) - routes = self.client.directions("Toledo", "Madrid", - region="es", - language="es") + routes = self.client.directions("Toledo", "Madrid", region="es", language="es") self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?' - 'origin=Toledo®ion=es&destination=Madrid&key=%s&' - 'language=es' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?" + "origin=Toledo®ion=es&destination=Madrid&key=%s&" + "language=es" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_alternatives(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/directions/json', - body='{"status":"OK","routes":[]}', - status=200, - content_type='application/json') - - routes = self.client.directions("Sydney Town Hall", - "Parramatta Town Hall", - alternatives=True) + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/directions/json", + body='{"status":"OK","routes":[]}', + status=200, + content_type="application/json", + ) + + routes = self.client.directions( + "Sydney Town Hall", "Parramatta Town Hall", alternatives=True + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/directions/json?' - 'origin=Sydney+Town+Hall&destination=Parramatta+Town+Hall&' - 'alternatives=true&key=%s' % self.key, - responses.calls[0].request.url) - + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/directions/json?" + "origin=Sydney+Town+Hall&destination=Parramatta+Town+Hall&" + "alternatives=true&key=%s" % self.key, + responses.calls[0].request.url, + ) diff --git a/googlemaps/test/test_distance_matrix.py b/googlemaps/test/test_distance_matrix.py index 5e929b24..564713a4 100644 --- a/googlemaps/test/test_distance_matrix.py +++ b/googlemaps/test/test_distance_matrix.py @@ -27,124 +27,157 @@ class DistanceMatrixTest(_test.TestCase): - def setUp(self): - self.key = 'AIzaasdf' + self.key = "AIzaasdf" self.client = googlemaps.Client(self.key) @responses.activate def test_basic_params(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/distancematrix/json', - body='{"status":"OK","rows":[]}', - status=200, - content_type='application/json') - - origins = ["Perth, Australia", "Sydney, Australia", - "Melbourne, Australia", "Adelaide, Australia", - "Brisbane, Australia", "Darwin, Australia", - "Hobart, Australia", "Canberra, Australia"] - destinations = ["Uluru, Australia", - "Kakadu, Australia", - "Blue Mountains, Australia", - "Bungle Bungles, Australia", - "The Pinnacles, Australia"] + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/distancematrix/json", + body='{"status":"OK","rows":[]}', + status=200, + content_type="application/json", + ) + + origins = [ + "Perth, Australia", + "Sydney, Australia", + "Melbourne, Australia", + "Adelaide, Australia", + "Brisbane, Australia", + "Darwin, Australia", + "Hobart, Australia", + "Canberra, Australia", + ] + destinations = [ + "Uluru, Australia", + "Kakadu, Australia", + "Blue Mountains, Australia", + "Bungle Bungles, Australia", + "The Pinnacles, Australia", + ] matrix = self.client.distance_matrix(origins, destinations) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/distancematrix/json?' - 'key=%s&origins=Perth%%2C+Australia%%7CSydney%%2C+' - 'Australia%%7CMelbourne%%2C+Australia%%7CAdelaide%%2C+' - 'Australia%%7CBrisbane%%2C+Australia%%7CDarwin%%2C+' - 'Australia%%7CHobart%%2C+Australia%%7CCanberra%%2C+Australia&' - 'destinations=Uluru%%2C+Australia%%7CKakadu%%2C+Australia%%7C' - 'Blue+Mountains%%2C+Australia%%7CBungle+Bungles%%2C+Australia' - '%%7CThe+Pinnacles%%2C+Australia' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/distancematrix/json?" + "key=%s&origins=Perth%%2C+Australia%%7CSydney%%2C+" + "Australia%%7CMelbourne%%2C+Australia%%7CAdelaide%%2C+" + "Australia%%7CBrisbane%%2C+Australia%%7CDarwin%%2C+" + "Australia%%7CHobart%%2C+Australia%%7CCanberra%%2C+Australia&" + "destinations=Uluru%%2C+Australia%%7CKakadu%%2C+Australia%%7C" + "Blue+Mountains%%2C+Australia%%7CBungle+Bungles%%2C+Australia" + "%%7CThe+Pinnacles%%2C+Australia" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_mixed_params(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/distancematrix/json', - body='{"status":"OK","rows":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/distancematrix/json", + body='{"status":"OK","rows":[]}', + status=200, + content_type="application/json", + ) origins = ["Bobcaygeon ON", [41.43206, -81.38992]] - destinations = [(43.012486, -83.6964149), - {"lat": 42.8863855, "lng": -78.8781627}] + destinations = [ + (43.012486, -83.6964149), + {"lat": 42.8863855, "lng": -78.8781627}, + ] matrix = self.client.distance_matrix(origins, destinations) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/distancematrix/json?' - 'key=%s&origins=Bobcaygeon+ON%%7C41.43206%%2C-81.38992&' - 'destinations=43.012486%%2C-83.696415%%7C42.886386%%2C' - '-78.878163' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/distancematrix/json?" + "key=%s&origins=Bobcaygeon+ON%%7C41.43206%%2C-81.38992&" + "destinations=43.012486%%2C-83.696415%%7C42.886386%%2C" + "-78.878163" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_all_params(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/distancematrix/json', - body='{"status":"OK","rows":[]}', - status=200, - content_type='application/json') - - origins = ["Perth, Australia", "Sydney, Australia", - "Melbourne, Australia", "Adelaide, Australia", - "Brisbane, Australia", "Darwin, Australia", - "Hobart, Australia", "Canberra, Australia"] - destinations = ["Uluru, Australia", - "Kakadu, Australia", - "Blue Mountains, Australia", - "Bungle Bungles, Australia", - "The Pinnacles, Australia"] + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/distancematrix/json", + body='{"status":"OK","rows":[]}', + status=200, + content_type="application/json", + ) + + origins = [ + "Perth, Australia", + "Sydney, Australia", + "Melbourne, Australia", + "Adelaide, Australia", + "Brisbane, Australia", + "Darwin, Australia", + "Hobart, Australia", + "Canberra, Australia", + ] + destinations = [ + "Uluru, Australia", + "Kakadu, Australia", + "Blue Mountains, Australia", + "Bungle Bungles, Australia", + "The Pinnacles, Australia", + ] now = datetime.now() - matrix = self.client.distance_matrix(origins, destinations, - mode="driving", - language="en-AU", - avoid="tolls", - units="imperial", - departure_time=now, - traffic_model="optimistic") + matrix = self.client.distance_matrix( + origins, + destinations, + mode="driving", + language="en-AU", + avoid="tolls", + units="imperial", + departure_time=now, + traffic_model="optimistic", + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/distancematrix/json?' - 'origins=Perth%%2C+Australia%%7CSydney%%2C+Australia%%7C' - 'Melbourne%%2C+Australia%%7CAdelaide%%2C+Australia%%7C' - 'Brisbane%%2C+Australia%%7CDarwin%%2C+Australia%%7CHobart%%2C+' - 'Australia%%7CCanberra%%2C+Australia&language=en-AU&' - 'avoid=tolls&mode=driving&key=%s&units=imperial&' - 'destinations=Uluru%%2C+Australia%%7CKakadu%%2C+Australia%%7C' - 'Blue+Mountains%%2C+Australia%%7CBungle+Bungles%%2C+Australia' - '%%7CThe+Pinnacles%%2C+Australia&departure_time=%d' - '&traffic_model=optimistic' % - (self.key, time.mktime(now.timetuple())), - responses.calls[0].request.url) - + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/distancematrix/json?" + "origins=Perth%%2C+Australia%%7CSydney%%2C+Australia%%7C" + "Melbourne%%2C+Australia%%7CAdelaide%%2C+Australia%%7C" + "Brisbane%%2C+Australia%%7CDarwin%%2C+Australia%%7CHobart%%2C+" + "Australia%%7CCanberra%%2C+Australia&language=en-AU&" + "avoid=tolls&mode=driving&key=%s&units=imperial&" + "destinations=Uluru%%2C+Australia%%7CKakadu%%2C+Australia%%7C" + "Blue+Mountains%%2C+Australia%%7CBungle+Bungles%%2C+Australia" + "%%7CThe+Pinnacles%%2C+Australia&departure_time=%d" + "&traffic_model=optimistic" % (self.key, time.mktime(now.timetuple())), + responses.calls[0].request.url, + ) @responses.activate def test_lang_param(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/distancematrix/json', - body='{"status":"OK","rows":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/distancematrix/json", + body='{"status":"OK","rows":[]}', + status=200, + content_type="application/json", + ) origins = ["Vancouver BC", "Seattle"] destinations = ["San Francisco", "Victoria BC"] - matrix = self.client.distance_matrix(origins, destinations, - language="fr-FR", - mode="bicycling") + matrix = self.client.distance_matrix( + origins, destinations, language="fr-FR", mode="bicycling" + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/distancematrix/json?' - 'key=%s&language=fr-FR&mode=bicycling&' - 'origins=Vancouver+BC%%7CSeattle&' - 'destinations=San+Francisco%%7CVictoria+BC' % - self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/distancematrix/json?" + "key=%s&language=fr-FR&mode=bicycling&" + "origins=Vancouver+BC%%7CSeattle&" + "destinations=San+Francisco%%7CVictoria+BC" % self.key, + responses.calls[0].request.url, + ) diff --git a/googlemaps/test/test_elevation.py b/googlemaps/test/test_elevation.py index 41146939..dfd5abd3 100644 --- a/googlemaps/test/test_elevation.py +++ b/googlemaps/test/test_elevation.py @@ -26,91 +26,109 @@ class ElevationTest(_test.TestCase): - def setUp(self): - self.key = 'AIzaasdf' + self.key = "AIzaasdf" self.client = googlemaps.Client(self.key) @responses.activate def test_elevation_single(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/elevation/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/elevation/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) results = self.client.elevation((40.714728, -73.998672)) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/elevation/json?' - 'locations=enc:abowFtzsbM&key=%s' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/elevation/json?" + "locations=enc:abowFtzsbM&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_elevation_single_list(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/elevation/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/elevation/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) results = self.client.elevation([(40.714728, -73.998672)]) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/elevation/json?' - 'locations=enc:abowFtzsbM&key=%s' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/elevation/json?" + "locations=enc:abowFtzsbM&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_elevation_multiple(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/elevation/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/elevation/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) locations = [(40.714728, -73.998672), (-34.397, 150.644)] results = self.client.elevation(locations) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/elevation/json?' - 'locations=enc:abowFtzsbMhgmiMuobzi@&key=%s' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/elevation/json?" + "locations=enc:abowFtzsbMhgmiMuobzi@&key=%s" % self.key, + responses.calls[0].request.url, + ) def test_elevation_along_path_single(self): with self.assertRaises(googlemaps.exceptions.ApiError): - results = self.client.elevation_along_path( - [(40.714728, -73.998672)], 5) + results = self.client.elevation_along_path([(40.714728, -73.998672)], 5) @responses.activate def test_elevation_along_path(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/elevation/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/elevation/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) path = [(40.714728, -73.998672), (-34.397, 150.644)] results = self.client.elevation_along_path(path, 5) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/elevation/json?' - 'path=enc:abowFtzsbMhgmiMuobzi@&' - 'key=%s&samples=5' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/elevation/json?" + "path=enc:abowFtzsbMhgmiMuobzi@&" + "key=%s&samples=5" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_short_latlng(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/elevation/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/elevation/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) results = self.client.elevation((40, -73)) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/elevation/json?' - 'locations=40,-73&key=%s' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/elevation/json?" + "locations=40,-73&key=%s" % self.key, + responses.calls[0].request.url, + ) diff --git a/googlemaps/test/test_geocoding.py b/googlemaps/test/test_geocoding.py index 511e6d8f..96bf9586 100644 --- a/googlemaps/test/test_geocoding.py +++ b/googlemaps/test/test_geocoding.py @@ -27,257 +27,322 @@ class GeocodingTest(_test.TestCase): - def setUp(self): - self.key = 'AIzaasdf' + self.key = "AIzaasdf" self.client = googlemaps.Client(self.key) @responses.activate def test_simple_geocode(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) - results = self.client.geocode('Sydney') + results = self.client.geocode("Sydney") self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'key=%s&address=Sydney' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=%s&address=Sydney" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_reverse_geocode(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) results = self.client.reverse_geocode((-33.8674869, 151.2069902)) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'latlng=-33.867487%%2C151.20699&key=%s' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "latlng=-33.867487%%2C151.20699&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_geocoding_the_googleplex(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) - results = self.client.geocode('1600 Amphitheatre Parkway, ' - 'Mountain View, CA') + results = self.client.geocode("1600 Amphitheatre Parkway, " "Mountain View, CA") self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'key=%s&address=1600+Amphitheatre+Parkway%%2C+Mountain' - '+View%%2C+CA' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=%s&address=1600+Amphitheatre+Parkway%%2C+Mountain" + "+View%%2C+CA" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_geocode_with_bounds(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) - results = self.client.geocode('Winnetka', - bounds={'southwest': (34.172684, -118.604794), - 'northeast':(34.236144, -118.500938)}) + results = self.client.geocode( + "Winnetka", + bounds={ + "southwest": (34.172684, -118.604794), + "northeast": (34.236144, -118.500938), + }, + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'bounds=34.172684%%2C-118.604794%%7C34.236144%%2C' - '-118.500938&key=%s&address=Winnetka' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "bounds=34.172684%%2C-118.604794%%7C34.236144%%2C" + "-118.500938&key=%s&address=Winnetka" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_geocode_with_region_biasing(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) - results = self.client.geocode('Toledo', region='es') + results = self.client.geocode("Toledo", region="es") self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'region=es&key=%s&address=Toledo' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "region=es&key=%s&address=Toledo" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_geocode_with_component_filter(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) - results = self.client.geocode('santa cruz', - components={'country': 'ES'}) + results = self.client.geocode("santa cruz", components={"country": "ES"}) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'key=%s&components=country%%3AES&address=santa+cruz' % - self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=%s&components=country%%3AES&address=santa+cruz" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_geocode_with_multiple_component_filters(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) - results = self.client.geocode('Torun', - components={'administrative_area': 'TX','country': 'US'}) + results = self.client.geocode( + "Torun", components={"administrative_area": "TX", "country": "US"} + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'key=%s&components=administrative_area%%3ATX%%7C' - 'country%%3AUS&address=Torun' % self.key, - responses.calls[0].request.url) - + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=%s&components=administrative_area%%3ATX%%7C" + "country%%3AUS&address=Torun" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_geocode_with_just_components(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) results = self.client.geocode( - components={'route': 'Annegatan', - 'administrative_area': 'Helsinki', - 'country': 'Finland'}) + components={ + "route": "Annegatan", + "administrative_area": "Helsinki", + "country": "Finland", + } + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'key=%s&components=administrative_area%%3AHelsinki' - '%%7Ccountry%%3AFinland%%7Croute%%3AAnnegatan' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=%s&components=administrative_area%%3AHelsinki" + "%%7Ccountry%%3AFinland%%7Croute%%3AAnnegatan" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_simple_reverse_geocode(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) results = self.client.reverse_geocode((40.714224, -73.961452)) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'latlng=40.714224%%2C-73.961452&key=%s' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "latlng=40.714224%%2C-73.961452&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_reverse_geocode_restricted_by_type(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') - - results = self.client.reverse_geocode((40.714224, -73.961452), - location_type='ROOFTOP', - result_type='street_address') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) + + results = self.client.reverse_geocode( + (40.714224, -73.961452), + location_type="ROOFTOP", + result_type="street_address", + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'latlng=40.714224%%2C-73.961452&result_type=street_address&' - 'key=%s&location_type=ROOFTOP' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "latlng=40.714224%%2C-73.961452&result_type=street_address&" + "key=%s&location_type=ROOFTOP" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_reverse_geocode_multiple_location_types(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') - - results = self.client.reverse_geocode((40.714224, -73.961452), - location_type=['ROOFTOP', - 'RANGE_INTERPOLATED'], - result_type='street_address') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) + + results = self.client.reverse_geocode( + (40.714224, -73.961452), + location_type=["ROOFTOP", "RANGE_INTERPOLATED"], + result_type="street_address", + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'latlng=40.714224%%2C-73.961452&result_type=street_address&' - 'key=%s&location_type=ROOFTOP%%7CRANGE_INTERPOLATED' % - self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "latlng=40.714224%%2C-73.961452&result_type=street_address&" + "key=%s&location_type=ROOFTOP%%7CRANGE_INTERPOLATED" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_reverse_geocode_multiple_result_types(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') - - results = self.client.reverse_geocode((40.714224, -73.961452), - location_type='ROOFTOP', - result_type=['street_address', - 'route']) + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) + + results = self.client.reverse_geocode( + (40.714224, -73.961452), + location_type="ROOFTOP", + result_type=["street_address", "route"], + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'latlng=40.714224%%2C-73.961452&result_type=street_address' - '%%7Croute&key=%s&location_type=ROOFTOP' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "latlng=40.714224%%2C-73.961452&result_type=street_address" + "%%7Croute&key=%s&location_type=ROOFTOP" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_partial_match(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) - results = self.client.geocode('Pirrama Pyrmont') + results = self.client.geocode("Pirrama Pyrmont") self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'key=%s&address=Pirrama+Pyrmont' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=%s&address=Pirrama+Pyrmont" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_utf_results(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) - results = self.client.geocode(components={'postal_code': '96766'}) + results = self.client.geocode(components={"postal_code": "96766"}) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://maps.googleapis.com/maps/api/geocode/json?' - 'key=%s&components=postal_code%%3A96766' % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=%s&components=postal_code%%3A96766" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_utf8_request(self): - responses.add(responses.GET, - 'https://maps.googleapis.com/maps/api/geocode/json', - body='{"status":"OK","results":[]}', - status=200, - content_type='application/json') - - self.client.geocode(self.u('\\u4e2d\\u56fd')) # China + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/geocode/json", + body='{"status":"OK","results":[]}', + status=200, + content_type="application/json", + ) + + self.client.geocode(self.u("\\u4e2d\\u56fd")) # China self.assertURLEqual( - 'https://maps.googleapis.com/maps/api/geocode/json?' - 'key=%s&address=%s' % (self.key, '%E4%B8%AD%E5%9B%BD'), - responses.calls[0].request.url) + "https://maps.googleapis.com/maps/api/geocode/json?" + "key=%s&address=%s" % (self.key, "%E4%B8%AD%E5%9B%BD"), + responses.calls[0].request.url, + ) diff --git a/googlemaps/test/test_geolocation.py b/googlemaps/test/test_geolocation.py index 64b6f36a..62f74f34 100644 --- a/googlemaps/test/test_geolocation.py +++ b/googlemaps/test/test_geolocation.py @@ -25,21 +25,24 @@ class GeolocationTest(_test.TestCase): - def setUp(self): - self.key = 'AIzaasdf' + self.key = "AIzaasdf" self.client = googlemaps.Client(self.key) @responses.activate def test_simple_geolocate(self): - responses.add(responses.POST, - 'https://www.googleapis.com/geolocation/v1/geolocate', - body='{"location": {"lat": 51.0,"lng": -0.1},"accuracy": 1200.4}', - status=200, - content_type='application/json') + responses.add( + responses.POST, + "https://www.googleapis.com/geolocation/v1/geolocate", + body='{"location": {"lat": 51.0,"lng": -0.1},"accuracy": 1200.4}', + status=200, + content_type="application/json", + ) results = self.client.geolocate() self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('https://www.googleapis.com/geolocation/v1/geolocate?' - 'key=%s' % self.key, responses.calls[0].request.url) + self.assertURLEqual( + "https://www.googleapis.com/geolocation/v1/geolocate?" "key=%s" % self.key, + responses.calls[0].request.url, + ) diff --git a/googlemaps/test/test_places.py b/googlemaps/test/test_places.py index 6bb4aa1e..dbc1a5de 100644 --- a/googlemaps/test/test_places.py +++ b/googlemaps/test/test_places.py @@ -27,51 +27,76 @@ class PlacesTest(_test.TestCase): - def setUp(self): - self.key = 'AIzaasdf' + self.key = "AIzaasdf" self.client = googlemaps.Client(self.key) self.location = (-33.86746, 151.207090) - self.type = 'liquor_store' - self.language = 'en-AU' - self.region = 'AU' + self.type = "liquor_store" + self.language = "en-AU" + self.region = "AU" self.radius = 100 @responses.activate def test_places_text_search(self): - url = 'https://maps.googleapis.com/maps/api/place/textsearch/json' - responses.add(responses.GET, url, - body='{"status": "OK", "results": [], "html_attributions": []}', - status=200, content_type='application/json') - - self.client.places('restaurant', location=self.location, - radius=self.radius, region=self.region, language=self.language, - min_price=1, max_price=4, open_now=True, - type=self.type) + url = "https://maps.googleapis.com/maps/api/place/textsearch/json" + responses.add( + responses.GET, + url, + body='{"status": "OK", "results": [], "html_attributions": []}', + status=200, + content_type="application/json", + ) + + self.client.places( + "restaurant", + location=self.location, + radius=self.radius, + region=self.region, + language=self.language, + min_price=1, + max_price=4, + open_now=True, + type=self.type, + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('%s?language=en-AU&location=-33.86746%%2C151.20709&' - 'maxprice=4&minprice=1&opennow=true&query=restaurant&' - 'radius=100®ion=AU&type=liquor_store&key=%s' - % (url, self.key), responses.calls[0].request.url) + self.assertURLEqual( + "%s?language=en-AU&location=-33.86746%%2C151.20709&" + "maxprice=4&minprice=1&opennow=true&query=restaurant&" + "radius=100®ion=AU&type=liquor_store&key=%s" % (url, self.key), + responses.calls[0].request.url, + ) @responses.activate def test_places_nearby_search(self): - url = 'https://maps.googleapis.com/maps/api/place/nearbysearch/json' - responses.add(responses.GET, url, - body='{"status": "OK", "results": [], "html_attributions": []}', - status=200, content_type='application/json') - - self.client.places_nearby(location=self.location, keyword='foo', - language=self.language, min_price=1, - max_price=4, name='bar', open_now=True, - rank_by='distance', type=self.type) + url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json" + responses.add( + responses.GET, + url, + body='{"status": "OK", "results": [], "html_attributions": []}', + status=200, + content_type="application/json", + ) + + self.client.places_nearby( + location=self.location, + keyword="foo", + language=self.language, + min_price=1, + max_price=4, + name="bar", + open_now=True, + rank_by="distance", + type=self.type, + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('%s?keyword=foo&language=en-AU&location=-33.86746%%2C151.20709&' - 'maxprice=4&minprice=1&name=bar&opennow=true&rankby=distance&' - 'type=liquor_store&key=%s' - % (url, self.key), responses.calls[0].request.url) + self.assertURLEqual( + "%s?keyword=foo&language=en-AU&location=-33.86746%%2C151.20709&" + "maxprice=4&minprice=1&name=bar&opennow=true&rankby=distance&" + "type=liquor_store&key=%s" % (url, self.key), + responses.calls[0].request.url, + ) with self.assertRaises(ValueError): self.client.places_nearby(radius=self.radius) @@ -79,85 +104,126 @@ def test_places_nearby_search(self): self.client.places_nearby(self.location, rank_by="distance") with self.assertRaises(ValueError): - self.client.places_nearby(location=self.location, rank_by="distance", - keyword='foo', radius=self.radius) + self.client.places_nearby( + location=self.location, + rank_by="distance", + keyword="foo", + radius=self.radius, + ) @responses.activate def test_places_radar_search(self): - url = 'https://maps.googleapis.com/maps/api/place/radarsearch/json' - responses.add(responses.GET, url, - body='{"status": "OK", "results": [], "html_attributions": []}', - status=200, content_type='application/json') - - self.client.places_radar(self.location, self.radius, keyword='foo', - min_price=1, max_price=4, name='bar', - open_now=True, type=self.type) + url = "https://maps.googleapis.com/maps/api/place/radarsearch/json" + responses.add( + responses.GET, + url, + body='{"status": "OK", "results": [], "html_attributions": []}', + status=200, + content_type="application/json", + ) + + self.client.places_radar( + self.location, + self.radius, + keyword="foo", + min_price=1, + max_price=4, + name="bar", + open_now=True, + type=self.type, + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('%s?keyword=foo&location=-33.86746%%2C151.20709&' - 'maxprice=4&minprice=1&name=bar&opennow=true&radius=100&' - 'type=liquor_store&key=%s' - % (url, self.key), responses.calls[0].request.url) + self.assertURLEqual( + "%s?keyword=foo&location=-33.86746%%2C151.20709&" + "maxprice=4&minprice=1&name=bar&opennow=true&radius=100&" + "type=liquor_store&key=%s" % (url, self.key), + responses.calls[0].request.url, + ) with self.assertRaises(ValueError): self.client.places_radar(self.location, self.radius) @responses.activate def test_place_detail(self): - url = 'https://maps.googleapis.com/maps/api/place/details/json' - responses.add(responses.GET, url, - body='{"status": "OK", "result": {}, "html_attributions": []}', - status=200, content_type='application/json') + url = "https://maps.googleapis.com/maps/api/place/details/json" + responses.add( + responses.GET, + url, + body='{"status": "OK", "result": {}, "html_attributions": []}', + status=200, + content_type="application/json", + ) - self.client.place('ChIJN1t_tDeuEmsRUsoyG83frY4', language=self.language) + self.client.place("ChIJN1t_tDeuEmsRUsoyG83frY4", language=self.language) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('%s?language=en-AU&placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=%s' - % (url, self.key), responses.calls[0].request.url) + self.assertURLEqual( + "%s?language=en-AU&placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=%s" + % (url, self.key), + responses.calls[0].request.url, + ) @responses.activate def test_photo(self): - url = 'https://maps.googleapis.com/maps/api/place/photo' + url = "https://maps.googleapis.com/maps/api/place/photo" responses.add(responses.GET, url, status=200) - ref = 'CnRvAAAAwMpdHeWlXl-lH0vp7lez4znKPIWSWvgvZFISdKx45AwJVP1Qp37YOrH7sqHMJ8C-vBDC546decipPHchJhHZL94RcTUfPa1jWzo-rSHaTlbNtjh-N68RkcToUCuY9v2HNpo5mziqkir37WU8FJEqVBIQ4k938TI3e7bf8xq-uwDZcxoUbO_ZJzPxremiQurAYzCTwRhE_V0' + ref = "CnRvAAAAwMpdHeWlXl-lH0vp7lez4znKPIWSWvgvZFISdKx45AwJVP1Qp37YOrH7sqHMJ8C-vBDC546decipPHchJhHZL94RcTUfPa1jWzo-rSHaTlbNtjh-N68RkcToUCuY9v2HNpo5mziqkir37WU8FJEqVBIQ4k938TI3e7bf8xq-uwDZcxoUbO_ZJzPxremiQurAYzCTwRhE_V0" response = self.client.places_photo(ref, max_width=100) self.assertTrue(isinstance(response, GeneratorType)) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('%s?maxwidth=100&photoreference=%s&key=%s' - % (url, ref, self.key), responses.calls[0].request.url) + self.assertURLEqual( + "%s?maxwidth=100&photoreference=%s&key=%s" % (url, ref, self.key), + responses.calls[0].request.url, + ) @responses.activate def test_autocomplete(self): - url = 'https://maps.googleapis.com/maps/api/place/autocomplete/json' - responses.add(responses.GET, url, - body='{"status": "OK", "predictions": []}', - status=200, content_type='application/json') - - self.client.places_autocomplete('Google', offset=3, - location=self.location, - radius=self.radius, - language=self.language, - types='geocode', - components={'country': 'au'}, - strict_bounds=True) + url = "https://maps.googleapis.com/maps/api/place/autocomplete/json" + responses.add( + responses.GET, + url, + body='{"status": "OK", "predictions": []}', + status=200, + content_type="application/json", + ) + + self.client.places_autocomplete( + "Google", + offset=3, + location=self.location, + radius=self.radius, + language=self.language, + types="geocode", + components={"country": "au"}, + strict_bounds=True, + ) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('%s?components=country%%3Aau&input=Google&language=en-AU&' - 'location=-33.86746%%2C151.20709&offset=3&radius=100&' - 'strictbounds=true&types=geocode&key=%s' % - (url, self.key), responses.calls[0].request.url) + self.assertURLEqual( + "%s?components=country%%3Aau&input=Google&language=en-AU&" + "location=-33.86746%%2C151.20709&offset=3&radius=100&" + "strictbounds=true&types=geocode&key=%s" % (url, self.key), + responses.calls[0].request.url, + ) @responses.activate def test_autocomplete_query(self): - url = 'https://maps.googleapis.com/maps/api/place/queryautocomplete/json' - responses.add(responses.GET, url, - body='{"status": "OK", "predictions": []}', - status=200, content_type='application/json') + url = "https://maps.googleapis.com/maps/api/place/queryautocomplete/json" + responses.add( + responses.GET, + url, + body='{"status": "OK", "predictions": []}', + status=200, + content_type="application/json", + ) - self.client.places_autocomplete_query('pizza near New York') + self.client.places_autocomplete_query("pizza near New York") self.assertEqual(1, len(responses.calls)) - self.assertURLEqual('%s?input=pizza+near+New+York&key=%s' % - (url, self.key), responses.calls[0].request.url) + self.assertURLEqual( + "%s?input=pizza+near+New+York&key=%s" % (url, self.key), + responses.calls[0].request.url, + ) diff --git a/googlemaps/test/test_roads.py b/googlemaps/test/test_roads.py index 6e11b604..6635186a 100644 --- a/googlemaps/test/test_roads.py +++ b/googlemaps/test/test_roads.py @@ -25,88 +25,107 @@ class RoadsTest(_test.TestCase): - def setUp(self): self.key = "AIzaasdf" self.client = googlemaps.Client(self.key) @responses.activate def test_snap(self): - responses.add(responses.GET, - "https://roads.googleapis.com/v1/snapToRoads", - body='{"snappedPoints":["foo"]}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://roads.googleapis.com/v1/snapToRoads", + body='{"snappedPoints":["foo"]}', + status=200, + content_type="application/json", + ) results = self.client.snap_to_roads((40.714728, -73.998672)) self.assertEqual("foo", results[0]) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual("https://roads.googleapis.com/v1/snapToRoads?" - "path=40.714728%%2C-73.998672&key=%s" % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://roads.googleapis.com/v1/snapToRoads?" + "path=40.714728%%2C-73.998672&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_nearest_roads(self): - responses.add(responses.GET, - "https://roads.googleapis.com/v1/nearestRoads", - body='{"snappedPoints":["foo"]}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://roads.googleapis.com/v1/nearestRoads", + body='{"snappedPoints":["foo"]}', + status=200, + content_type="application/json", + ) results = self.client.nearest_roads((40.714728, -73.998672)) self.assertEqual("foo", results[0]) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual("https://roads.googleapis.com/v1/nearestRoads?" - "points=40.714728%%2C-73.998672&key=%s" % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://roads.googleapis.com/v1/nearestRoads?" + "points=40.714728%%2C-73.998672&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_path(self): - responses.add(responses.GET, - "https://roads.googleapis.com/v1/speedLimits", - body='{"speedLimits":["foo"]}', - status=200, - content_type="application/json") - - results = self.client.snapped_speed_limits([(1, 2),(3, 4)]) + responses.add( + responses.GET, + "https://roads.googleapis.com/v1/speedLimits", + body='{"speedLimits":["foo"]}', + status=200, + content_type="application/json", + ) + + results = self.client.snapped_speed_limits([(1, 2), (3, 4)]) self.assertEqual("foo", results["speedLimits"][0]) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual("https://roads.googleapis.com/v1/speedLimits?" - "path=1%%2C2|3%%2C4" - "&key=%s" % self.key, - responses.calls[0].request.url) + self.assertURLEqual( + "https://roads.googleapis.com/v1/speedLimits?" + "path=1%%2C2|3%%2C4" + "&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_speedlimits(self): - responses.add(responses.GET, - "https://roads.googleapis.com/v1/speedLimits", - body='{"speedLimits":["foo"]}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://roads.googleapis.com/v1/speedLimits", + body='{"speedLimits":["foo"]}', + status=200, + content_type="application/json", + ) results = self.client.speed_limits("id1") self.assertEqual("foo", results[0]) - self.assertEqual("https://roads.googleapis.com/v1/speedLimits?" - "placeId=id1&key=%s" % self.key, - responses.calls[0].request.url) + self.assertEqual( + "https://roads.googleapis.com/v1/speedLimits?" + "placeId=id1&key=%s" % self.key, + responses.calls[0].request.url, + ) @responses.activate def test_speedlimits_multiple(self): - responses.add(responses.GET, - "https://roads.googleapis.com/v1/speedLimits", - body='{"speedLimits":["foo"]}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://roads.googleapis.com/v1/speedLimits", + body='{"speedLimits":["foo"]}', + status=200, + content_type="application/json", + ) results = self.client.speed_limits(["id1", "id2", "id3"]) self.assertEqual("foo", results[0]) - self.assertEqual("https://roads.googleapis.com/v1/speedLimits?" - "placeId=id1&placeId=id2&placeId=id3" - "&key=%s" % self.key, - responses.calls[0].request.url) + self.assertEqual( + "https://roads.googleapis.com/v1/speedLimits?" + "placeId=id1&placeId=id2&placeId=id3" + "&key=%s" % self.key, + responses.calls[0].request.url, + ) def test_clientid_not_accepted(self): client = googlemaps.Client(client_id="asdf", client_secret="asdf") @@ -123,13 +142,15 @@ def __init__(self): def __call__(self, req): if self.first_req: self.first_req = False - return (500, {}, 'Internal Server Error.') + return (500, {}, "Internal Server Error.") return (200, {}, '{"speedLimits":[]}') - responses.add_callback(responses.GET, - "https://roads.googleapis.com/v1/speedLimits", - content_type="application/json", - callback=request_callback()) + responses.add_callback( + responses.GET, + "https://roads.googleapis.com/v1/speedLimits", + content_type="application/json", + callback=request_callback(), + ) self.client.speed_limits([]) diff --git a/googlemaps/test/test_timezone.py b/googlemaps/test/test_timezone.py index 23daeca3..1be109ee 100644 --- a/googlemaps/test/test_timezone.py +++ b/googlemaps/test/test_timezone.py @@ -28,51 +28,56 @@ class TimezoneTest(_test.TestCase): - def setUp(self): self.key = "AIzaasdf" self.client = googlemaps.Client(self.key) @responses.activate def test_los_angeles(self): - responses.add(responses.GET, - "https://maps.googleapis.com/maps/api/timezone/json", - body='{"status":"OK"}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/timezone/json", + body='{"status":"OK"}', + status=200, + content_type="application/json", + ) ts = 1331766000 timezone = self.client.timezone((39.603481, -119.682251), ts) self.assertIsNotNone(timezone) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual("https://maps.googleapis.com/maps/api/timezone/json" - "?location=39.603481,-119.682251×tamp=%d" - "&key=%s" % - (ts, self.key), - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/timezone/json" + "?location=39.603481,-119.682251×tamp=%d" + "&key=%s" % (ts, self.key), + responses.calls[0].request.url, + ) class MockDatetime(object): - def now(self): return datetime.datetime.fromtimestamp(1608) + utcnow = now @responses.activate @mock.patch("googlemaps.timezone.datetime", MockDatetime()) def test_los_angeles_with_no_timestamp(self): - responses.add(responses.GET, - "https://maps.googleapis.com/maps/api/timezone/json", - body='{"status":"OK"}', - status=200, - content_type="application/json") + responses.add( + responses.GET, + "https://maps.googleapis.com/maps/api/timezone/json", + body='{"status":"OK"}', + status=200, + content_type="application/json", + ) timezone = self.client.timezone((39.603481, -119.682251)) self.assertIsNotNone(timezone) self.assertEqual(1, len(responses.calls)) - self.assertURLEqual("https://maps.googleapis.com/maps/api/timezone/json" - "?location=39.603481,-119.682251×tamp=%d" - "&key=%s" % - (1608, self.key), - responses.calls[0].request.url) + self.assertURLEqual( + "https://maps.googleapis.com/maps/api/timezone/json" + "?location=39.603481,-119.682251×tamp=%d" + "&key=%s" % (1608, self.key), + responses.calls[0].request.url, + ) diff --git a/googlemaps/timezone.py b/googlemaps/timezone.py index 0b6370dc..7db4e20d 100644 --- a/googlemaps/timezone.py +++ b/googlemaps/timezone.py @@ -45,10 +45,10 @@ def timezone(client, location, timestamp=None, language=None): params = { "location": convert.latlng(location), - "timestamp": convert.time(timestamp or datetime.utcnow()) + "timestamp": convert.time(timestamp or datetime.utcnow()), } if language: params["language"] = language - return client._request( "/maps/api/timezone/json", params) + return client._request("/maps/api/timezone/json", params) diff --git a/setup.py b/setup.py index 6ab70806..88527baa 100644 --- a/setup.py +++ b/setup.py @@ -2,41 +2,41 @@ try: - from setuptools import setup + from setuptools import setup except ImportError: - from distutils.core import setup + from distutils.core import setup if sys.version_info <= (2, 4): - error = 'Requires Python Version 2.5 or above... exiting.' - print >> sys.stderr, error - sys.exit(1) + error = "Requires Python Version 2.5 or above... exiting." + print >>sys.stderr, error + sys.exit(1) -requirements = [ - 'requests>=2.11.1,<3.0', -] +requirements = ["requests>=2.11.1,<3.0"] -setup(name='googlemaps', - version='2.5.1-dev', - description='Python client library for Google Maps API Web Services', - scripts=[], - url='https://github.com/googlemaps/google-maps-services-python', - packages=['googlemaps'], - license='Apache 2.0', - platforms='Posix; MacOS X; Windows', - setup_requires=requirements, - install_requires=requirements, - test_suite='googlemaps.test', - classifiers=['Development Status :: 4 - Beta', - 'Intended Audience :: Developers', - 'License :: OSI Approved :: Apache Software License', - 'Operating System :: OS Independent', - 'Programming Language :: Python :: 2.7', - 'Programming Language :: Python :: 3.2', - 'Programming Language :: Python :: 3.4', - 'Programming Language :: Python :: 3.5', - 'Programming Language :: Python :: 3.6', - 'Topic :: Internet', - ] - ) +setup( + name="googlemaps", + version="2.5.1-dev", + description="Python client library for Google Maps API Web Services", + scripts=[], + url="https://github.com/googlemaps/google-maps-services-python", + packages=["googlemaps"], + license="Apache 2.0", + platforms="Posix; MacOS X; Windows", + setup_requires=requirements, + install_requires=requirements, + test_suite="googlemaps.test", + classifiers=[ + "Development Status :: 4 - Beta", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3.2", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Topic :: Internet", + ], +)