From 4fb2586851b443ea2f77c85ca7c18ef0aa2b818f Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Tue, 3 Sep 2019 17:56:09 +0200 Subject: [PATCH 1/4] style: reformat using black Small refreshment for the package style. --- .coveragerc | 6 +- .flake8 | 4 + .pre-commit-config.yaml | 9 + .travis.yml | 56 ++- LICENSE | 209 ++++++++- README.txt | 2 - setup.cfg | 15 + setup.py | 70 +-- ticketbis/__init__.py | 595 +++++++++++++++---------- ticketbis/tests/__init__.py | 80 ++-- ticketbis/tests/_creds.example.py | 26 +- ticketbis/tests/test_categories.py | 35 +- ticketbis/tests/test_events.py | 45 +- ticketbis/tests/test_oauth.py | 23 +- ticketbis/tests/test_schemas.py | 33 +- ticketbis/tests/test_section_groups.py | 34 +- ticketbis/tests/test_sites.py | 35 +- ticketbis/tests/test_venues.py | 40 +- ticketbis/version.py | 18 + 19 files changed, 923 insertions(+), 412 deletions(-) create mode 100644 .flake8 create mode 100644 .pre-commit-config.yaml delete mode 100644 README.txt create mode 100644 setup.cfg create mode 100644 ticketbis/version.py diff --git a/.coveragerc b/.coveragerc index 294e07b..4bcf2d0 100644 --- a/.coveragerc +++ b/.coveragerc @@ -7,6 +7,6 @@ omit = */site-packages/nose/* */unittest2/* -exclude_lines = - # Have to re-enable the standard pragma - pragma: no cover +# exclude_lines = +# # Have to re-enable the standard pragma +# pragma: no cover diff --git a/.flake8 b/.flake8 new file mode 100644 index 0000000..8965fde --- /dev/null +++ b/.flake8 @@ -0,0 +1,4 @@ +[flake8] +max-line-length = 80 +select = C,E,F,W,B,B950 +ignore = E203,E501,W503 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..bf5fa28 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,9 @@ +repos: +- repo: https://github.com/ambv/black + rev: stable + hooks: + - id: black +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v2.2.1 + hooks: + - id: flake8 diff --git a/.travis.yml b/.travis.yml index 6e5acdc..e7208e2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,15 +1,49 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License + +notifications: + email: false + +sudo: false + language: python + +cache: + pip: true + directories: + - /home/travis/.cache/pre-commit/ + python: -- '2.6' -- '2.7' -- '3.4' + - "3.7" + - "3.6" + - "2.7" + +# env: +# global: +# - secure: ZyrUCICwX+Nzyl+iXjQklwlNdLfVuBb3UZRyARIiLfh70xLY2p7CT5+Ngc7l985ETwmXQmvUIIDRvYZnN7XIZhRsX9EMkYBlRIsNoUOaVsdWDTNlj6gBE47BVUvJduUrRgjvoVjeewG+NRv//KtJ1OwPu0tGDRlJdOMd7JGvyOs= +# - secure: vu1/nBWXAHk5emJkLSkNBJU4nt5IX9v2UAnd6ACZLRKANj1gH4WlX5w60MJ4UJF3HOBABftoBXyWrhs5iaQ0Ub8i71DncyBAEk+Esgck5IuWNhKuKTK+Y5p8f69cnHacC9AFKPJNInKrppoLYE+qaTgdmHAyXdiI/BeiBBxQuB8= +# - secure: ccozIsQQXnRkghE18z6YCeEExY5sGqwWjCkLJALL58+lwlOC+4t5FE4rV5OL16tyUV7mJ4w6j4waINvE3dVRjUIYQWbr3QQGIgy1f4sa/0QDGmhp2W2fkls2AAUPojE3QfbcxfjiYXDmnEaO5KyyDjNZ6earWIIyqIw08PICJBQ= + install: -- pip install coverage six --use-mirrors -- pip install . --use-mirrors + - travis_retry pip install -U coverage coveralls pip pre-commit setuptools twine wheel + - travis_retry pip install -e . + script: -- nosetests --with-coverage --cover-package=foursquare -env: - global: - - secure: ZyrUCICwX+Nzyl+iXjQklwlNdLfVuBb3UZRyARIiLfh70xLY2p7CT5+Ngc7l985ETwmXQmvUIIDRvYZnN7XIZhRsX9EMkYBlRIsNoUOaVsdWDTNlj6gBE47BVUvJduUrRgjvoVjeewG+NRv//KtJ1OwPu0tGDRlJdOMd7JGvyOs= # ACCESS_TOKEN - - secure: vu1/nBWXAHk5emJkLSkNBJU4nt5IX9v2UAnd6ACZLRKANj1gH4WlX5w60MJ4UJF3HOBABftoBXyWrhs5iaQ0Ub8i71DncyBAEk+Esgck5IuWNhKuKTK+Y5p8f69cnHacC9AFKPJNInKrppoLYE+qaTgdmHAyXdiI/BeiBBxQuB8= # CLIENT_ID - - secure: ccozIsQQXnRkghE18z6YCeEExY5sGqwWjCkLJALL58+lwlOC+4t5FE4rV5OL16tyUV7mJ4w6j4waINvE3dVRjUIYQWbr3QQGIgy1f4sa/0QDGmhp2W2fkls2AAUPojE3QfbcxfjiYXDmnEaO5KyyDjNZ6earWIIyqIw08PICJBQ= # CLIENT_SECRET + - pre-commit run -a + - nosetests --with-coverage --cover-package=ticketbis + +after_success: + - coveralls diff --git a/LICENSE b/LICENSE index 04325ba..d645695 100644 --- a/LICENSE +++ b/LICENSE @@ -1,13 +1,202 @@ -Copyright 2015 Ticketbis -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ - http://www.apache.org/licenses/LICENSE-2.0 + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.txt b/README.txt deleted file mode 100644 index 57091bb..0000000 --- a/README.txt +++ /dev/null @@ -1,2 +0,0 @@ -Python wrapper for the Ticketbis API. - diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..89ae6b8 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,15 @@ +# -*- coding: utf-8 -*- + +[aliases] +test = pytest + +[build_sphinx] +source-dir = docs/ +build-dir = docs/_build +all_files = 1 + +[bdist_wheel] +universal = 1 + +[pydocstyle] +add_ignore = D401 diff --git a/setup.py b/setup.py index 01f0796..7de5e7c 100755 --- a/setup.py +++ b/setup.py @@ -1,37 +1,53 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Python wrapper for the Ticketbis API.""" -from setuptools import setup, find_packages +import os -import ticketbis -version = str(ticketbis.__version__) +from setuptools import find_packages, setup + +# Get the version string. Cannot be done with import! +g = {} +with open(os.path.join("ticketbis", "version.py"), "rt") as fp: + exec(fp.read(), g) + version = g["__version__"] setup( - name='ticketbis', + name="ticketbis", version=version, - author='Jose Gargallo', - author_email='jose.gargallo@ticketbis.com', - url='https://github.com/ticketbis/ticketbis-python-api-client', - description='ticketbis API wrapper library', - long_description=open('./README.txt', 'r').read(), - download_url='https://github.com/ticketbis/ticketbis-python-api-client', + author="Ticketbis", + author_email="engineering@stubhub.com", + url="https://github.com/ticketbis/ticketbis-python-api-client", + description=__doc__, + long_description=open("./README.md", "r").read(), + long_description_content_type="text/markdown", + download_url="https://github.com/ticketbis/ticketbis-python-api-client", classifiers=[ - 'Development Status :: 5 - Production/Stable', - 'Intended Audience :: Developers', - 'Natural Language :: English', - 'Operating System :: OS Independent', - 'Programming Language :: Python', - 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', - 'License :: OSI Approved :: MIT License', - ], - packages=find_packages(), - install_requires=[ - 'requests>=2.1', - 'six', + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Natural Language :: English", + "Operating System :: OS Independent", + "Programming Language :: Python", + "Topic :: Internet :: WWW/HTTP :: Dynamic Content", + "License :: OSI Approved :: Apache Software License", ], - license='MIT License', - keywords='ticketbis api', + packages=find_packages(), + install_requires=["requests>=2.1", "six"], + license="MIT License", + keywords="ticketbis api", include_package_data=True, zip_safe=True, ) diff --git a/ticketbis/__init__.py b/ticketbis/__init__.py index b5dfb87..d04b9b1 100644 --- a/ticketbis/__init__.py +++ b/ticketbis/__init__.py @@ -1,7 +1,33 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis -import logging; log = logging.getLogger(__name__) +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Python wrapper for the Ticketbis API.""" + +import inspect +import logging +import math +import sys +import time +from copy import copy + +from .version import __version__ + +__all__ = ("__version__", "Ticketbis") + +log = logging.getLogger(__name__) # Try to load JSON libraries in this order: # ujson -> simplejson -> json @@ -13,11 +39,6 @@ except ImportError: import json -import inspect -import math -import time -import sys -from copy import copy # 3rd party libraries that might not be present during initial install try: @@ -40,6 +61,7 @@ # Enables debugging at httplib level (requests->urllib3->httplib) # The only thing missing will be the response.body which is not logged. import httplib + httplib.HTTPConnection.debuglevel = 1 # You must initialize logging, otherwise you'll not see debug output. @@ -53,13 +75,11 @@ # Default API version. API_VERSION = 1 -# Library versioning matches supported ticketbis API version -__version__ = '0.3.5' -__author__ = u'Jose Gargallo' +__author__ = "Ticketbis (StubHub)" -API_ENDPOINT = 'https://api.ticketbis.com/' -AUTH_ENDPOINT = 'oauth/authorize/' -TOKEN_ENDPOINT = 'oauth/token/' +API_ENDPOINT = "https://api.ticketbis.com/" +AUTH_ENDPOINT = "oauth/authorize/" +TOKEN_ENDPOINT = "oauth/token/" # Number of times to retry http requests NUM_REQUEST_RETRIES = 1 @@ -71,49 +91,99 @@ VERIFY_SSL = True # Grant types supported -AUTH_CODE_GRANT_TYPE = 'authorization_code' -CLIENT_CRED_GRANT_TYPE = 'client_credentials' +AUTH_CODE_GRANT_TYPE = "authorization_code" +CLIENT_CRED_GRANT_TYPE = "client_credentials" # Exceptions -class TicketbisException(RuntimeError): pass -class InvalidAuth(TicketbisException): pass -class ParamError(TicketbisException): pass -class EndpointError(TicketbisException): pass -class NotAuthorized(TicketbisException): pass -class RateLimitExceeded(TicketbisException): pass -class Deprecated(TicketbisException): pass -class ServerError(TicketbisException): pass -class FailedGeocode(TicketbisException): pass -class PreconditionFailed(TicketbisException): pass -class Other(TicketbisException): pass +class TicketbisException(RuntimeError): + """Base Ticketbis exception.""" + + +class InvalidAuth(TicketbisException): + pass + + +class ParamError(TicketbisException): + pass + + +class EndpointError(TicketbisException): + pass + + +class NotAuthorized(TicketbisException): + pass + + +class RateLimitExceeded(TicketbisException): + pass + + +class Deprecated(TicketbisException): + pass + + +class ServerError(TicketbisException): + pass + + +class FailedGeocode(TicketbisException): + pass + + +class PreconditionFailed(TicketbisException): + pass + + +class Other(TicketbisException): + pass + error_types = { - 'invalid_auth': InvalidAuth, - 'param_error': ParamError, - 'endpoint_error': EndpointError, - 'not_authorized': NotAuthorized, - 'rate_limit_exceeded': RateLimitExceeded, - 'deprecated': Deprecated, - 'server_error': ServerError, - 'failed_geocode': FailedGeocode, - 'other': Other, + "invalid_auth": InvalidAuth, + "param_error": ParamError, + "endpoint_error": EndpointError, + "not_authorized": NotAuthorized, + "rate_limit_exceeded": RateLimitExceeded, + "deprecated": Deprecated, + "server_error": ServerError, + "failed_geocode": FailedGeocode, + "other": Other, } - class Ticketbis(object): """Ticketbis API wrapper""" - def __init__(self, client_id=None, client_secret=None, access_token=None, - redirect_uri=None, version=None, site=None, lang='en-gb', - grant_type=AUTH_CODE_GRANT_TYPE, api_endpoint=API_ENDPOINT, auth=None): + def __init__( + self, + client_id=None, + client_secret=None, + access_token=None, + redirect_uri=None, + version=None, + site=None, + lang="en-gb", + grant_type=AUTH_CODE_GRANT_TYPE, + api_endpoint=API_ENDPOINT, + auth=None, + ): """Sets up the api object""" - self.oauth = self.OAuth(api_endpoint, client_id, client_secret, - redirect_uri, grant_type) + self.oauth = self.OAuth( + api_endpoint, client_id, client_secret, redirect_uri, grant_type + ) # Set up endpoints - self.base_requester = self.Requester(api_endpoint, client_id, client_secret, - access_token, version, site, lang, auth) + self.base_requester = self.Requester( + api_endpoint, + client_id, + client_secret, + access_token, + version, + site, + lang, + auth, + ) # Dynamically enable endpoints self._attach_endpoints() @@ -122,13 +192,16 @@ def __init__(self, client_id=None, client_secret=None, access_token=None, if not site and access_token: # forces API to return site according to lang # (gets site from response header) - self.sites(params={'max': 1}) + self.sites(params={"max": 1}) def _attach_endpoints(self): """Dynamically attach endpoint callables to this client""" for name, endpoint in inspect.getmembers(self): - if inspect.isclass(endpoint) and issubclass(endpoint, - self._Endpoint) and (endpoint is not self._Endpoint): + if ( + inspect.isclass(endpoint) + and issubclass(endpoint, self._Endpoint) + and (endpoint is not self._Endpoint) + ): endpoint_instance = endpoint(self.base_requester) setattr(self, endpoint_instance.endpoint, endpoint_instance) @@ -161,19 +234,20 @@ def site(self): """Returns site name""" return self.base_requester.site - @property def rate_remaining(self): - """ - Returns the remaining rate limit for the last API call - i.e. X-RateLimit-Remaining + """Return the remaining rate limit for the last API call. + + See ``X-RateLimit-Remaining`` header. """ return self.base_requester.rate_remaining class OAuth(object): - """Handles OAuth authentication procedures and helps retrieve tokens""" - def __init__(self, api_endpoint, client_id, client_secret, redirect_uri, - grant_type): + """Handle OAuth authentication procedures and helps retrieve tokens""" + + def __init__( + self, api_endpoint, client_id, client_secret, redirect_uri, grant_type + ): self.api_endpoint = api_endpoint self.client_id = client_id self.client_secret = client_secret @@ -181,46 +255,56 @@ def __init__(self, api_endpoint, client_id, client_secret, redirect_uri, self.grant_type = grant_type def auth_url(self): - """Gets the url a user needs to access to give up a user token""" + """Get the url a user needs to access to give up a user token""" params = { - 'client_id': self.client_id, - 'response_type': u'code', - 'redirect_uri': self.redirect_uri, + "client_id": self.client_id, + "response_type": u"code", + "redirect_uri": self.redirect_uri, } - return '{API_ENDPOINT}{AUTH_ENDPOINT}?{params}'.format( + return "{API_ENDPOINT}{AUTH_ENDPOINT}?{params}".format( API_ENDPOINT=self.api_endpoint, AUTH_ENDPOINT=AUTH_ENDPOINT, - params=parse.urlencode(params)) + params=parse.urlencode(params), + ) - def get_token(self, code=None, scope='read write'): - """Gets the auth token from a user's response""" + def get_token(self, code=None, scope="read write"): + """Get the auth token from a user's response""" params = { - 'client_id': self.client_id, - 'client_secret': self.client_secret, - 'grant_type': self.grant_type, + "client_id": self.client_id, + "client_secret": self.client_secret, + "grant_type": self.grant_type, } if self.grant_type == AUTH_CODE_GRANT_TYPE: - params['redirect_uri'] = self.redirect_uri + params["redirect_uri"] = self.redirect_uri if not code: - log.error(u'Code not provided') + log.error(u"Code not provided") return None else: - params['code'] = six.u(code) + params["code"] = six.u(code) elif self.grant_type == CLIENT_CRED_GRANT_TYPE: - params['scope'] = scope - + params["scope"] = scope # Get the response from the token uri and attempt to parse - token_endpoint = '{0}{1}'.format(self.api_endpoint, TOKEN_ENDPOINT) + token_endpoint = "{0}{1}".format(self.api_endpoint, TOKEN_ENDPOINT) res = _post(token_endpoint, data=params) - return res['data']['access_token'] + return res["data"]["access_token"] class Requester(object): - """Api requesting object""" - def __init__(self, api_endpoint, client_id=None, client_secret=None, - access_token=None, version=None, site=None, lang=None, auth=None): - """Sets up the api object""" + """API requesting object""" + + def __init__( + self, + api_endpoint, + client_id=None, + client_secret=None, + access_token=None, + version=None, + site=None, + lang=None, + auth=None, + ): + """Set up the API object""" self.client_id = client_id self.client_secret = client_secret self.set_token(access_token) @@ -234,27 +318,27 @@ def __init__(self, api_endpoint, client_id=None, client_secret=None, self.api_endpoint = api_endpoint self.auth = auth - """ pagination """ + #: Pagination properties self.total_count = None self.page_offset = None self.page_max = None - api_v = 'application/vnd.ticketbis.v{0}+json'.format(self.version) + api_v = "application/vnd.ticketbis.v{0}+json".format(self.version) self.base_headers = { - 'Accept': '{0}, application/json'.format(api_v), - 'Content-Type': 'application/json', + "Accept": "{0}, application/json".format(api_v), + "Content-Type": "application/json", } def set_token(self, access_token): """Set the OAuth token for this requester""" self.oauth_token = access_token - self.userless = not bool(access_token) # Userless if no access_token + self.userless = not bool(access_token) # Userless if no access_token def GET(self, path, params={}, **kwargs): """GET request that returns processed data""" params = params.copy() # Short-circuit multi requests - if kwargs.get('multi') is True: + if kwargs.get("multi") is True: return self.add_multi_request(path, params) # Continue processing normal requests headers = self._create_headers() @@ -264,7 +348,7 @@ def GET(self, path, params={}, **kwargs): result = _get(url, headers=headers, params=params, auth=self.auth) self._set_header_properties(result) - return result['data'] + return result["data"] def GET_PAGINATED(self, path, params={}, **kwargs): """GET request that returns data iterating over pagination""" @@ -278,25 +362,23 @@ def GET_PAGINATED(self, path, params={}, **kwargs): while pending_pages: result = _get(url, headers=headers, params=params, auth=self.auth) self._set_header_properties(result) - pending_pages = \ - self.page_offset + len(result['data']) < self.total_count - params['offset'] = self.page_offset + self.page_max - for r in result['data']: + pending_pages = ( + self.page_offset + len(result["data"]) < self.total_count + ) + params["offset"] = self.page_offset + self.page_max + for r in result["data"]: yield r def _set_header_properties(self, result): - self.site = result['headers']['X-ticketbis-site'] - - self.rate_limit = result['headers'].get('X-RateLimit-Limit', None) - self.rate_remaining = result['headers'].get('X-RateLimit-Remaining', None) - - if 'X-ticketbis-totalCount' in result['headers']: - self.total_count = \ - int(result['headers']['X-ticketbis-totalCount']) - self.page_offset = \ - int(result['headers']['X-ticketbis-pageOffset']) - self.page_max = \ - int(result['headers']['X-ticketbis-pageMaxSize']) + self.site = result["headers"]["X-ticketbis-site"] + + self.rate_limit = result["headers"].get("X-RateLimit-Limit", None) + self.rate_remaining = result["headers"].get("X-RateLimit-Remaining", None) + + if "X-ticketbis-totalCount" in result["headers"]: + self.total_count = int(result["headers"]["X-ticketbis-totalCount"]) + self.page_offset = int(result["headers"]["X-ticketbis-pageOffset"]) + self.page_max = int(result["headers"]["X-ticketbis-pageMaxSize"]) else: self.total_count = None self.page_offset = None @@ -306,7 +388,7 @@ def add_multi_request(self, path, params={}): """Add multi request to list and return number of requests added""" url = path if params: - url += '?{0}'.format(parse.quote_plus(parse.urlencode(params))) + url += "?{0}".format(parse.quote_plus(parse.urlencode(params))) self.multi_requests.append(url) return len(self.multi_requests) @@ -319,10 +401,12 @@ def POST(self, path, data={}, files=None): headers = self._create_headers() data = self._enrich_params(data) url = self._get_url(path) - result = _post(url, headers=headers, data=json.dumps(data), files=files, auth=self.auth) - self.rate_limit = result['headers'].get('X-RateLimit-Limit', None) - self.rate_remaining = result['headers'].get('X-RateLimit-Remaining', None) - return result['data'] + result = _post( + url, headers=headers, data=json.dumps(data), files=files, auth=self.auth + ) + self.rate_limit = result["headers"].get("X-RateLimit-Limit", None) + self.rate_remaining = result["headers"].get("X-RateLimit-Remaining", None) + return result["data"] def PUT(self, path, data={}, files=None): """PUT request that returns processed data""" @@ -333,22 +417,23 @@ def PUT(self, path, data={}, files=None): headers = self._create_headers() data = self._enrich_params(data) url = self._get_url(path) - result = _put(url, headers=headers, data=json.dumps(data), files=files, auth=self.auth) - self.rate_limit = result['headers'].get('X-RateLimit-Limit', None) - self.rate_remaining = result['headers'].get('X-RateLimit-Remaining', None) - return result['data'] + result = _put( + url, headers=headers, data=json.dumps(data), files=files, auth=self.auth + ) + self.rate_limit = result["headers"].get("X-RateLimit-Limit", None) + self.rate_remaining = result["headers"].get("X-RateLimit-Remaining", None) + return result["data"] def _get_url(self, path): - return '{API_ENDPOINT}{path}'.format( - API_ENDPOINT=self.api_endpoint, - path=path + return "{API_ENDPOINT}{path}".format( + API_ENDPOINT=self.api_endpoint, path=path ) def _enrich_params(self, params): """Enrich the params dict""" if self.userless: - params['client_id'] = self.client_id - params['client_secret'] = self.client_secret + params["client_id"] = self.client_id + params["client_secret"] = self.client_secret return params def _create_headers(self): @@ -356,18 +441,18 @@ def _create_headers(self): headers = self.base_headers.copy() if not self.userless: - headers['Authorization'] = 'Bearer {0}'.format(self.oauth_token) + headers["Authorization"] = "Bearer {0}".format(self.oauth_token) if self.site: - headers['X-ticketbis-site'] = self.site + headers["X-ticketbis-site"] = self.site elif self.lang: - headers['Accept-Language'] = self.lang + headers["Accept-Language"] = self.lang return headers - class _Endpoint(object): """Generic endpoint class""" + def __init__(self, requester): - """Stores the request function for retrieving data""" + """Store the request function for retrieving data""" self.requester = requester def copy(self): @@ -376,114 +461,128 @@ def copy(self): def _expanded_path(self, path=None): """Gets the expanded path, given this endpoint""" - return '{expanded_path}'.format( - expanded_path='/'.join(p for p in (self.endpoint, path) if p) + return "{expanded_path}".format( + expanded_path="/".join(p for p in (self.endpoint, path) if p) ) def create(self, params={}): - return self.POST('', params) + return self.POST("", params) def update(self, params={}): - return self.PUT('{0}'.format(params['id']), params) + return self.PUT("{0}".format(params["id"]), params) def GET(self, path=None, auto_pagination=False, *args, **kwargs): """Use the requester to get the data""" if not auto_pagination: - return self.requester.GET(self._expanded_path(path), - *args, **kwargs) + return self.requester.GET(self._expanded_path(path), *args, **kwargs) else: - return self.requester.GET_PAGINATED(self._expanded_path(path), - *args, **kwargs) + return self.requester.GET_PAGINATED( + self._expanded_path(path), *args, **kwargs + ) def POST(self, path=None, *args, **kwargs): """Use the requester to post the data""" - return self.requester.POST(self._expanded_path(path), - *args, **kwargs) + return self.requester.POST(self._expanded_path(path), *args, **kwargs) def PUT(self, path=None, *args, **kwargs): """Use the requester to put the data""" - return self.requester.PUT(self._expanded_path(path), - *args, **kwargs) + return self.requester.PUT(self._expanded_path(path), *args, **kwargs) class Events(_Endpoint): - endpoint = 'events' + endpoint = "events" - def __call__(self, event_id=u'', auto_pagination=False, - params={}, multi=False): - return self.GET('{0}'.format(event_id), auto_pagination, - params=params, multi=multi) + def __call__(self, event_id=u"", auto_pagination=False, params={}, multi=False): + return self.GET( + "{0}".format(event_id), auto_pagination, params=params, multi=multi + ) - def section_groups(self, event_id, auto_pagination=False, - params={}, multi=False): - return self.GET('{0}/section_groups'.format(event_id), auto_pagination, - params=params, multi=multi) + def section_groups( + self, event_id, auto_pagination=False, params={}, multi=False + ): + return self.GET( + "{0}/section_groups".format(event_id), + auto_pagination, + params=params, + multi=multi, + ) class Categories(_Endpoint): - endpoint = 'categories' + endpoint = "categories" - def __call__(self, category_id=u'', auto_pagination=False, - params={}, multi=False): - return self.GET('{0}'.format(category_id), auto_pagination, - params=params, multi=multi) + def __call__( + self, category_id=u"", auto_pagination=False, params={}, multi=False + ): + return self.GET( + "{0}".format(category_id), auto_pagination, params=params, multi=multi + ) - def events(self, category_id, auto_pagination=False, - params={}, multi=False): - return self.GET('{0}/events'.format(category_id), auto_pagination, - params=params, multi=multi) + def events(self, category_id, auto_pagination=False, params={}, multi=False): + return self.GET( + "{0}/events".format(category_id), + auto_pagination, + params=params, + multi=multi, + ) class Sites(_Endpoint): - endpoint = 'sites' - - def __call__(self, site_id=u'', auto_pagination=False, - params={}, multi=False): - return self.GET('{0}'.format(site_id), auto_pagination, - params=params, multi=multi) + endpoint = "sites" + def __call__(self, site_id=u"", auto_pagination=False, params={}, multi=False): + return self.GET( + "{0}".format(site_id), auto_pagination, params=params, multi=multi + ) class Cities(_Endpoint): - endpoint = 'cities' + endpoint = "cities" - def __call__(self, city_id=u'', auto_pagination=False, - params={}, multi=False): - return self.GET('{0}'.format(city_id), auto_pagination, - params=params, multi=multi) + def __call__(self, city_id=u"", auto_pagination=False, params={}, multi=False): + return self.GET( + "{0}".format(city_id), auto_pagination, params=params, multi=multi + ) class Venues(_Endpoint): - endpoint = 'venues' + endpoint = "venues" - def __call__(self, venue_id=u'', auto_pagination=False, - params={}, multi=False): - return self.GET('{0}'.format(venue_id), auto_pagination, - params=params, multi=multi) + def __call__(self, venue_id=u"", auto_pagination=False, params={}, multi=False): + return self.GET( + "{0}".format(venue_id), auto_pagination, params=params, multi=multi + ) - def schemas(self, venue_id, auto_pagination=False, - params={}, multi=False): - return self.GET('{0}/schemas'.format(venue_id), auto_pagination, - params=params, multi=multi) + def schemas(self, venue_id, auto_pagination=False, params={}, multi=False): + return self.GET( + "{0}/schemas".format(venue_id), + auto_pagination, + params=params, + multi=multi, + ) class Schemas(_Endpoint): - endpoint = 'schemas' + endpoint = "schemas" - def __call__(self, schema_id=u'', auto_pagination=False, - params={}, multi=False): - return self.GET('{0}'.format(schema_id), auto_pagination, - params=params, multi=multi) + def __call__( + self, schema_id=u"", auto_pagination=False, params={}, multi=False + ): + return self.GET( + "{0}".format(schema_id), auto_pagination, params=params, multi=multi + ) class SectionGroups(_Endpoint): - endpoint = 'section_groups' - - def __call__(self, schema_id=u'', auto_pagination=False, - params={}, multi=False): - return self.GET('{0}'.format(schema_id), auto_pagination, - params=params, multi=multi) + endpoint = "section_groups" + def __call__( + self, schema_id=u"", auto_pagination=False, params={}, multi=False + ): + return self.GET( + "{0}".format(schema_id), auto_pagination, params=params, multi=multi + ) class Multi(_Endpoint): """Multi request endpoint handler""" - endpoint = 'multi' + + endpoint = "multi" def __len__(self): - return len(self.requester.multi_requests) + return len(self.requester.multi_requests) def __call__(self): """ @@ -496,75 +595,94 @@ def __call__(self): while self.requester.multi_requests: # Pull n requests from the multi-request queue requests = self.requester.multi_requests[:MAX_MULTI_REQUESTS] - del(self.requester.multi_requests[:MAX_MULTI_REQUESTS]) + del self.requester.multi_requests[:MAX_MULTI_REQUESTS] # Process the 4sq multi request - params = { - 'requests': ','.join(requests), - } - responses = self.GET(params=params)['responses'] + params = {"requests": ",".join(requests)} + responses = self.GET(params=params)["responses"] # ... and yield out each individual response for response in responses: # Make sure the response was valid try: _raise_error_from_response(response) - yield response['response'] + yield response["response"] except TicketbisException as e: yield e @property def num_required_api_calls(self): """Returns the expected number of API calls to process""" - return int(math.ceil( - len(self.requester.multi_requests) / float(MAX_MULTI_REQUESTS))) + return int( + math.ceil( + len(self.requester.multi_requests) / float(MAX_MULTI_REQUESTS) + ) + ) + def _log_and_raise_exception(msg, data, cls=TicketbisException): - """Calls log.error() then raises an exception of class cls""" - data = u'{0}'.format(data) - # We put data as a argument for log.error() so error tracking systems such - # as Sentry will properly group errors together by msg only - log.error(u'{0}: %s'.format(msg), data) - raise cls(u'{0}: {1}'.format(msg, data)) - -""" -Network helper functions -""" + """Calls log.error() then raises an exception of class cls""" + data = u"{0}".format(data) + # We put data as a argument for log.error() so error tracking systems such + # as Sentry will properly group errors together by msg only + log.error(u"{0}: %s".format(msg), data) + raise cls(u"{0}: {1}".format(msg, data)) + + +#: Network helper functions + + def _get(url, headers={}, params=None, auth=None): - """Tries to GET data from an endpoint using retries""" + """Try to GET data from an endpoint using retries""" param_string = _ticketbis_urlencode(params) for i in xrange(NUM_REQUEST_RETRIES): try: try: - response = requests.get(url, headers=headers, - params=param_string, verify=VERIFY_SSL, auth=auth) + response = requests.get( + url, + headers=headers, + params=param_string, + verify=VERIFY_SSL, + auth=auth, + ) return _process_response(response) except requests.exceptions.RequestException as e: - _log_and_raise_exception('Error connecting with ticketbis API', - e) + _log_and_raise_exception("Error connecting with ticketbis API", e) except TicketbisException as e: # Some errors don't bear repeating - if e.__class__ in [InvalidAuth, ParamError, EndpointError, - NotAuthorized, Deprecated]: raise + if e.__class__ in [ + InvalidAuth, + ParamError, + EndpointError, + NotAuthorized, + Deprecated, + ]: + raise # If we've reached our last try, re-raise - if ((i + 1) == NUM_REQUEST_RETRIES): raise + if (i + 1) == NUM_REQUEST_RETRIES: + raise time.sleep(1) + def _post(url, headers={}, data=None, files=None, auth=None): - """Tries to POST data to an endpoint""" + """Try to POST data to an endpoint""" try: - response = requests.post(url, headers=headers, data=data, files=files, - verify=VERIFY_SSL, auth=auth) + response = requests.post( + url, headers=headers, data=data, files=files, verify=VERIFY_SSL, auth=auth + ) return _process_response(response) except requests.exceptions.RequestException as e: - _log_and_raise_exception('Error connecting with ticketbis API', e) + _log_and_raise_exception("Error connecting with ticketbis API", e) + def _put(url, headers={}, data=None, files=None, auth=None): - """Tries to PUT data to an endpoint""" + """Try to PUT data to an endpoint""" try: - response = requests.put(url, headers=headers, data=data, files=files, - verify=VERIFY_SSL, auth=auth) + response = requests.put( + url, headers=headers, data=data, files=files, verify=VERIFY_SSL, auth=auth + ) return _process_response(response) except requests.exceptions.RequestException as e: - _log_and_raise_exception('Error connecting with ticketbis API', e) + _log_and_raise_exception("Error connecting with ticketbis API", e) + def _process_response(response): """Make the request and handle exception processing""" @@ -572,69 +690,72 @@ def _process_response(response): try: if response.status_code in (200, 201): data = response.json() - return { 'headers': response.headers, 'data': data } + return {"headers": response.headers, "data": data} if response.status_code == 412: # Especial case - _log_and_raise_exception('Precondition failed', response.text, - cls=PreconditionFailed) + _log_and_raise_exception( + "Precondition failed", response.text, cls=PreconditionFailed + ) # Default case, Got proper response data = response.json() return _raise_error_from_response(data) except ValueError: - _log_and_raise_exception('Invalid response', response.text) + _log_and_raise_exception("Invalid response", response.text) def _raise_error_from_response(data): - """Processes the response data""" + """Process the response data""" # Check the meta-data for why this request failed - meta = data.get('meta') + meta = data.get("meta") if meta: # Account for ticketbis conflicts # see: https://developer.ticketbis.com/overview/responses - if meta.get('code') in (200, 409): return data - exc = error_types.get(meta.get('errorType')) + if meta.get("code") in (200, 409): + return data + exc = error_types.get(meta.get("errorType")) if exc: - raise exc(meta.get('errorDetail')) + raise exc(meta.get("errorDetail")) else: - _log_and_raise_exception('Unknown error. meta', meta) + _log_and_raise_exception("Unknown error. meta", meta) else: - _log_and_raise_exception('Invalid format, missing meta property. data', - data) + _log_and_raise_exception("Invalid format, missing meta property. data", data) + def _as_utf8(s): try: return str(s) except UnicodeEncodeError: - return unicode(s).encode('utf8') + return s.encode("utf8") + def _ticketbis_urlencode(query, doseq=0, safe_chars="&/,+"): # Courtesy of github.com/iambibhas - if hasattr(query,"items"): + if hasattr(query, "items"): query = query.items() else: try: if len(query) and not isinstance(query[0], tuple): raise TypeError except TypeError: - ty,va,tb = sys.exc_info() + ty, va, tb = sys.exc_info() raise TypeError("not valid non-string sequence").with_traceback(tb) - l = [] + args = [] if not doseq: # preserve old behavior for k, v in query: k = parse.quote(_as_utf8(k), safe=safe_chars) v = parse.quote(_as_utf8(v), safe=safe_chars) - l.append(k + '=' + v) + args.append(k + "=" + v) else: for k, v in query: k = parse.quote(_as_utf8(k), safe=safe_chars) if isinstance(v, six.string_types): v = parse.quote(_as_utf8(v), safe=safe_chars) - l.append(k + '=' + v) + args.append(k + "=" + v) else: try: # is this a sufficient test for sequence-ness? @@ -642,9 +763,9 @@ def _ticketbis_urlencode(query, doseq=0, safe_chars="&/,+"): except TypeError: # not a sequence v = parse.quote(_as_utf8(v), safe=safe_chars) - l.append(k + '=' + v) + args.append(k + "=" + v) else: # loop over the sequence for elt in v: - l.append(k + '=' + parse.quote(_as_utf8(elt))) - return '&'.join(l) + args.append(k + "=" + parse.quote(_as_utf8(elt))) + return "&".join(args) diff --git a/ticketbis/tests/__init__.py b/ticketbis/tests/__init__.py index da7e81c..9076efd 100644 --- a/ticketbis/tests/__init__.py +++ b/ticketbis/tests/__init__.py @@ -1,73 +1,103 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. import os import unittest import ticketbis -if 'CLIENT_ID' in os.environ and 'CLIENT_SECRET' in os.environ \ - and 'ACCESS_TOKEN' in os.environ and 'API_ENDPOINT' in os.environ: - CLIENT_ID = os.environ['CLIENT_ID'] - CLIENT_SECRET = os.environ['CLIENT_SECRET'] - ACCESS_TOKEN = os.environ['ACCESS_TOKEN'] - API_ENDPOINT = os.environ['API_ENDPOINT'] +if ( + "CLIENT_ID" in os.environ + and "CLIENT_SECRET" in os.environ + and "ACCESS_TOKEN" in os.environ + and "API_ENDPOINT" in os.environ +): + CLIENT_ID = os.environ["CLIENT_ID"] + CLIENT_SECRET = os.environ["CLIENT_SECRET"] + ACCESS_TOKEN = os.environ["ACCESS_TOKEN"] + API_ENDPOINT = os.environ["API_ENDPOINT"] else: try: - from ticketbis.tests._creds import * + from ticketbis.tests._creds import ( + CLIENT_ID, + CLIENT_SECRET, + ACCESS_TOKEN, + API_ENDPOINT, + ) except ImportError: - print("Please create a creds.py file in this package, based upon creds.example.py") + import logging + + log = logging.getLogger(__name__) + log.error( + "Please create a creds.py file in this package, based upon creds.example.py" + ) -TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), 'testdata') +TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "testdata") class BaseEndpointTestCase(unittest.TestCase): - default_site_name = 'ticketbisES' - default_category_id = u'2' - default_site_id = u'1' - default_venue_id = u'1' - default_schema_id = u'1' + default_site_name = "ticketbisES" + default_category_id = u"2" + default_site_id = u"1" + default_venue_id = u"1" + default_schema_id = u"1" + class BaseAuthenticationTestCase(BaseEndpointTestCase): def setUp(self): self.api = ticketbis.Ticketbis( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, - redirect_uri='http://ticketbis.com', + redirect_uri="http://ticketbis.com", site=self.default_site_name, - api_endpoint=API_ENDPOINT + api_endpoint=API_ENDPOINT, ) + class BaseAuthenticatedEndpointTestCase(BaseEndpointTestCase): def setUp(self): self.api = ticketbis.Ticketbis( -# client_id=CLIENT_ID, -# client_secret=CLIENT_SECRET, + # client_id=CLIENT_ID, + # client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, site=self.default_site_name, - api_endpoint=API_ENDPOINT + api_endpoint=API_ENDPOINT, ) + class BaseUserlessEndpointTestCase(BaseEndpointTestCase): def setUp(self): self.api = ticketbis.Ticketbis( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, site=self.default_site_name, - api_endpoint=API_ENDPOINT + api_endpoint=API_ENDPOINT, ) + class MultilangEndpointTestCase(BaseEndpointTestCase): def setUp(self): self.apis = [] - for lang in ('es', 'fr', 'de', 'it', 'ja', 'th', 'ko', 'ru', 'pt', 'id'): + for lang in ("es", "fr", "de", "it", "ja", "th", "ko", "ru", "pt", "id"): self.apis.append( ticketbis.Ticketbis( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, lang=lang, - api_endpoint=API_ENDPOINT + api_endpoint=API_ENDPOINT, ) ) diff --git a/ticketbis/tests/_creds.example.py b/ticketbis/tests/_creds.example.py index dacb133..d30f144 100644 --- a/ticketbis/tests/_creds.example.py +++ b/ticketbis/tests/_creds.example.py @@ -1,8 +1,20 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -API_ENDPOINT = u'https://api.ticketbis.com' -CLIENT_ID = u'YOUR_CLIENT_ID' -CLIENT_SECRET = u'YOUR_CLIENT_SECRET' -ACCESS_TOKEN = u'EXAMPLE_USER_ACCESS_TOKEN' +API_ENDPOINT = u"https://api.ticketbis.com" +CLIENT_ID = u"YOUR_CLIENT_ID" +CLIENT_SECRET = u"YOUR_CLIENT_SECRET" +ACCESS_TOKEN = u"EXAMPLE_USER_ACCESS_TOKEN" diff --git a/ticketbis/tests/test_categories.py b/ticketbis/tests/test_categories.py index 4d01f3e..c49ef3c 100644 --- a/ticketbis/tests/test_categories.py +++ b/ticketbis/tests/test_categories.py @@ -1,22 +1,33 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis -import logging; log = logging.getLogger(__name__) +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -import os +from . import BaseAuthenticatedEndpointTestCase -from . import TEST_DATA_DIR, BaseAuthenticatedEndpointTestCase class CategoriesEndpointTestCase(BaseAuthenticatedEndpointTestCase): - """ - General - """ + """Test endpoint for retrieving categories.""" + def test_category(self): + """Return a single category.""" response = self.api.categories(self.default_category_id) - assert 'name' in response + assert "name" in response def test_categories(self): - response = self.api.categories(params={'max': 2, 'offset': 0}) - assert 'name' in response[0] + """Return multiple categories using pagination.""" + response = self.api.categories(params={"max": 2, "offset": 0}) + assert "name" in response[0] assert self.api.page_max == 2 assert self.api.page_offset == 0 diff --git a/ticketbis/tests/test_events.py b/ticketbis/tests/test_events.py index 19ccc56..e495d96 100644 --- a/ticketbis/tests/test_events.py +++ b/ticketbis/tests/test_events.py @@ -1,33 +1,40 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis -import logging; log = logging.getLogger(__name__) +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License -import os +from . import BaseAuthenticatedEndpointTestCase -from . import TEST_DATA_DIR, BaseAuthenticatedEndpointTestCase class EventsEndpointTestCase(BaseAuthenticatedEndpointTestCase): - """ - General - """ - def test_events(self): - response = self.api.events(params={'max': 2, 'offset': 0}) - assert 'id' in response[0] + response = self.api.events(params={"max": 2, "offset": 0}) + assert "id" in response[0] assert self.api.page_max == 2 assert self.api.page_offset == 0 - response = self.api.events(response[0]['id']) - assert 'name' in response + response = self.api.events(response[0]["id"]) + assert "name" in response def test_events_by_category(self): - response = self.api.categories.events(self.default_category_id, - params={'max': 2, 'offset': 0}) - assert 'name' in response[0] + response = self.api.categories.events( + self.default_category_id, params={"max": 2, "offset": 0} + ) + assert "name" in response[0] def test_event_pagination(self): - response = self.api.events(auto_pagination=True, params={'max': 1}) + response = self.api.events(auto_pagination=True, params={"max": 1}) r = next(response) r = next(response) - assert 'name' in r + assert "name" in r diff --git a/ticketbis/tests/test_oauth.py b/ticketbis/tests/test_oauth.py index 1eb1684..ca3a3c6 100644 --- a/ticketbis/tests/test_oauth.py +++ b/ticketbis/tests/test_oauth.py @@ -1,11 +1,22 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis -import logging; log = logging.getLogger(__name__) +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -from . import BaseAuthenticationTestCase import six -import ticketbis + +from . import BaseAuthenticationTestCase class OAuthEndpointTestCase(BaseAuthenticationTestCase): diff --git a/ticketbis/tests/test_schemas.py b/ticketbis/tests/test_schemas.py index 5dff566..610ae10 100644 --- a/ticketbis/tests/test_schemas.py +++ b/ticketbis/tests/test_schemas.py @@ -1,26 +1,33 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis -import logging; log = logging.getLogger(__name__) +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -import os +from . import BaseAuthenticatedEndpointTestCase -from . import TEST_DATA_DIR, BaseAuthenticatedEndpointTestCase class SchemasEndpointTestCase(BaseAuthenticatedEndpointTestCase): - """ - General - """ def test_schema(self): response = self.api.schemas(self.default_schema_id) - assert 'name' in response + assert "name" in response def test_schemas(self): - response = self.api.schemas(params={'max': 2, 'offset': 0}) - assert 'name' in response[0] + response = self.api.schemas(params={"max": 2, "offset": 0}) + assert "name" in response[0] assert self.api.page_max == 2 assert self.api.page_offset == 0 def test_schemas_by_venue(self): response = self.api.venues.schemas(self.default_venue_id) - assert 'name' in response[0] + assert "name" in response[0] diff --git a/ticketbis/tests/test_section_groups.py b/ticketbis/tests/test_section_groups.py index c13b599..8dae797 100644 --- a/ticketbis/tests/test_section_groups.py +++ b/ticketbis/tests/test_section_groups.py @@ -1,19 +1,25 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis -import logging; log = logging.getLogger(__name__) +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -import os +from . import BaseAuthenticatedEndpointTestCase -from . import TEST_DATA_DIR, BaseAuthenticatedEndpointTestCase class SectionGroupsEndpointTestCase(BaseAuthenticatedEndpointTestCase): - """ - General - """ - def test_section_groups_by_event(self): - response = self.api.events(params={'max': 1, 'offset': 0}) - assert 'id' in response[0] - response = self.api.events.section_groups(response[0]['id']) - assert 'name' in response[0] + response = self.api.events(params={"max": 1, "offset": 0}) + assert "id" in response[0] + response = self.api.events.section_groups(response[0]["id"]) + assert "name" in response[0] diff --git a/ticketbis/tests/test_sites.py b/ticketbis/tests/test_sites.py index 934a48d..986be44 100644 --- a/ticketbis/tests/test_sites.py +++ b/ticketbis/tests/test_sites.py @@ -1,22 +1,33 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis -import logging; log = logging.getLogger(__name__) +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -import os +from . import BaseAuthenticatedEndpointTestCase -from . import TEST_DATA_DIR, BaseAuthenticatedEndpointTestCase class SitesEndpointTestCase(BaseAuthenticatedEndpointTestCase): - """ - General - """ + """Test endpoint for retrieving sites.""" + def test_site(self): + """Return a single site.""" response = self.api.sites(self.default_site_id) - assert 'name' in response + assert "name" in response def test_sites(self): - response = self.api.sites(params={'max': 2, 'offset': 0}) - assert 'name' in response[0] + """Return multiple sites using pagination.""" + response = self.api.sites(params={"max": 2, "offset": 0}) + assert "name" in response[0] assert self.api.page_max == 2 assert self.api.page_offset == 0 diff --git a/ticketbis/tests/test_venues.py b/ticketbis/tests/test_venues.py index b051e97..511a1bb 100644 --- a/ticketbis/tests/test_venues.py +++ b/ticketbis/tests/test_venues.py @@ -1,27 +1,39 @@ -#!/usr/bin/env python -# -*- coding: UTF-8 -*- -# (c) 2015 Ticketbis -import logging; log = logging.getLogger(__name__) +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. -import os -from . import TEST_DATA_DIR, BaseAuthenticatedEndpointTestCase +from . import BaseAuthenticatedEndpointTestCase + class VenuesEndpointTestCase(BaseAuthenticatedEndpointTestCase): - """ - General - """ + """Test endpoint for managing venues.""" + def test_venue(self): + """Return a single venue.""" response = self.api.venues(self.default_venue_id) - assert 'name' in response + assert "name" in response def test_venues(self): - response = self.api.venues(params={'max': 2, 'offset': 0}) - assert 'name' in response[0] + """Return multiple venues using pagination.""" + response = self.api.venues(params={"max": 2, "offset": 0}) + assert "name" in response[0] assert self.api.page_max == 2 assert self.api.page_offset == 0 - - #def test_venues_update(self): + + # def test_venues_update(self): # response = self.api.venues.update({ # 'id': '1', # 'name': 'San mames API TEST 222222', diff --git a/ticketbis/version.py b/ticketbis/version.py new file mode 100644 index 0000000..2886d14 --- /dev/null +++ b/ticketbis/version.py @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2015-2019 Ticketbis +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Library versioning matches supported ticketbis API version.""" + +__version__ = "0.3.5.1.dev0" From c03aca88dca3a2e133e9ad7c29469f2e1892f4f8 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Wed, 4 Sep 2019 14:11:17 +0200 Subject: [PATCH 2/4] test(api): record responses to run tests offline Previously tests needed to contact a running (production) service but now one can run tests locally without the Internet connection. --- .gitignore | 1 + .travis.yml | 13 +- MANIFEST.in | 9 +- README.md | 26 +-- pytest.ini | 3 + setup.py | 9 +- {ticketbis/tests => tests}/.gitignore | 0 {ticketbis/tests => tests}/__init__.py | 39 +++- {ticketbis/tests => tests}/_creds.example.py | 0 ...oriesEndpointTestCase.test_categories.json | 100 +++++++++ ...egoriesEndpointTestCase.test_category.json | 91 ++++++++ ...ndpointTestCase.test_event_pagination.json | 195 ++++++++++++++++++ .../EventsEndpointTestCase.test_events.json | 186 +++++++++++++++++ ...pointTestCase.test_events_by_category.json | 100 +++++++++ .../OAuthEndpointTestCase.test_auth_url.json | 4 + .../OAuthEndpointTestCase.test_get_token.json | 4 + .../SchemasEndpointTestCase.test_schema.json | 91 ++++++++ .../SchemasEndpointTestCase.test_schemas.json | 100 +++++++++ ...ndpointTestCase.test_schemas_by_venue.json | 100 +++++++++ ...TestCase.test_section_groups_by_event.json | 195 ++++++++++++++++++ .../SitesEndpointTestCase.test_site.json | 91 ++++++++ .../SitesEndpointTestCase.test_sites.json | 100 +++++++++ .../VenuesEndpointTestCase.test_venue.json | 91 ++++++++ .../VenuesEndpointTestCase.test_venues.json | 100 +++++++++ {ticketbis/tests => tests}/readme.md | 0 {ticketbis/tests => tests}/test_categories.py | 0 {ticketbis/tests => tests}/test_events.py | 0 {ticketbis/tests => tests}/test_oauth.py | 0 {ticketbis/tests => tests}/test_schemas.py | 0 .../tests => tests}/test_section_groups.py | 0 {ticketbis/tests => tests}/test_sites.py | 0 {ticketbis/tests => tests}/test_venues.py | 0 ticketbis/__init__.py | 54 +++-- 33 files changed, 1653 insertions(+), 49 deletions(-) create mode 100644 pytest.ini rename {ticketbis/tests => tests}/.gitignore (100%) rename {ticketbis/tests => tests}/__init__.py (69%) rename {ticketbis/tests => tests}/_creds.example.py (100%) create mode 100644 tests/cassettes/CategoriesEndpointTestCase.test_categories.json create mode 100644 tests/cassettes/CategoriesEndpointTestCase.test_category.json create mode 100644 tests/cassettes/EventsEndpointTestCase.test_event_pagination.json create mode 100644 tests/cassettes/EventsEndpointTestCase.test_events.json create mode 100644 tests/cassettes/EventsEndpointTestCase.test_events_by_category.json create mode 100644 tests/cassettes/OAuthEndpointTestCase.test_auth_url.json create mode 100644 tests/cassettes/OAuthEndpointTestCase.test_get_token.json create mode 100644 tests/cassettes/SchemasEndpointTestCase.test_schema.json create mode 100644 tests/cassettes/SchemasEndpointTestCase.test_schemas.json create mode 100644 tests/cassettes/SchemasEndpointTestCase.test_schemas_by_venue.json create mode 100644 tests/cassettes/SectionGroupsEndpointTestCase.test_section_groups_by_event.json create mode 100644 tests/cassettes/SitesEndpointTestCase.test_site.json create mode 100644 tests/cassettes/SitesEndpointTestCase.test_sites.json create mode 100644 tests/cassettes/VenuesEndpointTestCase.test_venue.json create mode 100644 tests/cassettes/VenuesEndpointTestCase.test_venues.json rename {ticketbis/tests => tests}/readme.md (100%) rename {ticketbis/tests => tests}/test_categories.py (100%) rename {ticketbis/tests => tests}/test_events.py (100%) rename {ticketbis/tests => tests}/test_oauth.py (100%) rename {ticketbis/tests => tests}/test_schemas.py (100%) rename {ticketbis/tests => tests}/test_section_groups.py (100%) rename {ticketbis/tests => tests}/test_sites.py (100%) rename {ticketbis/tests => tests}/test_venues.py (100%) diff --git a/.gitignore b/.gitignore index c888179..0cc7ad0 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ # Do not wants *.py[c|o] *.egg-info +.eggs *.swp .coverage .Python diff --git a/.travis.yml b/.travis.yml index e7208e2..433e44f 100644 --- a/.travis.yml +++ b/.travis.yml @@ -31,19 +31,14 @@ python: - "3.6" - "2.7" -# env: -# global: -# - secure: ZyrUCICwX+Nzyl+iXjQklwlNdLfVuBb3UZRyARIiLfh70xLY2p7CT5+Ngc7l985ETwmXQmvUIIDRvYZnN7XIZhRsX9EMkYBlRIsNoUOaVsdWDTNlj6gBE47BVUvJduUrRgjvoVjeewG+NRv//KtJ1OwPu0tGDRlJdOMd7JGvyOs= -# - secure: vu1/nBWXAHk5emJkLSkNBJU4nt5IX9v2UAnd6ACZLRKANj1gH4WlX5w60MJ4UJF3HOBABftoBXyWrhs5iaQ0Ub8i71DncyBAEk+Esgck5IuWNhKuKTK+Y5p8f69cnHacC9AFKPJNInKrppoLYE+qaTgdmHAyXdiI/BeiBBxQuB8= -# - secure: ccozIsQQXnRkghE18z6YCeEExY5sGqwWjCkLJALL58+lwlOC+4t5FE4rV5OL16tyUV7mJ4w6j4waINvE3dVRjUIYQWbr3QQGIgy1f4sa/0QDGmhp2W2fkls2AAUPojE3QfbcxfjiYXDmnEaO5KyyDjNZ6earWIIyqIw08PICJBQ= - install: - - travis_retry pip install -U coverage coveralls pip pre-commit setuptools twine wheel - - travis_retry pip install -e . + - travis_retry pip install -U check-manifest coverage coveralls pip pre-commit setuptools twine wheel + - travis_retry pip install -e .[all] script: + - check-manifest --ignore=tests - pre-commit run -a - - nosetests --with-coverage --cover-package=ticketbis + - python setup.py test after_success: - coveralls diff --git a/MANIFEST.in b/MANIFEST.in index 44e86bd..e0679c7 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,8 @@ -include LICENSE MANIFEST.in -include *.txt +include .coveragerc +include .flake8 include *.md +include *.yaml +include LICENSE +include pytest.ini + +recursive-exclude tests * diff --git a/README.md b/README.md index 41f9ab0..3ee51b0 100644 --- a/README.md +++ b/README.md @@ -37,8 +37,8 @@ Depending upon your system and virtualenv settings, these may require sudo permi ```python # Construct the client object client = ticketbis.Ticketbis( - client_id='YOUR_CLIENT_ID', - client_secret='YOUR_CLIENT_SECRET', + client_id='YOUR_CLIENT_ID', + client_secret='YOUR_CLIENT_SECRET', redirect_uri='http://yoururl.example.com') # Build the authorization url for your app @@ -63,8 +63,8 @@ sites = client.sites() ```python # Construct the client object client = ticketbis.Ticketbis( - client_id='YOUR_CLIENT_ID', - client_secret='YOUR_CLIENT_SECRET', + client_id='YOUR_CLIENT_ID', + client_secret='YOUR_CLIENT_SECRET', grant_type=ticketbis.CLIENT_CRED_GRANT_TYPE) # Interrogate ticketbis' servers to get the client's access_token (no code required) @@ -76,13 +76,13 @@ client.set_access_token(access_token) # Get sites sites = client.sites() ``` - + ### Instantiating a client #### Userless Access ```python client = ticketbis.Ticketbis( - client_id='YOUR_CLIENT_ID', + client_id='YOUR_CLIENT_ID', client_secret='YOUR_CLIENT_SECRET') ``` @@ -96,8 +96,8 @@ client = ticketbis.Ticketbis(access_token='USER_ACCESS_TOKEN') ```python client = ticketbis.Ticketbis( - client_id='YOUR_CLIENT_ID', - client_secret='YOUR_CLIENT_SECRET', + client_id='YOUR_CLIENT_ID', + client_secret='YOUR_CLIENT_SECRET', version=2) ``` @@ -112,16 +112,16 @@ Since Ticketbis is a multi-site platform, a `site` or `lang` is required. If you ```python client = ticketbis.Ticketbis( - client_id='YOUR_CLIENT_ID', - client_secret='YOUR_CLIENT_SECRET', + client_id='YOUR_CLIENT_ID', + client_secret='YOUR_CLIENT_SECRET', site='ticketbisES') ``` Ticketbis can auto-discover the site based on the `lang` parameter (i.e. user's locale): ```python client = ticketbis.Ticketbis( - client_id='YOUR_CLIENT_ID', - client_secret='YOUR_CLIENT_SECRET', + client_id='YOUR_CLIENT_ID', + client_secret='YOUR_CLIENT_SECRET', lang='en-gb') ``` @@ -172,7 +172,7 @@ events = client.categories.events(2, auto_pagination=True) In order to run the tests: * Copy `ticketbis/tests/_creds.example.py` to `ticketbis/tests/_creds.py` * Fill in your personal credentials to run the tests (`_creds.py` is in .gitignore) -* Run `nosetests` +* Run `python setup.py test` ## License MIT License. See LICENSE diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..e0fe6e2 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,3 @@ +[pytest] +addopts = -vvv --cov=ticketbis --cov-config .coveragerc --cov-report=term-missing +doctest_optionflags = ALLOW_UNICODE ALLOW_BYTES DONT_ACCEPT_TRUE_FOR_1 ELLIPSIS IGNORE_EXCEPTION_DETAIL diff --git a/setup.py b/setup.py index 7de5e7c..a765118 100755 --- a/setup.py +++ b/setup.py @@ -25,6 +25,10 @@ exec(fp.read(), g) version = g["__version__"] +tests_require = ["pytest", "pytest-cov", "betamax", "betamax-serializers"] +extras_require = {"all": tests_require} +setup_requires = ["pytest-runner>=2.6.2"] + setup( name="ticketbis", version=version, @@ -44,8 +48,11 @@ "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "License :: OSI Approved :: Apache Software License", ], - packages=find_packages(), + packages=find_packages(exclude=["tests"]), install_requires=["requests>=2.1", "six"], + tests_require=tests_require, + extras_require=extras_require, + setup_requires=setup_requires, license="MIT License", keywords="ticketbis api", include_package_data=True, diff --git a/ticketbis/tests/.gitignore b/tests/.gitignore similarity index 100% rename from ticketbis/tests/.gitignore rename to tests/.gitignore diff --git a/ticketbis/tests/__init__.py b/tests/__init__.py similarity index 69% rename from ticketbis/tests/__init__.py rename to tests/__init__.py index 9076efd..908bc7b 100644 --- a/ticketbis/tests/__init__.py +++ b/tests/__init__.py @@ -15,7 +15,10 @@ # limitations under the License. import os -import unittest + +import betamax +from betamax.fixtures import unittest +from betamax_serializers import pretty_json import ticketbis @@ -38,59 +41,74 @@ API_ENDPOINT, ) except ImportError: - import logging - - log = logging.getLogger(__name__) - log.error( - "Please create a creds.py file in this package, based upon creds.example.py" - ) + API_ENDPOINT = "https://buscaticket.com.qa2.sh-env.net/api/" + CLIENT_ID = "api" + CLIENT_SECRET = "deadbeef" + ACCESS_TOKEN = "deadbeef==" TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "testdata") +betamax.Betamax.register_serializer(pretty_json.PrettyJSONSerializer) + +with betamax.Betamax.configure() as config: + config.cassette_library_dir = os.path.join(os.path.dirname(__file__), "cassettes") + config.default_cassette_options["serialize_with"] = "prettyjson" -class BaseEndpointTestCase(unittest.TestCase): + config.define_cassette_placeholder("", ACCESS_TOKEN) + + +class BaseEndpointTestCase(unittest.BetamaxTestCase): default_site_name = "ticketbisES" default_category_id = u"2" default_site_id = u"1" default_venue_id = u"1" default_schema_id = u"1" + def setUp(self): + super(BaseEndpointTestCase, self).setUp() + self.session.headers.pop("Accept-Encoding", None) + class BaseAuthenticationTestCase(BaseEndpointTestCase): def setUp(self): + super(BaseAuthenticationTestCase, self).setUp() self.api = ticketbis.Ticketbis( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri="http://ticketbis.com", site=self.default_site_name, api_endpoint=API_ENDPOINT, + session=self.session, ) class BaseAuthenticatedEndpointTestCase(BaseEndpointTestCase): def setUp(self): + super(BaseAuthenticatedEndpointTestCase, self).setUp() self.api = ticketbis.Ticketbis( - # client_id=CLIENT_ID, - # client_secret=CLIENT_SECRET, access_token=ACCESS_TOKEN, site=self.default_site_name, api_endpoint=API_ENDPOINT, + session=self.session, ) class BaseUserlessEndpointTestCase(BaseEndpointTestCase): def setUp(self): + super(BaseUserlessEndpointTestCase, self).setUp() self.api = ticketbis.Ticketbis( client_id=CLIENT_ID, client_secret=CLIENT_SECRET, site=self.default_site_name, api_endpoint=API_ENDPOINT, + session=self.session, ) class MultilangEndpointTestCase(BaseEndpointTestCase): def setUp(self): + super(MultilangEndpointTestCase, self).setUp() self.apis = [] for lang in ("es", "fr", "de", "it", "ja", "th", "ko", "ru", "pt", "id"): self.apis.append( @@ -99,5 +117,6 @@ def setUp(self): client_secret=CLIENT_SECRET, lang=lang, api_endpoint=API_ENDPOINT, + session=self.session, ) ) diff --git a/ticketbis/tests/_creds.example.py b/tests/_creds.example.py similarity index 100% rename from ticketbis/tests/_creds.example.py rename to tests/_creds.example.py diff --git a/tests/cassettes/CategoriesEndpointTestCase.test_categories.json b/tests/cassettes/CategoriesEndpointTestCase.test_categories.json new file mode 100644 index 0000000..46ebb78 --- /dev/null +++ b/tests/cassettes/CategoriesEndpointTestCase.test_categories.json @@ -0,0 +1,100 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:02", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/categories?max=2&offset=0" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":1,\"name\":\"Deportes\",\"depth\":1,\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-deportes/ca1\",\"events_count\":23976,\"entity_type\":\"CATEGORY\",\"title\":\"Entradas Deportes | StubHub Espa\u00f1a\",\"leaf\":false,\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/1.jpg\",\"ticketbis_only\":false,\"sh_image\":{\"resource_url\":\"https://ssli.ebayimg.com/images/g/~c8AAOSwujBZyoUS/\",\"guid\":\"~c8AAOSwujBZyoUS\",\"author\":\"Getty\",\"cdn_url\":\"https://ssli.ebayimg.com/images/g\"}},{\"id\":2,\"name\":\"M\u00fasica\",\"depth\":1,\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-musica/ca2\",\"events_count\":39394,\"entity_type\":\"CATEGORY\",\"title\":\"Entradas M\u00fasica | StubHub Espa\u00f1a\",\"leaf\":false,\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/2.jpg\",\"ticketbis_only\":false}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "786" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:02 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:02 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "8d7d04dc-baae-4381-a1ff-fe67681f8d5d" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "78953e91-10cb-4aa9-aa1b-37aa83a5343d" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of Category resources" + ], + "X-ticketbis-pageMaxSize": [ + "2" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "76176" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/categories?max=2&offset=0" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/CategoriesEndpointTestCase.test_category.json b/tests/cassettes/CategoriesEndpointTestCase.test_category.json new file mode 100644 index 0000000..449381a --- /dev/null +++ b/tests/cassettes/CategoriesEndpointTestCase.test_category.json @@ -0,0 +1,91 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:03", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/categories/2" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "{\"id\":2,\"name\":\"M\u00fasica\",\"depth\":1,\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-musica/ca2\",\"events_count\":39394,\"entity_type\":\"CATEGORY\",\"title\":\"Entradas M\u00fasica | StubHub Espa\u00f1a\",\"leaf\":false,\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/2.jpg\",\"ticketbis_only\":false,\"description\":\"

Pocos placeres pueden compararse al de escuchar la mejor música en directo. Si eres de los que estás deseando que tu artista favorito saque gira para ir a disfrutar de sus últimos temas, estás en el sitio adecuado. Las entradas para los mejores eventos musicales del año están a tu disposición, con todos los conciertos y festivales nacionales e internacionales que puedas imaginar. Piensa en tu artista favorito sobre el escenario. Tal vez no has podido verlo porque sus entradas se han agotado, pero eso no es problema ya que en el portal de compra y venta de entradas StubHub aún tienes la posibilidad de reservar un sitio privilegiado para verlo en el sitio que elijas. Todas las entradas de música están a solo un clic de distancia. No lo pienses más: busca tu evento y encuentra entradas para los mejores conciertos y festivales aquí, en StubHub. <\\u002fp>\",\"description_unique\":true,\"meta_description\":\"Compra y venta de entradas para los mejores conciertos y festivales nacionales e internacionales con total garant\u00eda. No te lo pierdas con StubHub.\"}" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "1480" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:03 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:03 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "39c0cd50-3b91-4bf8-b2e0-cb9d724245f2" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "c0d31dfa-11a6-40bc-9afc-67ae10d0f81b" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "Details for the Category resource" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/categories/2" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/EventsEndpointTestCase.test_event_pagination.json b/tests/cassettes/EventsEndpointTestCase.test_event_pagination.json new file mode 100644 index 0000000..41fed72 --- /dev/null +++ b/tests/cassettes/EventsEndpointTestCase.test_event_pagination.json @@ -0,0 +1,195 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:06", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/events?max=1" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":877217,\"name\":\"Harry Potter and the Cursed Child London (Part 1 & 2)\",\"title\":\"Entradas Harry Potter and the Cursed Child London (Part 1 & 2) | 04/09/2019 | StubHub Espa\u00f1a\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1-and-2/ev877217\",\"affiliate_url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1-and-2/ev877217/fix\",\"market_type\":\"SECONDARY\",\"date\":\"2019-09-04T12:55:00Z\",\"localized_date\":\"04/09/2019-13:55\",\"updated_time\":\"2019-07-13T04:18:45Z\",\"timezone\":\"Europe/London\",\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/11246.jpg\",\"min_price\":{\"amount\":334.83,\"currency\":\"EUR\"},\"min_listing_price\":{\"amount\":334.83,\"currency\":\"EUR\"},\"external_platform\":null,\"details\":null,\"on_sale_date\":\"2018-12-06T16:00:00Z\",\"lastminute\":false,\"shipment_deadline\":\"2019-09-04T12:55:00Z\",\"pum_deadline\":\"2019-09-04T12:55:00Z\",\"lmsInstructions\":null,\"ticketbis_only\":false}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "996" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:06 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:06 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "d620b79c-1843-4dfe-bc15-ccb0e49e757b" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "a2e0204f-3b8a-4de6-a013-be669ecf1667" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of Event resources" + ], + "X-ticketbis-pageMaxSize": [ + "1" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "127210" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/events?max=1" + } + }, + { + "recorded_at": "2019-09-04T11:44:10", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/events?max=1&offset=1" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":877120,\"name\":\"Harry Potter and the Cursed Child London (Part 1)\",\"title\":\"Entradas Harry Potter and the Cursed Child London (Part 1) | 04/09/2019 | StubHub Espa\u00f1a\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1/ev877120\",\"affiliate_url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1/ev877120/fix\",\"market_type\":\"SECONDARY\",\"date\":\"2019-09-04T13:00:00Z\",\"localized_date\":\"04/09/2019-14:00\",\"updated_time\":\"2019-07-13T04:17:06Z\",\"timezone\":\"Europe/London\",\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/11246.jpg\",\"min_price\":null,\"min_listing_price\":null,\"external_platform\":null,\"details\":null,\"on_sale_date\":\"2018-12-06T15:30:00Z\",\"lastminute\":false,\"shipment_deadline\":\"2019-09-04T13:00:00Z\",\"pum_deadline\":\"2019-09-04T13:00:00Z\",\"lmsInstructions\":null,\"ticketbis_only\":false}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "916" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:10 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:10 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "87d1cdac-0a05-4237-9805-26ab1fb72ac2" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "230feaf5-f21d-4982-b77a-6a49039cdd9c" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of Event resources" + ], + "X-ticketbis-pageMaxSize": [ + "1" + ], + "X-ticketbis-pageOffset": [ + "1" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "127210" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/events?max=1&offset=1" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/EventsEndpointTestCase.test_events.json b/tests/cassettes/EventsEndpointTestCase.test_events.json new file mode 100644 index 0000000..21f7ffa --- /dev/null +++ b/tests/cassettes/EventsEndpointTestCase.test_events.json @@ -0,0 +1,186 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:21", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/events?max=2&offset=0" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":877217,\"name\":\"Harry Potter and the Cursed Child London (Part 1 & 2)\",\"title\":\"Entradas Harry Potter and the Cursed Child London (Part 1 & 2) | 04/09/2019 | StubHub Espa\u00f1a\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1-and-2/ev877217\",\"affiliate_url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1-and-2/ev877217/fix\",\"market_type\":\"SECONDARY\",\"date\":\"2019-09-04T12:55:00Z\",\"localized_date\":\"04/09/2019-13:55\",\"updated_time\":\"2019-07-13T04:18:45Z\",\"timezone\":\"Europe/London\",\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/11246.jpg\",\"min_price\":{\"amount\":334.83,\"currency\":\"EUR\"},\"min_listing_price\":{\"amount\":334.83,\"currency\":\"EUR\"},\"external_platform\":null,\"details\":null,\"on_sale_date\":\"2018-12-06T16:00:00Z\",\"lastminute\":false,\"shipment_deadline\":\"2019-09-04T12:55:00Z\",\"pum_deadline\":\"2019-09-04T12:55:00Z\",\"lmsInstructions\":null,\"ticketbis_only\":false},{\"id\":877120,\"name\":\"Harry Potter and the Cursed Child London (Part 1)\",\"title\":\"Entradas Harry Potter and the Cursed Child London (Part 1) | 04/09/2019 | StubHub Espa\u00f1a\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1/ev877120\",\"affiliate_url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1/ev877120/fix\",\"market_type\":\"SECONDARY\",\"date\":\"2019-09-04T13:00:00Z\",\"localized_date\":\"04/09/2019-14:00\",\"updated_time\":\"2019-07-13T04:17:06Z\",\"timezone\":\"Europe/London\",\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/11246.jpg\",\"min_price\":null,\"min_listing_price\":null,\"external_platform\":null,\"details\":null,\"on_sale_date\":\"2018-12-06T15:30:00Z\",\"lastminute\":false,\"shipment_deadline\":\"2019-09-04T13:00:00Z\",\"pum_deadline\":\"2019-09-04T13:00:00Z\",\"lmsInstructions\":null,\"ticketbis_only\":false}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "1911" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:21 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:21 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "410bdbb2-54d8-48c4-8946-d0e3fc0542bd" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "227c9e02-40b5-4b0b-88a0-71619cc9182d" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of Event resources" + ], + "X-ticketbis-pageMaxSize": [ + "2" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "127210" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/events?max=2&offset=0" + } + }, + { + "recorded_at": "2019-09-04T11:44:21", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/events/877217" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "{\"id\":877217,\"name\":\"Harry Potter and the Cursed Child London (Part 1 & 2)\",\"title\":\"Entradas Harry Potter and the Cursed Child London (Part 1 & 2) | 04/09/2019 | StubHub Espa\u00f1a\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1-and-2/ev877217\",\"affiliate_url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1-and-2/ev877217/fix\",\"market_type\":\"SECONDARY\",\"date\":\"2019-09-04T12:55:00Z\",\"localized_date\":\"04/09/2019-13:55\",\"updated_time\":\"2019-07-13T04:18:45Z\",\"timezone\":\"Europe/London\",\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/11246.jpg\",\"min_price\":{\"amount\":334.83,\"currency\":\"EUR\"},\"min_listing_price\":{\"amount\":334.83,\"currency\":\"EUR\"},\"external_platform\":null,\"details\":null,\"on_sale_date\":\"2018-12-06T16:00:00Z\",\"lastminute\":false,\"shipment_deadline\":\"2019-09-04T12:55:00Z\",\"pum_deadline\":\"2019-09-04T12:55:00Z\",\"lmsInstructions\":null,\"ticketbis_only\":false,\"description\":\"Harry Potter and the Cursed Child London<\\u002fstrong> es uno de los espect\u00e1culos por los que merece la pena ir a un teatro. No te pierdas Harry Potter and the Cursed Child London<\\u002fstrong><\\u002fstrong> en Palace Theatre London<\\u002fstrong> y compra tus entradas<\\u002fstrong> ahora. Las mejores entradas<\\u002fstrong> para Harry Potter and the Cursed Child London (Part 1 & 2)<\\u002fstrong> las puedes encontrar en StubHub<\\u002fstrong> y en las mejores condiciones posibles. \u00bfTe lo vas a perder?\",\"description_unique\":false,\"important_message\":null,\"venue\":{\"id\":15234,\"name\":\"Palace Theatre London\",\"city\":{\"id\":2812,\"latitude\":51.5073219,\"longitude\":-0.1276474,\"name\":\"Londres\",\"country\":\"Reino Unido\",\"countryCode\":\"GB\",\"slug\":\"entradas-londres\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-londres/ct2812\"},\"address\":\"Cambridge Circus, London, LND W1A4AF\",\"country\":\"Reino Unido\",\"country_code\":\"GB\",\"latitude\":51.5132810,\"longitude\":-0.1295500},\"schema\":{\"id\":29512,\"name\":\"Standard - Dynamic\",\"static_image\":null,\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false},\"dynamic_map\":null,\"meta_description\":\"\u00bfBuscas entradas para Harry Potter and the Cursed Child London (Part 1 & 2)? C\u00f3mpralas ahora en StubHub y asegura tu sitio en Palace Theatre London el 4 de septiembre de 2019.\",\"currency\":\"GBP\"}" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "2418" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:21 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:21 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "2e82775a-f8a3-4d7d-bee7-754eab71f01f" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "9e24298a-b755-4c75-a089-7dba04cec0e9" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "Details for the Event resource" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/events/877217" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/EventsEndpointTestCase.test_events_by_category.json b/tests/cassettes/EventsEndpointTestCase.test_events_by_category.json new file mode 100644 index 0000000..a062758 --- /dev/null +++ b/tests/cassettes/EventsEndpointTestCase.test_events_by_category.json @@ -0,0 +1,100 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:27", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/categories/2/events?max=2&offset=0" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":1029751,\"name\":\"Evanescence Plze\u0148\",\"title\":\"Entradas Evanescence Plze\u0148 | 04/09/2019 | StubHub Espa\u00f1a\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-evanescence-plzen/ev1029751\",\"affiliate_url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-evanescence-plzen/ev1029751/fix\",\"market_type\":\"SECONDARY\",\"date\":\"2019-09-04T16:00:00Z\",\"localized_date\":\"04/09/2019-18:00\",\"updated_time\":\"2019-07-13T18:17:57Z\",\"timezone\":\"Europe/Berlin\",\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/2454.jpg\",\"min_price\":{\"amount\":250.00,\"currency\":\"EUR\"},\"min_listing_price\":{\"amount\":250.00,\"currency\":\"EUR\"},\"external_platform\":null,\"details\":null,\"on_sale_date\":\"2019-05-06T13:30:00Z\",\"lastminute\":false,\"shipment_deadline\":\"2019-09-04T16:00:00Z\",\"pum_deadline\":\"2019-09-04T16:00:00Z\",\"lmsInstructions\":null,\"ticketbis_only\":false},{\"id\":906198,\"name\":\"ProgPower USA 2 Day Pass (September 4-5)\",\"title\":\"Entradas ProgPower USA 2 Day Pass (September 4-5) | 04/09/2019 | StubHub Espa\u00f1a\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-progpower-usa-2-day-pass-september-4-5/ev906198\",\"affiliate_url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-progpower-usa-2-day-pass-september-4-5/ev906198/fix\",\"market_type\":\"SECONDARY\",\"date\":\"2019-09-04T16:59:00Z\",\"localized_date\":\"04/09/2019-12:59\",\"updated_time\":\"2019-06-12T01:18:32Z\",\"timezone\":\"America/New_York\",\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/79.jpg\",\"min_price\":{\"amount\":79.17,\"currency\":\"EUR\"},\"min_listing_price\":{\"amount\":79.17,\"currency\":\"EUR\"},\"external_platform\":null,\"details\":null,\"on_sale_date\":\"2019-01-04T11:00:00Z\",\"lastminute\":false,\"shipment_deadline\":\"2019-09-04T16:59:00Z\",\"pum_deadline\":\"2019-09-04T16:59:00Z\",\"lmsInstructions\":null,\"ticketbis_only\":false}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "1795" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:27 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:27 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "16072311-bb90-4764-aeb2-e3d5b55352d4" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "3018e0bd-f579-4aed-8a89-358a460dff7a" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of Event resources" + ], + "X-ticketbis-pageMaxSize": [ + "2" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "37880" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/categories/2/events?max=2&offset=0" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/OAuthEndpointTestCase.test_auth_url.json b/tests/cassettes/OAuthEndpointTestCase.test_auth_url.json new file mode 100644 index 0000000..9a55c18 --- /dev/null +++ b/tests/cassettes/OAuthEndpointTestCase.test_auth_url.json @@ -0,0 +1,4 @@ +{ + "http_interactions": [], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/OAuthEndpointTestCase.test_get_token.json b/tests/cassettes/OAuthEndpointTestCase.test_get_token.json new file mode 100644 index 0000000..9a55c18 --- /dev/null +++ b/tests/cassettes/OAuthEndpointTestCase.test_get_token.json @@ -0,0 +1,4 @@ +{ + "http_interactions": [], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/SchemasEndpointTestCase.test_schema.json b/tests/cassettes/SchemasEndpointTestCase.test_schema.json new file mode 100644 index 0000000..3768cb8 --- /dev/null +++ b/tests/cassettes/SchemasEndpointTestCase.test_schema.json @@ -0,0 +1,91 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:28", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/schemas/1" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s-esquema f\u00fatbol- LIGA BUENO\",\"static_image\":null,\"dynamic_image\":\"https://d3l13i8idnuwnd.cloudfront.net/map/1573.svg\",\"venue_schema_id\":1573,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}}" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "596" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:28 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:28 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "0687b8c0-c1cf-4a66-b132-c2634d49be21" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "fd72fbae-5583-4aeb-bcad-4a38c952dc48" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "Details for the schema resource" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/schemas/1" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/SchemasEndpointTestCase.test_schemas.json b/tests/cassettes/SchemasEndpointTestCase.test_schemas.json new file mode 100644 index 0000000..95ac095 --- /dev/null +++ b/tests/cassettes/SchemasEndpointTestCase.test_schemas.json @@ -0,0 +1,100 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:28", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/schemas?max=2&offset=0" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s-esquema f\u00fatbol- LIGA BUENO\",\"static_image\":null,\"dynamic_image\":\"https://d3l13i8idnuwnd.cloudfront.net/map/1573.svg\",\"venue_schema_id\":1573,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":272,\"name\":\"Estadio de San Mames - Concierto-esquema\",\"static_image\":\"https://s3-eu-west-1.amazonaws.com/tb-qa2-statics/esquema/272\",\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "1199" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:28 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:28 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "bacc1b59-9d87-4bd9-b826-0a0fcef1e17e" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "54c44fd7-4898-4979-af9c-5ccb6dbc0b8b" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of schema resources" + ], + "X-ticketbis-pageMaxSize": [ + "2" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "76574" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/schemas?max=2&offset=0" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/SchemasEndpointTestCase.test_schemas_by_venue.json b/tests/cassettes/SchemasEndpointTestCase.test_schemas_by_venue.json new file mode 100644 index 0000000..ca51202 --- /dev/null +++ b/tests/cassettes/SchemasEndpointTestCase.test_schemas_by_venue.json @@ -0,0 +1,100 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:28", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/venues/1/schemas" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s-esquema f\u00fatbol- LIGA BUENO\",\"static_image\":null,\"dynamic_image\":\"https://d3l13i8idnuwnd.cloudfront.net/map/1573.svg\",\"venue_schema_id\":1573,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":272,\"name\":\"Estadio de San Mames - Concierto-esquema\",\"static_image\":\"https://s3-eu-west-1.amazonaws.com/tb-qa2-statics/esquema/272\",\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":6253,\"name\":\"miCirco\",\"static_image\":null,\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":6280,\"name\":\"aaaaaaaaaaaaaaaa\",\"static_image\":null,\"dynamic_image\":\"https://d3l13i8idnuwnd.cloudfront.net/map/180.svg\",\"venue_schema_id\":180,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":6442,\"name\":\"Estadio San Mam\u00e9s - Provisional\",\"static_image\":\"https://s3-eu-west-1.amazonaws.com/tb-qa2-statics/esquema/6442.jpg\",\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":10454,\"name\":\"Estadio San Mam\u00e9s - Champions\",\"static_image\":\"https://s3-eu-west-1.amazonaws.com/tb-qa2-statics/esquema/10454.svg\",\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":15666,\"name\":\"Prueba colores\",\"static_image\":null,\"dynamic_image\":\"https://d3l13i8idnuwnd.cloudfront.net/map/135.svg\",\"venue_schema_id\":135,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":19175,\"name\":\"test mapa\",\"static_image\":null,\"dynamic_image\":\"https://d3l13i8idnuwnd.cloudfront.net/map/1050.svg\",\"venue_schema_id\":1050,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":21168,\"name\":\"Estadio de San Mam\u00e9s - concierto\",\"static_image\":null,\"dynamic_image\":\"https://d3l13i8idnuwnd.cloudfront.net/map/1823.svg\",\"venue_schema_id\":1823,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":37855,\"name\":\"Estadio de San Mam\u00e9s - rugby - 3 cats\",\"static_image\":null,\"dynamic_image\":\"https://d3l13i8idnuwnd.cloudfront.net/map/2312.svg\",\"venue_schema_id\":2312,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":39094,\"name\":\"san mames test Sonia\",\"static_image\":null,\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":56648,\"name\":\"Test Config\",\"static_image\":null,\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":62148,\"name\":\"Estadio de San Mam\u00e9s-esquema f\u00fatbol- LIGA BUENO - DYNAMIC\",\"static_image\":null,\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":63712,\"name\":\"San Mames - Concierto Pista GA ,Grada GA - Dynamic\",\"static_image\":null,\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":75360,\"name\":\"aaaaaaaaaaaaaaaa - DYNAMIC\",\"static_image\":null,\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}},{\"id\":77647,\"name\":\"UEFA Euro\",\"static_image\":null,\"dynamic_image\":null,\"venue_schema_id\":null,\"general_admission\":false,\"venue\":{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "8971" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:28 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:28 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "23fbba03-3336-4e09-914c-d3400f139d8d" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "92a0d72f-9044-43d4-bce4-9d9086020b82" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of schema resources" + ], + "X-ticketbis-pageMaxSize": [ + "100" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "16" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/venues/1/schemas" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/SectionGroupsEndpointTestCase.test_section_groups_by_event.json b/tests/cassettes/SectionGroupsEndpointTestCase.test_section_groups_by_event.json new file mode 100644 index 0000000..92ee3ca --- /dev/null +++ b/tests/cassettes/SectionGroupsEndpointTestCase.test_section_groups_by_event.json @@ -0,0 +1,195 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:32", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/events?max=1&offset=0" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":877217,\"name\":\"Harry Potter and the Cursed Child London (Part 1 & 2)\",\"title\":\"Entradas Harry Potter and the Cursed Child London (Part 1 & 2) | 04/09/2019 | StubHub Espa\u00f1a\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1-and-2/ev877217\",\"affiliate_url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-harry-potter-and-the-cursed-child-london-part-1-and-2/ev877217/fix\",\"market_type\":\"SECONDARY\",\"date\":\"2019-09-04T12:55:00Z\",\"localized_date\":\"04/09/2019-13:55\",\"updated_time\":\"2019-07-13T04:18:45Z\",\"timezone\":\"Europe/London\",\"image\":\"http://s3-eu-west-1.amazonaws.com/tb-qa2-statics/categoria/11246.jpg\",\"min_price\":{\"amount\":334.83,\"currency\":\"EUR\"},\"min_listing_price\":{\"amount\":334.83,\"currency\":\"EUR\"},\"external_platform\":null,\"details\":null,\"on_sale_date\":\"2018-12-06T16:00:00Z\",\"lastminute\":false,\"shipment_deadline\":\"2019-09-04T12:55:00Z\",\"pum_deadline\":\"2019-09-04T12:55:00Z\",\"lmsInstructions\":null,\"ticketbis_only\":false}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "996" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:32 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:32 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "5d35f7b0-1a6a-41ea-acf7-38988d825cf2" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "97d9c9c6-c855-483e-84e7-ac6ee5e6eed4" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of Event resources" + ], + "X-ticketbis-pageMaxSize": [ + "1" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "127210" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/events?max=1&offset=0" + } + }, + { + "recorded_at": "2019-09-04T11:44:32", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/events/877217/section_groups" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":3440006,\"name\":\"Grand Circle\",\"price_section\":null,\"color\":5},{\"id\":3440007,\"name\":\"Orchestra Stalls\",\"price_section\":null,\"color\":6},{\"id\":3440008,\"name\":\"Box\",\"price_section\":null,\"color\":2},{\"id\":3440009,\"name\":\"Boxes\",\"price_section\":null,\"color\":3},{\"id\":3440010,\"name\":\"Dress Circle\",\"price_section\":null,\"color\":4},{\"id\":3440011,\"name\":\"Balcony\",\"price_section\":null,\"color\":1}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "392" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:32 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:32 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "9e5538ed-2b4c-4be6-a4f1-6f68e7238330" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "e50436d5-6d69-41d4-b571-b37db8447be1" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of section_group resources" + ], + "X-ticketbis-pageMaxSize": [ + "6" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "6" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/events/877217/section_groups" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/SitesEndpointTestCase.test_site.json b/tests/cassettes/SitesEndpointTestCase.test_site.json new file mode 100644 index 0000000..b4c2be0 --- /dev/null +++ b/tests/cassettes/SitesEndpointTestCase.test_site.json @@ -0,0 +1,91 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:32", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/sites/1" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "{\"id\":1,\"locale\":\"es_ES\",\"brandName\":\"StubHub\",\"companyName\":\"eBay\",\"mixpanelActive\":false,\"layout\":\"stubhub\",\"logoName\":\"stubhub\",\"name\":\"ticketbisES\",\"url\":\"http://intl.stubhub.es.qa2.sh-env.net\",\"secure_url\":\"https://secure.stubhub.es.qa2.sh-env.net\",\"country\":{\"id\":10,\"name\":\"Espa\u00f1a\",\"a2\":\"ES\",\"timezone\":\"Europe/Madrid\",\"currency\":\"EUR\"},\"emailSender\":\"no-reply@stubhub.es\",\"brokerCustomerServiceEmail\":\"topsellers@stubhub.es\",\"customerServiceEmail\":\"contacto@stubhub.es\",\"hidden\":true}" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "493" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:32 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:32 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "94b8a47d-8230-42ed-b87b-3d86c868ca59" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "9834d639-dd71-42d8-ac3d-18b5e922e2e7" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "Details for the site resource" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/sites/1" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/SitesEndpointTestCase.test_sites.json b/tests/cassettes/SitesEndpointTestCase.test_sites.json new file mode 100644 index 0000000..b74a033 --- /dev/null +++ b/tests/cassettes/SitesEndpointTestCase.test_sites.json @@ -0,0 +1,100 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:32", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/sites?max=2&offset=0" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":1,\"locale\":\"es_ES\",\"brandName\":\"StubHub\",\"companyName\":\"eBay\",\"mixpanelActive\":false,\"layout\":\"stubhub\",\"logoName\":\"stubhub\",\"name\":\"ticketbisES\",\"url\":\"http://intl.stubhub.es.qa2.sh-env.net\",\"secure_url\":\"https://secure.stubhub.es.qa2.sh-env.net\",\"country\":{\"id\":10,\"name\":\"Espa\u00f1a\",\"a2\":\"ES\",\"timezone\":\"Europe/Madrid\",\"currency\":\"EUR\"},\"emailSender\":\"no-reply@stubhub.es\",\"brokerCustomerServiceEmail\":\"topsellers@stubhub.es\",\"customerServiceEmail\":\"contacto@stubhub.es\",\"hidden\":true},{\"id\":2,\"locale\":\"it_IT\",\"brandName\":\"StubHub\",\"companyName\":\"eBay\",\"mixpanelActive\":false,\"layout\":\"stubhub\",\"logoName\":\"stubhub\",\"name\":\"ticketbisIT\",\"url\":\"http://intl.stubhub.it.qa2.sh-env.net\",\"secure_url\":\"https://secure.stubhub.it.qa2.sh-env.net\",\"country\":{\"id\":12,\"name\":\"Italia\",\"a2\":\"IT\",\"timezone\":\"Europe/Rome\",\"currency\":\"EUR\"},\"emailSender\":\"no-reply@stubhub.it\",\"brokerCustomerServiceEmail\":\"topsellers@stubhub.it\",\"customerServiceEmail\":\"contatto@stubhub.it\",\"hidden\":true}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "986" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:32 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:32 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "ffbea67f-772f-4c68-8e2c-1460acf8cc29" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "2af1d7c8-3ffc-4b68-90dd-6848ab75714e" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of site resources" + ], + "X-ticketbis-pageMaxSize": [ + "2" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "4" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/sites?max=2&offset=0" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/VenuesEndpointTestCase.test_venue.json b/tests/cassettes/VenuesEndpointTestCase.test_venue.json new file mode 100644 index 0000000..8ba792b --- /dev/null +++ b/tests/cassettes/VenuesEndpointTestCase.test_venue.json @@ -0,0 +1,91 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:33", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/venues/1" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000}" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "382" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:33 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:33 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "976fb9aa-afc8-4d29-a529-9bca29589d9a" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "f63fb212-1c9e-4690-9b10-655b2d42e470" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "Details for the Venue resource" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/venues/1" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/tests/cassettes/VenuesEndpointTestCase.test_venues.json b/tests/cassettes/VenuesEndpointTestCase.test_venues.json new file mode 100644 index 0000000..7b0e9c7 --- /dev/null +++ b/tests/cassettes/VenuesEndpointTestCase.test_venues.json @@ -0,0 +1,100 @@ +{ + "http_interactions": [ + { + "recorded_at": "2019-09-04T11:44:33", + "request": { + "body": { + "encoding": "utf-8", + "string": "" + }, + "headers": { + "Accept": [ + "application/vnd.ticketbis.v1+json, application/json" + ], + "Authorization": [ + "Basic " + ], + "Connection": [ + "keep-alive" + ], + "Content-Type": [ + "application/json" + ], + "User-Agent": [ + "python-requests/2.22.0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ] + }, + "method": "GET", + "uri": "https://buscaticket.com.qa2.sh-env.net/api/venues?max=2&offset=0" + }, + "response": { + "body": { + "encoding": "utf-8", + "string": "[{\"id\":1,\"name\":\"Estadio de San Mam\u00e9s\",\"city\":{\"id\":1,\"latitude\":43.2630051,\"longitude\":-2.9349915,\"name\":\"Bilbao\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-bilbao\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-bilbao/ct1\"},\"address\":\"15 Calle de Bri\u00f1as, Bilbao, PV 48013\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":43.2623200,\"longitude\":-2.9480000},{\"id\":6,\"name\":\"WiZink Center (Palacio de los Deportes)\",\"city\":{\"id\":5556,\"latitude\":40.4167047,\"longitude\":-3.7035825,\"name\":\"Madrid\",\"country\":\"Espa\u00f1a\",\"countryCode\":\"ES\",\"slug\":\"entradas-madrid\",\"url\":\"https://intl.stubhub.es.qa2.sh-env.net/entradas-madrid/ct5556\"},\"address\":\"Avenida Felipe II, s/n, 28009 Madrid Spain, Madrid, MAD 28009\",\"country\":\"Espa\u00f1a\",\"country_code\":\"ES\",\"latitude\":40.4239600,\"longitude\":-3.6742200}]" + }, + "headers": { + "Access-Control-Allow-Origin": [ + "*" + ], + "Cache-Control": [ + "max-age=0" + ], + "Connection": [ + "keep-alive" + ], + "Content-Length": [ + "815" + ], + "Content-Type": [ + "application/json;charset=utf-8" + ], + "Date": [ + "Wed, 04 Sep 2019 11:44:33 GMT" + ], + "Expires": [ + "Wed, 04 Sep 2019 11:44:33 GMT" + ], + "Server": [ + "nginx" + ], + "X-Request-ID": [ + "85c66f1c-e329-4816-9f36-869c94f1896d" + ], + "X-Robots-Tag": [ + "noindex" + ], + "X-Stubhub-International-dye": [ + "45d5f7aa-70d6-4955-8aee-0bbfe83b998a" + ], + "X-ticketbis-Media-Type": [ + "application/json" + ], + "X-ticketbis-message": [ + "List of Venue resources" + ], + "X-ticketbis-pageMaxSize": [ + "2" + ], + "X-ticketbis-pageOffset": [ + "0" + ], + "X-ticketbis-site": [ + "ticketbisES" + ], + "X-ticketbis-totalCount": [ + "28789" + ] + }, + "status": { + "code": 200, + "message": "OK" + }, + "url": "https://buscaticket.com.qa2.sh-env.net/api/venues?max=2&offset=0" + } + } + ], + "recorded_with": "betamax/0.8.1" +} \ No newline at end of file diff --git a/ticketbis/tests/readme.md b/tests/readme.md similarity index 100% rename from ticketbis/tests/readme.md rename to tests/readme.md diff --git a/ticketbis/tests/test_categories.py b/tests/test_categories.py similarity index 100% rename from ticketbis/tests/test_categories.py rename to tests/test_categories.py diff --git a/ticketbis/tests/test_events.py b/tests/test_events.py similarity index 100% rename from ticketbis/tests/test_events.py rename to tests/test_events.py diff --git a/ticketbis/tests/test_oauth.py b/tests/test_oauth.py similarity index 100% rename from ticketbis/tests/test_oauth.py rename to tests/test_oauth.py diff --git a/ticketbis/tests/test_schemas.py b/tests/test_schemas.py similarity index 100% rename from ticketbis/tests/test_schemas.py rename to tests/test_schemas.py diff --git a/ticketbis/tests/test_section_groups.py b/tests/test_section_groups.py similarity index 100% rename from ticketbis/tests/test_section_groups.py rename to tests/test_section_groups.py diff --git a/ticketbis/tests/test_sites.py b/tests/test_sites.py similarity index 100% rename from ticketbis/tests/test_sites.py rename to tests/test_sites.py diff --git a/ticketbis/tests/test_venues.py b/tests/test_venues.py similarity index 100% rename from ticketbis/tests/test_venues.py rename to tests/test_venues.py diff --git a/ticketbis/__init__.py b/ticketbis/__init__.py index d04b9b1..d1f611d 100644 --- a/ticketbis/__init__.py +++ b/ticketbis/__init__.py @@ -45,7 +45,6 @@ import requests from six.moves.urllib import parse - from six.moves import xrange import six # Monkey patch to requests' json using ujson when available; @@ -168,6 +167,7 @@ def __init__( grant_type=AUTH_CODE_GRANT_TYPE, api_endpoint=API_ENDPOINT, auth=None, + session=None, ): """Sets up the api object""" self.oauth = self.OAuth( @@ -183,6 +183,7 @@ def __init__( site, lang, auth, + session, ) # Dynamically enable endpoints @@ -303,6 +304,7 @@ def __init__( site=None, lang=None, auth=None, + session=None, ): """Set up the API object""" self.client_id = client_id @@ -329,6 +331,8 @@ def __init__( "Content-Type": "application/json", } + self.session = session or requests.Session() + def set_token(self, access_token): """Set the OAuth token for this requester""" self.oauth_token = access_token @@ -345,7 +349,13 @@ def GET(self, path, params={}, **kwargs): params = self._enrich_params(params) url = self._get_url(path) - result = _get(url, headers=headers, params=params, auth=self.auth) + result = _get( + url, + headers=headers, + params=params, + auth=self.auth, + session=self.session, + ) self._set_header_properties(result) return result["data"] @@ -360,7 +370,13 @@ def GET_PAGINATED(self, path, params={}, **kwargs): pending_pages = True while pending_pages: - result = _get(url, headers=headers, params=params, auth=self.auth) + result = _get( + url, + headers=headers, + params=params, + auth=self.auth, + session=self.session, + ) self._set_header_properties(result) pending_pages = ( self.page_offset + len(result["data"]) < self.total_count @@ -402,7 +418,12 @@ def POST(self, path, data={}, files=None): data = self._enrich_params(data) url = self._get_url(path) result = _post( - url, headers=headers, data=json.dumps(data), files=files, auth=self.auth + url, + headers=headers, + data=json.dumps(data), + files=files, + auth=self.auth, + session=self.session, ) self.rate_limit = result["headers"].get("X-RateLimit-Limit", None) self.rate_remaining = result["headers"].get("X-RateLimit-Remaining", None) @@ -418,7 +439,12 @@ def PUT(self, path, data={}, files=None): data = self._enrich_params(data) url = self._get_url(path) result = _put( - url, headers=headers, data=json.dumps(data), files=files, auth=self.auth + url, + headers=headers, + data=json.dumps(data), + files=files, + auth=self.auth, + session=self.session, ) self.rate_limit = result["headers"].get("X-RateLimit-Limit", None) self.rate_remaining = result["headers"].get("X-RateLimit-Remaining", None) @@ -440,8 +466,8 @@ def _create_headers(self): """Get the headers we need""" headers = self.base_headers.copy() - if not self.userless: - headers["Authorization"] = "Bearer {0}".format(self.oauth_token) + if not self.userless: # FIXME + headers["Authorization"] = "Basic {0}".format(self.oauth_token) if self.site: headers["X-ticketbis-site"] = self.site elif self.lang: @@ -630,13 +656,13 @@ def _log_and_raise_exception(msg, data, cls=TicketbisException): #: Network helper functions -def _get(url, headers={}, params=None, auth=None): +def _get(url, headers={}, params=None, auth=None, session=requests): """Try to GET data from an endpoint using retries""" param_string = _ticketbis_urlencode(params) - for i in xrange(NUM_REQUEST_RETRIES): + for i in range(NUM_REQUEST_RETRIES): try: try: - response = requests.get( + response = session.get( url, headers=headers, params=param_string, @@ -662,10 +688,10 @@ def _get(url, headers={}, params=None, auth=None): time.sleep(1) -def _post(url, headers={}, data=None, files=None, auth=None): +def _post(url, headers={}, data=None, files=None, auth=None, session=requests): """Try to POST data to an endpoint""" try: - response = requests.post( + response = session.post( url, headers=headers, data=data, files=files, verify=VERIFY_SSL, auth=auth ) return _process_response(response) @@ -673,10 +699,10 @@ def _post(url, headers={}, data=None, files=None, auth=None): _log_and_raise_exception("Error connecting with ticketbis API", e) -def _put(url, headers={}, data=None, files=None, auth=None): +def _put(url, headers={}, data=None, files=None, auth=None, session=requests): """Try to PUT data to an endpoint""" try: - response = requests.put( + response = session.put( url, headers=headers, data=data, files=files, verify=VERIFY_SSL, auth=auth ) return _process_response(response) From 90ef0af836ca9075e4fdb19957141b03505400a5 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Wed, 4 Sep 2019 14:29:02 +0200 Subject: [PATCH 3/4] docs(README): update links and license mention --- README.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 3ee51b0..df2570f 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # Ticketbis +[![Build Status](https://travis-ci.org/ticketbis/ticketbis-python-api-client.svg?branch=master)](https://travis-ci.org/ticketbis/ticketbis-python-api-client) + +[![Coverage Status](https://coveralls.io/repos/github/ticketbis/ticketbis-python-api-client/badge.svg?branch=master)](https://coveralls.io/github/ticketbis/ticketbis-python-api-client?branch=master) + Python wrapper for the [Ticketbis API](http://api.ticketbis.com). NOTE: This document is a *work in progress*. @@ -26,7 +30,7 @@ or Depending upon your system and virtualenv settings, these may require sudo permissions. -[PyPi page](https://pypi.python.org/pypi/ticketbis) +[PyPi page](https://pypi.org/project/ticketbis/) ## Usage @@ -175,5 +179,5 @@ In order to run the tests: * Run `python setup.py test` ## License -MIT License. See LICENSE -Copyright (c) 2015 Ticketbis +Apache License Version 2.0. See the LICENSE file. +Copyright (c) 2015-2019 Ticketbis From 6c1d2df724c3f0dd2e116fa5437a36213f1c9517 Mon Sep 17 00:00:00 2001 From: Jiri Kuncar Date: Wed, 4 Sep 2019 15:02:07 +0200 Subject: [PATCH 4/4] ci(travis): run pre-commit checks only on Python 3+ --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 433e44f..f5d6be1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -37,7 +37,7 @@ install: script: - check-manifest --ignore=tests - - pre-commit run -a + - if [[ $TRAVIS_PYTHON_VERSION != "2.7" ]]; then pre-commit run -a; fi - python setup.py test after_success: