Esempio n. 1
0
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_preserve_exact_body_bytes(self):
        with Betamax.configure() as config:
            config.preserve_exact_body_bytes = True

        with Betamax(self.session) as b:
            b.use_cassette('global_preserve_exact_body_bytes')
            r = self.session.get('https://httpbin.org/get')
            assert 'headers' in r.json()

            interaction = b.current_cassette.interactions[0].json
            assert 'base64_string' in interaction['response']['body']
Esempio n. 3
0
    def setUpClass(cls):

        cls.session = requests.Session()
        cls.recorder = Betamax(cls.session)

        cls.api_key = config.MAILCHIMP_API_KEY

        # the subdomain to use in the api url
        # is always the last 3 characters of the api key
        cls.subdomain = cls.api_key[-3:]

        # define the string that will be passed in the MailChimp request
        # 'Authorization' header
        MAILCHIMP_REQUEST_AUTH_HEADER_NAME = 'apikey'
        MAILCHIMP_REQUEST_AUTH_HEADER = '{}:{}'.format(
            MAILCHIMP_REQUEST_AUTH_HEADER_NAME, cls.api_key)

        # create the directory to store betamax cassettes
        abs_cassette_dir = os.path.join(os.path.dirname(
            os.path.abspath(__file__)), cls.cassette_dir)
        os.makedirs(abs_cassette_dir, exist_ok=True)

        Betamax.register_serializer(pretty_json.PrettyJSONSerializer)
        with Betamax.configure() as betamaxconfig:
            betamaxconfig.cassette_library_dir = abs_cassette_dir
            betamaxconfig.default_cassette_options['record_mode'] = 'once'
            betamaxconfig.default_cassette_options[
                'serialize_with'] = 'prettyjson'
            betamaxconfig.default_cassette_options['match_requests_on'] = [
                'method'
            ]
            betamaxconfig.define_cassette_placeholder(
                '<MAILCHIMP_AUTH_B64>',
                base64.b64encode(
                    MAILCHIMP_REQUEST_AUTH_HEADER.encode()
                ).decode()
            )
            betamaxconfig.define_cassette_placeholder(
                '<MAILCHIMP_SUBDOMAIN>',
                cls.subdomain
            )

        # suppress these warnings (due to requests module): 
        # ResourceWarning: unclosed <ssl.SSLSocket
        warnings.simplefilter("ignore", ResourceWarning)
def configure_betamax(api, **additional_apis):
    with Betamax.configure() as config:
        config.cassette_library_dir = 'tests/fixtures/cassettes'
        config.match_requests_on = ['method', 'uri', 'body']

        def _set_api(api, template):
            for attr in ('username', 'password', 'password_hash'):
                value = getattr(api, attr, None)
                if value:
                    config.define_cassette_placeholder(template % attr.upper(), value)

        # Configure primary API
        config.define_cassette_placeholder('<URL>', api.url)
        _set_api(api, '<%s>')

        # Any additional APIs
        for name, api in additional_apis.items():
            template = '<' + name.upper() + '_%s>' if name else '<%s>'
            _set_api(api, template)
Esempio n. 5
0
def configure_betamax(api, **additional_apis):
    with Betamax.configure() as config:
        config.cassette_library_dir = 'tests/fixtures/cassettes'
        config.default_cassette_options['match_options'] = ['method', 'uri', 'body']

        def _set_api(api, template):
            for attr in ('username', 'password', 'password_hash'):
                value = getattr(api, attr, None)
                if value:
                    config.define_cassette_placeholder(template % attr.upper(), value)

        # Configure primary API
        config.define_cassette_placeholder('<URL>', api.url)
        _set_api(api, '<%s>')
        # placeholders aren't replaced in gzipped responses
        api.session.headers['Accept-Encoding'] = ''

        # Any additional APIs
        for name, api in additional_apis.items():
            template = '<' + name.upper() + '_%s>' if name else '<%s>'
            _set_api(api, template)
            # placeholders aren't replaced in gzipped responses
            api.session.headers['Accept-Encoding'] = ''
Esempio n. 6
0
        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)
        def betamax_function(obj):
Esempio n. 7
0
 def setUp(self):
     super(TestPlaceholders, self).setUp()
     config = Betamax.configure()
     config.define_cassette_placeholder('<AUTHORIZATION>', b64_foobar)
 def setUp(self):
     with Betamax.configure() as config:
         config.default_cassette_options['record_mode'] = 'none'
 def tearDown(self):
     with Betamax.configure() as config:
         config.default_cassette_options['record_mode'] = 'once'
Esempio n. 10
0
"""muttlib.gdrive test suite."""
import os
import unittest

import betamax
import requests
from betamax import Betamax
from betamax_serializers import pretty_json

from muttlib.gdrive import GDrive, GDriveMimeType

betamax.Betamax.register_serializer(pretty_json.PrettyJSONSerializer)

with Betamax.configure() as config:
    config.cassette_library_dir = 'tests/cassettes'
    # https://betamax.readthedocs.io/en/latest/record_modes.html
    record_mode = os.environ.get('MUTTLIB_RECORD_MODE', 'once')
    config.default_cassette_options['record_mode'] = record_mode
    config.default_cassette_options['serialize_with'] = 'prettyjson'

# TODO: provide a reasonable default
CREDS_FILE = os.getenv('MUTTLIB_GOOGLE_TEST_SERVICE_ACCOUNT_CREDS')


class BetamaxTest(unittest.TestCase):
    """Base TestCase class for using Betamax.

    This implementation is based on betamax.fixtures.unittest.py.
    """
    @classmethod
    def setUpClass(cls):
Esempio n. 11
0
ddi_site_name = os.environ.get('DDI_SITE_NAME', 'EXAMPLE')
ddi_url = url_normalize.url_normalize(ddi_server)
ddi_username = os.environ.get('DDI_USERNAME', 'test_user')
domain_name = os.environ.get('DOMAINNAME', 'example.com')
errant_ddi_host = 'bad-host.example.com'

# Test variables:
errant_ipv4_address = '1.1.1.1'
errant_subnet_address = '1.1.1.0'
ipv4_address = '172.23.23.4'
subnet_address = '172.23.23.0'

# Makes the output more readable
Betamax.register_serializer(PrettyJSONSerializer)

config = Betamax.configure()
config.cassette_library_dir = 'tests/cassettes'
config.default_cassette_options['serialize_with'] = 'prettyjson'
config.default_cassette_options['placeholders'] = [
    {
        'placeholder': '<PASSWORD>',
        'replace': base64.b64encode(ddi_password.encode()).decode()
    },
    {
        'placeholder': '<LOGIN>',
        'replace': base64.b64encode(ddi_username.encode()).decode()
    },
    {
        'placeholder': '<DDI_SERVER>',
        'replace': ddi_server
    },
Esempio n. 12
0
 def setUp(self):
     super(TestPlaceholders, self).setUp()
     config = Betamax.configure()
     config.define_cassette_placeholder('<AUTHORIZATION>', b64_foobar)