def configure(): config = Betamax.configure() config.cassette_library_dir = "tests/test_api/betamax/" config.default_cassette_options['record_mode'] = 'once' config.default_cassette_options['match_requests_on'] = ['method', 'path_matcher'] if credentials: auth_key = 'token' if 'token' in credentials else 'password' config.define_cassette_placeholder( '<ZENPY-CREDENTIALS>', str(base64.b64encode( "{}/token:{}".format(credentials['email'], credentials[auth_key]).encode('utf-8') )) ) session = requests.Session() credentials['session'] = session zenpy_client = Zenpy(**credentials) recorder = Betamax(session=session) class PathMatcher(URIMatcher): """ I use trial accounts for testing Zenpy and as such the subdomain is always changing. This matcher ignores the netloc section of the parsed URL which prevents the tests failing when the subdomain is changed. """ name = 'path_matcher' def parse(self, uri): parse_result = super(PathMatcher, self).parse(uri) parse_result.pop('netloc') return parse_result Betamax.register_request_matcher(PathMatcher) recorder.register_serializer(PrettyJSONSerializer) return zenpy_client, recorder
def test_register_request_matcher(self): class FakeMatcher(object): name = 'fake' Betamax.register_request_matcher(FakeMatcher) assert 'fake' in matchers.matcher_registry assert isinstance(matchers.matcher_registry['fake'], FakeMatcher)
def setup_betamax(): """Do global configuration for betamax. This function is idempotent.""" Betamax.register_request_matcher(CustomBodyMatcher) Betamax.register_serializer(PrettyJSONSerializer) config = Betamax.configure() config.cassette_library_dir = "cassettes" config.default_cassette_options['match_requests_on'] = [ 'uri', 'method', 'custom-body' ] config.default_cassette_options['serialize_with'] = 'prettyjson'
def setup_betamax(record_mode="none"): """Do global configuration for betamax. This function is idempotent.""" Betamax.register_request_matcher(CustomBodyMatcher) Betamax.register_serializer(PrettyJSONSerializer) config = Betamax.configure() config.cassette_library_dir = "cassettes" config.default_cassette_options["match_requests_on"] = [ "uri", "method", "custom-body", ] config.default_cassette_options["serialize_with"] = "prettyjson" config.default_cassette_options["record_mode"] = record_mode
def configure(): config = Betamax.configure() config.cassette_library_dir = "tests/test_api/betamax/" config.default_cassette_options["record_mode"] = "once" config.default_cassette_options["match_requests_on"] = ["method", "path_matcher"] if credentials: auth_key = "token" if "token" in credentials else "password" config.define_cassette_placeholder( "<ZENPY-CREDENTIALS>", str( base64.b64encode( "{}/token:{}".format( credentials["email"], credentials[auth_key] ).encode("utf-8") ) ), ) session = requests.Session() credentials["session"] = session zenpy_client = Zenpy(**credentials) recorder = Betamax(session=session) class PathMatcher(URIMatcher): """ I use trial accounts for testing Zenpy and as such the subdomain is always changing. This matcher ignores the netloc section of the parsed URL which prevents the tests failing when the subdomain is changed. """ name = "path_matcher" def parse(self, uri): parse_result = super(PathMatcher, self).parse(uri) parse_result.pop("netloc") return parse_result Betamax.register_request_matcher(PathMatcher) recorder.register_serializer(PrettyJSONSerializer) return zenpy_client, recorder
def configure(): config = Betamax.configure() config.cassette_library_dir = "tests/test_api/betamax/" config.default_cassette_options['record_mode'] = 'once' config.default_cassette_options['match_requests_on'] = [ 'method', 'path_matcher' ] if credentials: auth_key = 'token' if 'token' in credentials else 'password' config.define_cassette_placeholder( '<ZENPY-CREDENTIALS>', str( base64.b64encode("{}/token:{}".format( credentials['email'], credentials[auth_key]).encode('utf-8')))) session = requests.Session() credentials['session'] = session zenpy_client = Zenpy(**credentials) recorder = Betamax(session=session) class PathMatcher(URIMatcher): """ I use trial accounts for testing Zenpy and as such the subdomain is always changing. This matcher ignores the netloc section of the parsed URL which prevents the tests failing when the subdomain is changed. """ name = 'path_matcher' def parse(self, uri): parse_result = super(PathMatcher, self).parse(uri) parse_result.pop('netloc') return parse_result Betamax.register_request_matcher(PathMatcher) recorder.register_serializer(PrettyJSONSerializer) return zenpy_client, recorder
first_hit = next((x for x in sequence if predicate(x)), None) self.assertTrue(first_hit) return first_hit def none(self, sequence, predicate): self.assertEqual( None, next((x for x in sequence if predicate(x)), None)) def setUp(self): self.configure() def url(self, path): return urljoin(self.r.config.permalink_url, path) Betamax.register_request_matcher(BodyMatcher) with Betamax.configure() as config: if os.getenv('TRAVIS'): config.default_cassette_options['record_mode'] = 'none' config.cassette_library_dir = 'tests/cassettes' config.default_cassette_options['match_requests_on'].append('PRAWBody') def betamax(cassette_name=None, **cassette_options): """Utilze betamax to record/replay any network activity of the test. The wrapped function's `betmax_init` method will be invoked if it exists. """ def factory(function): @wraps(function)
return urljoin(self.r.config.permalink_url, path) class OAuthPRAWTest(PRAWTest): def betamax_init(self): self.r.set_oauth_app_info(self.client_id, self.client_secret, self.redirect_uri) def setUp(self): self.configure() self.r = Reddit(USER_AGENT, site_name='reddit_oauth_test', disable_update_check=True) Betamax.register_request_matcher(BodyMatcher) with Betamax.configure() as config: if os.getenv('TRAVIS'): config.default_cassette_options['record_mode'] = 'none' config.cassette_library_dir = 'tests/cassettes' config.default_cassette_options['match_requests_on'].append('PRAWBody') def betamax(cassette_name=None, **cassette_options): """Utilze betamax to record/replay any network activity of the test. The wrapped function's `betmax_init` method will be invoked if it exists. """ def factory(function): @wraps(function)
class SalesforceRestMatcher(BaseMatcher): name = "salesforce_rest" excluded_query_keys = ("start", "end") def to_dict(self, query): query_dict = parse_qs(query or "") # Protect against None return dict(filter(lambda i: i[0] not in self.excluded_query_keys, query_dict.items())) def match(self, request, recorded_request): request_query = self.to_dict(urlparse(request.url).query) recorded_query = self.to_dict(urlparse(recorded_request["uri"]).query) return request_query == recorded_query Betamax.register_request_matcher(SalesforceRestMatcher) custom_object_name = primitives.capital_word(charset=string.lowercase) with Betamax.configure() as config: config.define_cassette_placeholder("__CUSTOM_OBJECT_NAME__", custom_object_name) #### Fixtures #### @pytest.yield_fixture(scope="module") def metadata_client(request): Client = getattr(request.module, "metadata_client_class") client = Client(client_id, client_secret, domain, access_token) cassette_name = ".".join((request.module.__name__, "metadata"))
excluded_query_keys = ('start', 'end') def to_dict(self, query): query_dict = parse_qs(query or '') # Protect against None return dict( filter(lambda i: i[0] not in self.excluded_query_keys, query_dict.items())) def match(self, request, recorded_request): request_query = self.to_dict(urlparse(request.url).query) recorded_query = self.to_dict(urlparse(recorded_request['uri']).query) return request_query == recorded_query Betamax.register_request_matcher(SalesforceRestMatcher) custom_object_name = primitives.capital_word(charset=string.lowercase) with Betamax.configure() as config: config.define_cassette_placeholder('__CUSTOM_OBJECT_NAME__', custom_object_name) #### Fixtures #### @pytest.yield_fixture(scope='module') def metadata_client(request): Client = getattr(request.module, "metadata_client_class") client = Client(client_id, client_secret, domain, access_token)
from __future__ import unicode_literals import os import pytest from betamax import Betamax from betamax_serializers import pretty_json from betamax_matchers import json_body import helium_commander Betamax.register_serializer(pretty_json.PrettyJSONSerializer) Betamax.register_request_matcher(json_body.JSONBodyMatcher) API_TOKEN = os.environ.get('HELIUM_API_KEY', 'X' * 10) API_URL = os.environ.get('HELIUM_API_URL', 'https://api.helium.com/v1') RECORD_MODE = os.environ.get('HELIUM_RECORD_MODE', 'none') RECORD_FOLDER = os.environ.get('HELIUM_RECORD_FOLDER', 'tests/cassettes') with Betamax.configure() as config: config.cassette_library_dir = RECORD_FOLDER record_mode = RECORD_MODE cassette_options = config.default_cassette_options cassette_options['record_mode'] = record_mode cassette_options['serialize_with'] = 'prettyjson' cassette_options['match_requests_on'].append('json-body') config.define_cassette_placeholder('<AUTH_TOKEN>', API_TOKEN) @pytest.fixture def helium_recorder(request): """Generate and start a recorder using a helium.Client."""
def setUp(self): self.configure() self.r = Reddit(USER_AGENT, site_name='reddit_oauth_test', disable_update_check=True) class NewOAuthPRAWTest(OAuthPRAWTest): def betamax_init(self): # All tokens were revoked before all tests were completed self.r.set_oauth_app_info(self.new_client_id, self.new_client_secret, self.new_redirect_uri) Betamax.register_request_matcher(BodyMatcher) Betamax.register_request_matcher(CustomHeaderMatcher) Betamax.register_serializer(pretty_json.PrettyJSONSerializer) with Betamax.configure() as config: if os.getenv('TRAVIS'): config.default_cassette_options['record_mode'] = 'none' config.cassette_library_dir = 'tests/cassettes' config.default_cassette_options['match_requests_on'].append('PRAWBody') config.default_cassette_options['serialize_with'] = 'prettyjson' def betamax(cassette_name=None, pass_recorder=False, **cassette_options): """Utilze betamax to record/replay any network activity of the test. The wrapped function's `betmax_init` method will be invoked if it exists.