Exemplo 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
Exemplo n.º 2
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)
Exemplo n.º 3
0
from pycaching.errors import Error
from pycaching.geocaching import Geocaching
from .helpers import sanitize_cookies

username = os.environ.get('PYCACHING_TEST_USERNAME') or 'USERNAMEPLACEHOLDER'
password = os.environ.get('PYCACHING_TEST_PASSWORD') or 'PASSWORDPLACEHOLDER'

path = str(Path('test/cassettes'))

with Betamax.configure() as config:
    config.cassette_library_dir = path
    config.define_cassette_placeholder('<USERNAME>', quote_plus(username))
    config.define_cassette_placeholder('<PASSWORD>', quote_plus(password))
    config.before_record(callback=sanitize_cookies)

Betamax.register_serializer(PrettyJSONSerializer)


class NetworkedTest(unittest.TestCase):
    """Class to represent tests that perform network requests"""

    @classmethod
    def setUpClass(cls):
        cls.session = Session()
        cls.recorder = Betamax(cls.session, default_cassette_options={'serialize_with': 'prettyjson'})
        cls.gc = Geocaching(session=cls.session)
        try:
            cls.gc.login(username, password)
        except Error:
            # LoginFailedException is raised with invalid creds; Error is raised
            # with no network connection. This is okay as long as we aren't
Exemplo n.º 4
0

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)
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, **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.

    """
Exemplo n.º 5
0
    unicode
except NameError:
    basestring = unicode = str


CREDS_FILENAME = os.getenv('GS_CREDS_FILENAME')

SCOPE = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive.file',
]
DUMMY_ACCESS_TOKEN = '<ACCESS_TOKEN>'

I18N_STR = u'Iñtërnâtiônàlizætiøn'  # .encode('utf8')

Betamax.register_serializer(JSONBodySerializer)


def sanitize_token(interaction, current_cassette):
    headers = interaction.data['request']['headers']
    token = headers.get('Authorization')

    if token is None:
        return

    interaction.data['request']['headers']['Authorization'] = [
        'Bearer %s' % DUMMY_ACCESS_TOKEN
    ]


with Betamax.configure() as config:
Exemplo n.º 6
0
try:
    unicode
except NameError:
    basestring = unicode = str

CREDS_FILENAME = os.getenv('GS_CREDS_FILENAME')

SCOPE = [
    'https://spreadsheets.google.com/feeds',
    'https://www.googleapis.com/auth/drive.file',
]
DUMMY_ACCESS_TOKEN = '<ACCESS_TOKEN>'

I18N_STR = u'Iñtërnâtiônàlizætiøn'  # .encode('utf8')

Betamax.register_serializer(JSONBodySerializer)


def sanitize_token(interaction, current_cassette):
    headers = interaction.data['request']['headers']
    token = headers.get('Authorization')

    if token is None:
        return

    interaction.data['request']['headers']['Authorization'] = [
        'Bearer %s' % DUMMY_ACCESS_TOKEN
    ]


with Betamax.configure() as config:
Exemplo n.º 7
0
def betamax_recorder(nonblock_session):
    Betamax.register_serializer(pretty_json.PrettyJSONSerializer)
    return Betamax(nonblock_session, cassette_library_dir=CASSETTE_LIBRARY_DIR)