本文整理汇总了Python中betamax.Betamax类的典型用法代码示例。如果您正苦于以下问题:Python Betamax类的具体用法?Python Betamax怎么用?Python Betamax使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Betamax类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_register_request_matcher
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)
示例2: test_creates_new_cassettes
def test_creates_new_cassettes(self):
recorder = Betamax(self.session)
opts = {"record": "new_episodes"}
cassette_name = "test_record_new_makes_new_cassettes"
with recorder.use_cassette(cassette_name, **opts) as betamax:
self.cassette_path = betamax.current_cassette.cassette_path
self.session.get("https://httpbin.org/get")
示例3: setUp
def setUp(self):
self.api_key = "dummy_key"
self.betamax_record = "none"
if os.environ.get("BESNAPPY_TEST_RECORD_REQUESTS"):
if BESNAPPY_TEST_API_KEY:
self.betamax_record = "all"
self.api_key = BESNAPPY_TEST_API_KEY
else:
raise RuntimeError(
"BESNAPPY_TEST_RECORD_REQUESTS is set, but"
" BESNAPPY_TEST_API_KEY is not.")
self.no_http_session = TestSession()
self.betamax_session = Session()
# We reset the Accept-Encoding header to avoid storing (opaque) gzip
# response data.
self.betamax_session.headers["Accept-Encoding"] = ""
self.betamax = Betamax(
self.betamax_session, cassette_library_dir=CASSETTE_LIBRARY_DIR)
self.common_session = Session()
# We reset the Accept-Encoding header to avoid storing (opaque) gzip
# response data.
self.common_session.headers["Accept-Encoding"] = ""
self.betamax_common = Betamax(
self.common_session, cassette_library_dir=CASSETTE_LIBRARY_DIR)
self.betamax_placeholders = []
self.common_snappy = self._get_common_snappy()
示例4: TestBetamax
class TestBetamax(unittest.TestCase):
def setUp(self):
self.session = Session()
self.vcr = Betamax(self.session)
def test_initialization_does_alter_the_session(self):
for v in self.session.adapters.values():
assert not isinstance(v, BetamaxAdapter)
assert isinstance(v, HTTPAdapter)
def test_entering_context_alters_adapters(self):
with self.vcr:
for v in self.session.adapters.values():
assert isinstance(v, BetamaxAdapter)
def test_exiting_resets_the_adapters(self):
with self.vcr:
pass
for v in self.session.adapters.values():
assert not isinstance(v, BetamaxAdapter)
def test_current_cassette(self):
assert self.vcr.current_cassette is None
self.vcr.use_cassette('test')
assert isinstance(self.vcr.current_cassette, Cassette)
def test_use_cassette_returns_cassette_object(self):
assert self.vcr.use_cassette('test') is self.vcr
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 test_stores_the_session_instance(self):
assert self.session is self.vcr.session
def test_replaces_all_adapters(self):
mount_point = 'fake_protocol://'
s = Session()
s.mount(mount_point, HTTPAdapter())
with Betamax(s):
adapter = s.adapters.get(mount_point)
assert adapter is not None
assert isinstance(adapter, BetamaxAdapter)
示例5: setUpClass
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)
示例6: setup
def setup(self):
self.lat = 51.0 + 32.0/60.0
self.lng = -22.0/60.0
self.year = 2015
self.usno_data = USNO_Data(self.lat, self.lng)
self.recorder = Betamax(self.usno_data.session, default_cassette_options={
'record_mode': 'once',
'match_requests_on': ['method', 'uri', 'headers'],
'preserve_exact_body_bytes': True
})
示例7: helium_recorder
def helium_recorder(request):
"""Generate and start a recorder using a helium.Client."""
cassette_name = ''
if request.module is not None:
cassette_name += request.module.__name__ + '.'
if request.cls is not None:
cassette_name += request.cls.__name__ + '.'
cassette_name += request.function.__name__
session = helium_commander.Client(base_url=API_URL)
session.token_auth(API_TOKEN)
recorder = Betamax(session)
recorder.use_cassette(cassette_name)
recorder.start()
request.addfinalizer(recorder.stop)
return recorder
示例8: test_preserve_exact_body_bytes
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']
示例9: configure
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
示例10: configure_betamax
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)
示例11: configure_betamax
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'] = ''
示例12: setUp
def setUp(self):
super(TestPlaceholders, self).setUp()
config = Betamax.configure()
config.define_cassette_placeholder('<AUTHORIZATION>', b64_foobar)
示例13: urljoin
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)
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.
示例14: setup
def setup(self):
session = Session()
self.betamax = Betamax(session)
self.cs = ContentService(url=URL, apikey=APIKEY, session=session)
示例15: TestContentService
class TestContentService():
def setup(self):
session = Session()
self.betamax = Betamax(session)
self.cs = ContentService(url=URL, apikey=APIKEY, session=session)
def test_checkassets(self):
# curl -X POST -H "Authorization: deconst ${APIKEY}" \
# http://dockerdev:9000/assets \
# -F [email protected]/fixtures/assets/foo/aaa.jpg \
# -F [email protected]/fixtures/assets/bar/bbb.gif
with self.betamax.use_cassette('checkassets'):
response = self.cs.checkassets({
'foo/aaa.jpg': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
'bar/bbb.gif': '8810ad581e59f2bc3928b261707a71308f7e139eb04820366dc4d5c18d980225',
'baz/missing.css': 'ffa63583dfa6706b87d284b86b0d693a161e4840aad2c5cf6b5d27c3b9621f7d'
})
assert_equal(response, {
'foo/aaa.jpg': '/__local_asset__/aaa-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.jpg',
'bar/bbb.gif': None,
'baz/missing.css': None
})
def test_bulkasset(self):
with self.betamax.use_cassette('bulkasset'):
tarball = io.BytesIO()
tf = tarfile.open(fileobj=tarball, mode='w:gz')
add_tar_entry(tf, 'bar/bbb.gif')
add_tar_entry(tf, 'foo/aaa.jpg')
tf.close()
response = self.cs.bulkasset(tarball.getvalue())
assert_equal(response, {
'bar/bbb.gif': '/__local_asset__/bbb-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.gif',
'foo/aaa.jpg': '/__local_asset__/aaa-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855.jpg'
})
def test_checkcontent(self):
# curl -X PUT -H "Authorization: deconst ${APIKEY}" \
# -H 'Content-Type: application/json' \
# http://dockerdev:9000/content/https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Fone \
# -d '{"title":"one","body":"one"}'
# echo -n '{"body":"one","title":"one"}' | shasum -a 256
# curl -X PUT -H "Authorization: deconst ${APIKEY}" \
# -H 'Content-Type: application/json' \
# http://dockerdev:9000/content/https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Ftwo \
# -d '{"title":"two","body":"two"}'
# echo -n '{"body":"two","title":"two"}' | shasum -a 256
with self.betamax.use_cassette('checkcontent'):
response = self.cs.checkcontent({
'https://github.com/org/repo/one': '842d36ad29589a39fc4be06157c5c204a360f98981fc905c0b2a114662172bd8',
'https://github.com/org/repo/two': 'f0e62392fc00c71ba3118c91b97c6f2cbfdcd75e8053fe2d9f029ebfcf6c23fe'
})
assert_equal(response, {
'https://github.com/org/repo/one': True,
'https://github.com/org/repo/two': False
})
def test_bulkcontent(self):
with self.betamax.use_cassette('bulkcontent'):
tarball = io.BytesIO()
tf = tarfile.open(fileobj=tarball, mode='w:gz')
add_tar_entry(
tf,
'https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Fone.json',
b'{"body":"one","title":"one"}')
add_tar_entry(
tf,
'https%3A%2F%2Fgithub.com%2Forg%2Frepo%2Ftwo.json',
b'{"body":"two","title":"two"}')
tf.close()
response = self.cs.bulkcontent(tarball.getvalue())
assert_equal(response, {
'accepted': 2,
'failed': 0,
'deleted': 0
})