def vcr(request): def auth_matcher(r1, r2): return (r1.headers.get('authorization') == r2.headers.get('authorization')) def uri_with_query_matcher(r1, r2): "URI matcher that allows query params to appear in any order" p1, p2 = urlparse(r1.uri), urlparse(r2.uri) return (p1[:3] == p2[:3] and parse_qs(p1.query, True) == parse_qs(p2.query, True)) # Use `none` to use the recorded requests, and `once` to delete existing # cassettes and re-record. record_mode = request.config.option.record_mode assert record_mode in ('once', 'none') cassette_dir = os.path.join(os.path.dirname(__file__), 'cassettes') if not os.path.exists(cassette_dir): os.makedirs(cassette_dir) # https://github.com/kevin1024/vcrpy/pull/196 vcr = VCR( record_mode=request.config.option.record_mode, filter_headers=[('Authorization', '**********')], filter_post_data_parameters=[('refresh_token', '**********')], match_on=['method', 'uri_with_query', 'auth', 'body'], cassette_library_dir=cassette_dir) vcr.register_matcher('auth', auth_matcher) vcr.register_matcher('uri_with_query', uri_with_query_matcher) return vcr
def test_vcr_before_record_request_params(): base_path = 'http://httpbin.org/' def before_record_cb(request): if request.path != '/get': return request test_vcr = VCR(filter_headers=('cookie',), before_record_request=before_record_cb, ignore_hosts=('www.test.com',), ignore_localhost=True, filter_query_parameters=('foo',)) with test_vcr.use_cassette('test') as cassette: assert cassette.filter_request(Request('GET', base_path + 'get', '', {})) is None assert cassette.filter_request(Request('GET', base_path + 'get2', '', {})) is not None assert cassette.filter_request(Request('GET', base_path + '?foo=bar', '', {})).query == [] assert cassette.filter_request( Request('GET', base_path + '?foo=bar', '', {'cookie': 'test', 'other': 'fun'})).headers == {'other': 'fun'} assert cassette.filter_request(Request('GET', base_path + '?foo=bar', '', {'cookie': 'test', 'other': 'fun'})).headers == {'other': 'fun'} assert cassette.filter_request(Request('GET', 'http://www.test.com' + '?foo=bar', '', {'cookie': 'test', 'other': 'fun'})) is None with test_vcr.use_cassette('test', before_record_request=None) as cassette: # Test that before_record can be overwritten with assert cassette.filter_request(Request('GET', base_path + 'get', '', {})) is not None
def test_custom_patchers(): class Test(object): attribute = None attribute2 = None test_vcr = VCR(custom_patches=((Test, 'attribute', VCRHTTPSConnection),)) with test_vcr.use_cassette('custom_patches'): assert issubclass(Test.attribute, VCRHTTPSConnection) assert VCRHTTPSConnection is not Test.attribute with test_vcr.use_cassette('custom_patches', custom_patches=((Test, 'attribute2', VCRHTTPSConnection),)): assert issubclass(Test.attribute, VCRHTTPSConnection) assert VCRHTTPSConnection is not Test.attribute assert Test.attribute is Test.attribute2
def test_before_record_response_as_filter(): request = Request('GET', '/', '', {}) response = object() # just can't be None # Prevent actually saving the cassette with mock.patch('vcr.cassette.FilesystemPersister.save_cassette'): filter_all = mock.Mock(return_value=None) vcr = VCR(before_record_response=filter_all) with vcr.use_cassette('test') as cassette: cassette.append(request, response) assert cassette.data == [] assert not cassette.dirty
def test_ensure_suffix(): vcr = VCR(inject_cassette=True, path_transformer=VCR.ensure_suffix('.yaml')) @vcr.use_cassette def function_name(cassette): assert cassette._path == os.path.join(os.path.dirname(__file__), 'function_name.yaml') function_name()
def vcr(vcr): def scrub_request(request): for header in ("Authorization", "Set-Cookie", "Cookie"): if header in request.headers: del request.headers[header] return request def scrub_response(response): for header in ("Authorization", "Set-Cookie", "Cookie", "Date", "Expires", "Transfer-Encoding"): if header in response["headers"]: del response["headers"][header] return response def range_header_matcher(r1, r2): return r1.headers.get('Range', '') == r2.headers.get('Range', '') vcr.cassette_library_dir = CASSETTE_DIR vcr.path_transformer = VCR.ensure_suffix('.yaml') vcr.filter_headers = ['Set-Cookie'] vcr.before_record_request = scrub_request vcr.before_record_response = scrub_response vcr.decode_compressed_response = True vcr.register_serializer('custom', BinaryContentSerializer(CASSETTE_DIR)) vcr.serializer = 'custom' vcr.register_matcher('range_header', range_header_matcher) vcr.match_on = ['uri', 'method', 'body', 'range_header'] return vcr
def test_vcr_before_record_request_params(): base_path = 'http://httpbin.org/' def before_record_cb(request): if request.path != '/get': return request test_vcr = VCR(filter_headers=('cookie', ('bert', 'ernie')), before_record_request=before_record_cb, ignore_hosts=('www.test.com',), ignore_localhost=True, filter_query_parameters=('foo', ('tom', 'jerry')), filter_post_data_parameters=('posted', ('no', 'trespassing'))) with test_vcr.use_cassette('test') as cassette: # Test explicit before_record_cb request_get = Request('GET', base_path + 'get', '', {}) assert cassette.filter_request(request_get) is None request = Request('GET', base_path + 'get2', '', {}) assert cassette.filter_request(request) is not None # Test filter_query_parameters request = Request('GET', base_path + '?foo=bar', '', {}) assert cassette.filter_request(request).query == [] request = Request('GET', base_path + '?tom=nobody', '', {}) assert cassette.filter_request(request).query == [('tom', 'jerry')] # Test filter_headers request = Request('GET', base_path + '?foo=bar', '', {'cookie': 'test', 'other': 'fun', 'bert': 'nobody'}) assert (cassette.filter_request(request).headers == {'other': 'fun', 'bert': 'ernie'}) # Test ignore_hosts request = Request('GET', 'http://www.test.com' + '?foo=bar', '', {'cookie': 'test', 'other': 'fun'}) assert cassette.filter_request(request) is None # Test ignore_localhost request = Request('GET', 'http://localhost:8000' + '?foo=bar', '', {'cookie': 'test', 'other': 'fun'}) assert cassette.filter_request(request) is None with test_vcr.use_cassette('test', before_record_request=None) as cassette: # Test that before_record can be overwritten in context manager. assert cassette.filter_request(request_get) is not None
def test_with_current_defaults(): vcr = VCR(inject_cassette=True, record_mode='once') @vcr.use_cassette('test', with_current_defaults=False) def changing_defaults(cassette, checks): checks(cassette) @vcr.use_cassette('test', with_current_defaults=True) def current_defaults(cassette, checks): checks(cassette) def assert_record_mode_once(cassette): assert cassette.record_mode == 'once' def assert_record_mode_all(cassette): assert cassette.record_mode == 'all' changing_defaults(assert_record_mode_once) current_defaults(assert_record_mode_once) vcr.record_mode = 'all' changing_defaults(assert_record_mode_all) current_defaults(assert_record_mode_once)
def __init__(self, max_pages=5): self.headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Host': 'zhixing.court.gov.cn', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' } self.j_captcha = '0000' # 验证码 self.s = None # session self.total_pages = 1 self.case_ids = set() self.detail_info = [] self.vcr = VCR() self.MAX_PAGES = max_pages
def test_with_current_defaults(): vcr = VCR(inject_cassette=True, record_mode="once") @vcr.use_cassette("test", with_current_defaults=False) def changing_defaults(cassette, checks): checks(cassette) @vcr.use_cassette("test", with_current_defaults=True) def current_defaults(cassette, checks): checks(cassette) def assert_record_mode_once(cassette): assert cassette.record_mode == "once" def assert_record_mode_all(cassette): assert cassette.record_mode == "all" changing_defaults(assert_record_mode_once) current_defaults(assert_record_mode_once) vcr.record_mode = "all" changing_defaults(assert_record_mode_all) current_defaults(assert_record_mode_once)
def test_vcr_before_record_request_params(): base_path = "http://httpbin.org/" def before_record_cb(request): if request.path != "/get": return request test_vcr = VCR( filter_headers=("cookie",), before_record_request=before_record_cb, ignore_hosts=("www.test.com",), ignore_localhost=True, filter_query_parameters=("foo",), ) with test_vcr.use_cassette("test") as cassette: assert cassette.filter_request(Request("GET", base_path + "get", "", {})) is None assert cassette.filter_request(Request("GET", base_path + "get2", "", {})) is not None assert cassette.filter_request(Request("GET", base_path + "?foo=bar", "", {})).query == [] assert cassette.filter_request( Request("GET", base_path + "?foo=bar", "", {"cookie": "test", "other": "fun"}) ).headers == {"other": "fun"} assert cassette.filter_request( Request("GET", base_path + "?foo=bar", "", {"cookie": "test", "other": "fun"}) ).headers == {"other": "fun"} assert ( cassette.filter_request( Request("GET", "http://www.test.com" + "?foo=bar", "", {"cookie": "test", "other": "fun"}) ) is None ) with test_vcr.use_cassette("test", before_record_request=None) as cassette: # Test that before_record can be overwritten with assert cassette.filter_request(Request("GET", base_path + "get", "", {})) is not None
def test_vcr_before_record_response_iterable(): # Regression test for #191 request = Request('GET', '/', '', {}) response = object() # just can't be None # Prevent actually saving the cassette with mock.patch('vcr.cassette.save_cassette'): # Baseline: non-iterable before_record_response should work mock_filter = mock.Mock() vcr = VCR(before_record_response=mock_filter) with vcr.use_cassette('test') as cassette: assert mock_filter.call_count == 0 cassette.append(request, response) assert mock_filter.call_count == 1 # Regression test: iterable before_record_response should work too mock_filter = mock.Mock() vcr = VCR(before_record_response=(mock_filter,)) with vcr.use_cassette('test') as cassette: assert mock_filter.call_count == 0 cassette.append(request, response) assert mock_filter.call_count == 1
def test_vcr_path_transformer(): # Regression test for #199 # Prevent actually saving the cassette with mock.patch('vcr.cassette.save_cassette'): # Baseline: path should be unchanged vcr = VCR() with vcr.use_cassette('test') as cassette: assert cassette._path == 'test' # Regression test: path_transformer=None should do the same. vcr = VCR(path_transformer=None) with vcr.use_cassette('test') as cassette: assert cassette._path == 'test' # and it should still work with cassette_library_dir vcr = VCR(cassette_library_dir='/foo') with vcr.use_cassette('test') as cassette: assert cassette._path == '/foo/test'
import flexget.logger from flexget.manager import Manager from flexget.plugin import load_plugins from flexget.task import Task, TaskAbort from flexget.webserver import User from flexget.manager import Session from flexget.api import app log = logging.getLogger('tests') VCR_CASSETTE_DIR = os.path.join(os.path.dirname(__file__), 'cassettes') VCR_RECORD_MODE = os.environ.get('VCR_RECORD_MODE', 'once') vcr = VCR(cassette_library_dir=VCR_CASSETTE_DIR, record_mode=VCR_RECORD_MODE, custom_patches=( (backport_client, 'HTTPSConnection', VCRHTTPSConnection), (backport_client, 'HTTPConnection', VCRHTTPConnection), )) # --- These are the public fixtures tests can ask for --- @pytest.fixture(scope='class') def config(request): """ If used inside a test class, uses the `config` class attribute of the class. This is used by `manager` fixture, and can be parametrized. """ return request.cls.config
from regonapi.exceptions import RegonAPIError from regonapi.api import RegonAPI from tests.utils import ( check_structure_base_data, check_structure_address, check_structure_pkd, check_structure_contact, check_structure_report_f1, check_structure_report_f2, check_structure_report_f3, check_structure_report_p, check_structure_report_lp, ) vcr = VCR( path_transformer=VCR.ensure_suffix(".yaml"), cassette_library_dir=os.path.join("tests", "cassettes"), ) @pytest.fixture def api(): return RegonAPI(api_key=None) def test_required_lookup(api): with pytest.raises( AttributeError, match=r"At least one parameter \(nip, regon, krs\) is required."): api.find_by()
import mock from nose.plugins.attrib import attr from vcr import VCR import flexget.logger from flexget.manager import Manager from flexget.plugin import load_plugins from flexget.task import Task, TaskAbort from tests import util log = logging.getLogger('tests') VCR_CASSETTE_DIR = os.path.join(os.path.dirname(__file__), 'cassettes') VCR_RECORD_MODE = os.environ.get('VCR_RECORD_MODE', 'once') vcr = VCR(cassette_library_dir=VCR_CASSETTE_DIR, record_mode=VCR_RECORD_MODE) test_arguments = None plugins_loaded = False def setup_logging_level(): # set logging level according to nosetests verbosity; # overrides the default level in tests/logging.cfg level = logging.DEBUG if "--verbose" in sys.argv or "-v" in sys.argv: level = flexget.logger.TRACE elif "--quiet" in sys.argv or "-q" in sys.argv: level = logging.INFO logging.getLogger().setLevel(level) return level
# -*- coding: utf-8 -*- import bot_mock from pyfibot.modules import module_urltitle from utils import check_re import pytest from vcr import VCR my_vcr = VCR( path_transformer=VCR.ensure_suffix(".yaml"), cassette_library_dir="tests/cassettes/", record_mode=pytest.config.getoption("--vcrmode"), ) @pytest.fixture def botmock(): bot = bot_mock.BotMock() module_urltitle.init(bot) return bot length_str_regex = u"\d+(h|m|s)(\d+(m))?(\d+s)?" views_str_regex = u"\d+(\.\d+)?(k|M|Billion|Trillion)?" age_str_regex = u"(FRESH|(\d+(\.\d+)?(y|d) (ago|from now)))" @my_vcr.use_cassette def test_areena_radio(botmock):
import mock import odoo from contextlib import contextmanager from os.path import dirname, join from odoo import models from odoo.addons.component.tests.common import SavepointComponentCase from vcr import VCR logging.getLogger("vcr").setLevel(logging.WARNING) recorder = VCR( record_mode='once', cassette_library_dir=join(dirname(__file__), 'fixtures/cassettes'), path_transformer=VCR.ensure_suffix('.yaml'), filter_headers=['Authorization'], decode_compressed_response=True, ) class MockResponseImage(object): def __init__(self, resp_data, code=200, msg='OK'): self.resp_data = resp_data self.code = code self.msg = msg self.headers = {'content-type': 'image/jpeg'} def read(self): # pylint: disable=W8106 return self.resp_data
from unittest import TestCase from click.testing import CliRunner from vcr import VCR from pycep import cli vcr_ = VCR(cassette_library_dir='tests/cassetts', path_transformer=VCR.ensure_suffix('.yaml'), record_mode='once') class TestCli(TestCase): def setUp(self): self.runner = CliRunner() @vcr_.use_cassette def test_cep(self): result = self.runner.invoke(cli.cep, '07713045') self.assertEqual(result.exit_code, 0) @vcr_.use_cassette def test_get_by_name(self): result = self.runner.invoke(cli.name, ['sp', 'osasco', 'sabirigui']) self.assertEqual(result.exit_code, 0)
# -*- coding: utf-8 -*- import os from babelfish import Language import pytest from vcr import VCR from subliminal.providers.podnapisi import PodnapisiProvider, PodnapisiSubtitle vcr = VCR(path_transformer=lambda path: path + '.yaml', record_mode=os.environ.get('VCR_RECORD_MODE', 'once'), cassette_library_dir=os.path.realpath(os.path.join('tests', 'cassettes', 'podnapisi'))) def test_get_matches_movie(movies): subtitle_releases = [ 'Man.Of.Steel.2013.720p.BRRip.x264.AAC-ViSiON', 'Man.Of.Steel.2013.720p.BluRay.x264-Felony', 'Man.Of.Steel.2013.1080p.BluRay.x264-SECTOR7', 'Man.Of.Steel.2013.720p.BRRip.x264.AC3-UNDERCOVER', 'Man.Of.Steel.2013.BDRip.XviD.MP3-RARBG', 'Man.Of.Steel.(2013).BDRip.600MB.Ganool', 'Man.of.Steel.2013.BDRip.x264.700MB-Micromkv', 'Man.Of.Steel.2013.BRRip.AAC.x264-SSDD', 'Man.Of.Steel.2013.BDRip.x264-Larceny', 'Man.Of.Steel.2013.BDRiP.XViD-NoGRP', 'Man.Of.Steel.2013.720p.BRRip.x264.AC3-EVO', 'Man.of.Steel.2013.720p.BRRip.h264.AAC-RARBG', 'Man.Of.Steel.[2013].BRRip.XviD-ETRG', 'Man.of.Steel.[2013].BRRip.XViD.[AC3]-ETRG', 'Man.Of.Steel.2013.BRRiP.XVID.AC3-MAJESTIC', 'Man.of.steel.2013.BRRip.XviD.AC3-RARBG', 'Man.Of.Steel.2013.720p.BRRip.x264.AC3-SUPERM4N', 'Man.Of.Steel.2013.720p.BRRip.XviD.AC3-ViSiON', 'Man.Of.Steel.2013.720p.BRRip.x264.AC3-JYK', 'Man.of.Steel.[2013].DVDRIP.DIVX.[Eng]-DUQA', 'Man.of.Steel.2013.1080p.BluRay.x264.YIFY' ] subtitle = PodnapisiSubtitle(Language('eng'), True, None, 'EMgo', subtitle_releases, 'Man of Steel', None, None, 2013)
from freezegun import freeze_time from vcr import VCR from scan.models import PeerMonitor from scan.peers import ( explore_peer, get_country_by_ip, get_ip_by_domain, get_nodes_list, get_state, is_good_version, ) my_vcr = VCR( cassette_library_dir="scan/tests/fixtures/vcr/peers", record_mode="once", decode_compressed_response=True, ) class PeersChartsViewTests(TestCase): fixtures = ["peers"] def test_slash_redirect(self): response = self.client.get("/peers-charts") self.assertEqual(response.status_code, 301) def test_ok(self): response = self.client.get("/peers-charts/") self.assertEqual(response.status_code, 200) self.assertContains(
def serialize(cassette_dict): for i in cassette_dict['interactions']: # Remove request headers i['request']['headers'] = {} # Filter some unimportant response headers response_headers = i['response']['headers'] response_headers.pop('connection', None) response_headers.pop('date', None) response_headers.pop('server', None) filter_x_headers(response_headers) return yamlserializer.serialize(cassette_dict) @staticmethod def deserialize(cassette_str): return yamlserializer.deserialize(cassette_str) vcr = VCR( cassette_library_dir=FIXTURES_ROOT, record_mode='once', # for reference: new_episodes match_on=['url', 'method'], ) vcr.register_serializer('custom', CustomSerializer) def use_cassette(name): return vcr.use_cassette( '{}.yml'.format(name), serializer='custom', )
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from babelfish import Language import pytest from vcr import VCR from subliminal.providers.podnapisi import PodnapisiProvider, PodnapisiSubtitle vcr = VCR(path_transformer=lambda path: path + '.yaml', cassette_library_dir=os.path.join('tests', 'cassettes', 'podnapisi')) def test_get_matches_movie(movies): subtitle_releases = [ 'Man.Of.Steel.2013.720p.BRRip.x264.AAC-ViSiON', 'Man.Of.Steel.2013.720p.BluRay.x264-Felony', 'Man.Of.Steel.2013.1080p.BluRay.x264-SECTOR7', 'Man.Of.Steel.2013.720p.BRRip.x264.AC3-UNDERCOVER', 'Man.Of.Steel.2013.BDRip.XviD.MP3-RARBG', 'Man.Of.Steel.(2013).BDRip.600MB.Ganool', 'Man.of.Steel.2013.BDRip.x264.700MB-Micromkv', 'Man.Of.Steel.2013.BRRip.AAC.x264-SSDD', 'Man.Of.Steel.2013.BDRip.x264-Larceny', 'Man.Of.Steel.2013.BDRiP.XViD-NoGRP', 'Man.Of.Steel.2013.720p.BRRip.x264.AC3-EVO', 'Man.of.Steel.2013.720p.BRRip.h264.AAC-RARBG', 'Man.Of.Steel.[2013].BRRip.XviD-ETRG', 'Man.of.Steel.[2013].BRRip.XViD.[AC3]-ETRG', 'Man.Of.Steel.2013.BRRiP.XVID.AC3-MAJESTIC',
def vcr(): return VCR(cassette_library_dir=os.path.join(os.path.dirname(__file__), "cassettes"))
def serialize(cassette_dict): for i in cassette_dict['interactions']: # Remove request headers i['request']['headers'] = {} # Filter some unimportant response headers response_headers = i['response']['headers'] response_headers.pop('connection', None) response_headers.pop('date', None) response_headers.pop('server', None) filter_x_headers(response_headers) return yamlserializer.serialize(cassette_dict) @staticmethod def deserialize(cassette_str): return yamlserializer.deserialize(cassette_str) vcr = VCR( cassette_library_dir=FIXTURES_ROOT, record_mode='once', match_on=['url', 'method'], ) vcr.register_serializer('custom', CustomSerializer) def use_cassette(name): return vcr.use_cassette( '{}.yml'.format(name), serializer='custom', )
from datetime import datetime from decimal import Decimal from vcr import VCR from app.exchanges.base import ECurrency, Pair, PairData from app.exchanges.exceptions import PairNotExistsException from app.exchanges.openexchangerates import OpenExchangeRatesExchange from suite.test.testcases import SimpleTestCase from suite.test.utils import override_settings my_vcr = VCR( cassette_library_dir="app/exchanges/tests/fixtures/vcr/openexchangerates", record_mode="once", decode_compressed_response=True, filter_query_parameters=["app_id"], ) @override_settings(OPENEXCHANGERATES_TOKEN="FAKE-TOKEN") class OpenExchangeRatesTest(SimpleTestCase): def test_name(self): self.assertEqual(OpenExchangeRatesExchange.name, "OpenExchangeRates") @my_vcr.use_cassette("query_200.yaml") def test_list_currencies(self): currencies = OpenExchangeRatesExchange().list_currencies self.assertEqual(len(currencies), 172) self.assertTrue(ECurrency(code="EUR") in currencies) self.assertTrue(ECurrency(code="USD") in currencies)
from vcr import VCR def before_record_callback(request): """Replace confidential information in the recorded cassettes. - customer:key are replaced with 'X:Y' """ payload = json.loads(request.body) payload['SignRequest']['OptionalInputs']['ClaimedIdentity']['Name'] = 'X:Y' request.body = json.dumps(payload) return request my_vcr = VCR(serializer='json', record_mode='once', cassette_library_dir=join(dirname(__file__), 'cassettes'), path_transformer=VCR.ensure_suffix('.json'), before_record=before_record_callback) def fixture_path(filename): """Build the full path of a fixture file.""" return join(dirname(__file__), 'fixtures', filename) class BaseCase(unittest.TestCase): pass
from datetime import datetime import pytest from vcr import VCR import autosubliminal from autosubliminal import version from autosubliminal.core.item import WantedItem from autosubliminal.util.common import get_today, run_cmd, connect_url, wait_for_internet_connection, to_obj, to_text, \ to_list, to_obj_or_list, to_dict, get_boolean, safe_text, safe_lowercase, safe_uppercase, safe_trim, sanitize, \ display_mapping_dict, display_list_single_line, display_list_multi_line, display_value, display_item_title, \ display_item_name, display_interval, display_timestamp, convert_timestamp, humanize_bytes, get_common_path, \ get_root_path, get_file_size, set_rw_and_remove, atoi, natural_keys, get_wanted_languages vcr = VCR(path_transformer=VCR.ensure_suffix('.yaml'), record_mode='once', match_on=['method', 'scheme', 'host', 'port', 'path', 'query', 'body'], cassette_library_dir=os.path.join(os.path.abspath(os.path.dirname(__file__)), 'cassettes', 'common')) text_value = 'test' text_value_upper = 'TEST' text_value_special_char = u'ù' text_value_special_char_upper = u'Ù' num_value = 1 long_value = 1.0 bool_value = True list_value = [] list_value_with_items = ['a', 'b'] list_value_with_items_upper = ['A', 'B'] dict_value = {} dict_value_with_items = {'1': 'a'} dict_value_with_items_upper = {'1': 'A'}
from datetime import datetime from decimal import Decimal from freezegun import freeze_time from vcr import VCR from app.exchanges.base import ECurrency, Pair, PairData from app.exchanges.exceptions import PairNotExistsException from app.exchanges.satang import SatangExchange from suite.test.testcases import SimpleTestCase my_vcr = VCR( cassette_library_dir="app/exchanges/tests/fixtures/vcr/satang", record_mode="once", decode_compressed_response=True, ) class SatangExchangeTest(SimpleTestCase): def test_name(self): self.assertEqual( SatangExchange.name, "[satang.pro](https://satang.pro/signup?referral=STZ3EEU2)", ) @my_vcr.use_cassette("query_200.yaml") def test_list_currencies(self): currencies = SatangExchange().list_currencies self.assertEqual(len(currencies), 12) self.assertTrue(ECurrency(code="BTC") in currencies) self.assertTrue(ECurrency(code="THB") in currencies)
session.server_url = 'http://example.com' return session @pytest.fixture() def session_fixture(): options = copy.deepcopy(Yagocd.DEFAULT_OPTIONS) options['server'] = 'http://local.docker:8153/' return Session( auth=('admin', '12345'), options=options ) my_vcr_object = VCR( path_transformer=VCR.ensure_suffix('.yaml'), cassette_library_dir=os.path.join(tests_dir(), 'fixtures/cassettes'), ) @pytest.fixture() def my_vcr(): return my_vcr_object CONTAINER_NAME = 'yagocd-server' CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) def pytest_addoption(parser): parser.addoption(
try: pass except ImportError: pass def generator(f, suffix=None): filename = "{}.{}".format(f.__self__.__class__.__name__, f.__name__) if suffix: filename = "{}.{}".format(suffix, filename) return os.path.join(os.path.dirname(inspect.getfile(f)), "cassettes", filename) my_vcr = VCR( func_path_generator=generator, decode_compressed_response=True, serializer="yaml", path_transformer=VCR.ensure_suffix(".yaml"), ) class ParserTestCaseMixin(TestCase): @my_vcr.use_cassette() def test_return_valid_signaturerow(self): for parser_key in get_parser_keys(): court = CourtFactory(parser_key=parser_key) with my_vcr.use_cassette( generator(f=self.test_return_valid_signaturerow, suffix=parser_key) ): for i, session_row in enumerate(court.get_parser().get_session_rows()): msg = "Failed for {} in {}.".format(i, parser_key) self.assertTrue(
# Remove request headers i['request']['headers'] = {} # Filter some unimportant response headers response_headers = i['response']['headers'] response_headers.pop('connection', None) response_headers.pop('date', None) response_headers.pop('server', None) filter_x_headers(response_headers) return yaml.dump(cassette_dict, default_flow_style=None, Dumper=yaml.Dumper) @staticmethod def deserialize(cassette_str): return yaml.load(cassette_str, Loader=yaml.Loader) vcr = VCR( cassette_library_dir=FIXTURES_ROOT, record_mode=os.environ.get('VCR', 'once'), match_on=['method', 'scheme', 'host', 'path', 'query'], ) vcr.register_serializer('custom', CustomSerializer) def use_cassette(name): return vcr.use_cassette( '{}.yml'.format(name), serializer='custom', )
import json from urllib.parse import quote_plus import arrow as arrow import pytest from vcr import VCR import app # configure http recorder my_vcr = VCR(cassette_library_dir='tests/cassettes', record_mode='once', serializer='json', match_on=['method', 'scheme', 'host', 'port', 'path', 'query'], path_transformer=VCR.ensure_suffix('.json'), decode_compressed_response=True, filter_query_parameters=[('apikey', 'XXXXXXX'), ('ts', '2019-05-0501:01:01'), ('hash', 'deadbeef')]) _COMICS_ATTRIBUTES = ['id', 'title', 'on_sale', 'series_id', 'images'] _SERIES_ATTRIBUTES = ['title', 'series_id', 'thumb'] def _structure_matches(attrs, list_of_dicts): return all(key in obj for key in attrs for obj in list_of_dicts) @pytest.fixture def client(): app.app.config['TESTING'] = True
from webviewcamera import Camera, exceptions from webviewcamera.parameters import ZOOM import pytest from vcr import VCR from six import BytesIO from PIL import Image URL = 'http://10.109.2.134' vcr = VCR(cassette_library_dir='tests/fixtures/cassettes') @pytest.fixture def camera(): return Camera(URL) def test_camera_url(camera): assert camera.url('info.cgi') == URL + '/-wvhttp-01-/info.cgi' @vcr.use_cassette() def test_info(camera): info = camera.info() assert isinstance(info['realtime'], float) assert 1000000000 < info['realtime'] < 5000000000 assert isinstance(info['v.list'], list) assert 'jpg:320x240:3:30000' in info['v.list'] assert info[ZOOM] == info['c.1.zoom'] @vcr.use_cassette()
def get_path_transformer(config): if "serializer" in config: suffix = ".{}".format(config["serializer"]) else: suffix = ".yaml" return VCR.ensure_suffix(suffix)
# Copyright 2015-2019 Camptocamp # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from os.path import dirname, join from vcr import VCR from odoo.tests import common recorder = VCR( record_mode='once', cassette_library_dir=join(dirname(__file__), 'fixtures/cassettes'), path_transformer=VCR.ensure_suffix('.yaml'), filter_headers=['Authorization'], filter_post_data_parameters=['client_id', 'client_secret'], # ignore scheme, host, port match_on=('method', 'path', 'query'), # allow to read and edit content in cassettes decode_compressed_response=True, ) AUTH_URL = "https://wedecint.post.ch/WEDECOAuth/token" GENERATE_LABEL_URL = "https://wedecint.post.ch/api/barcode/v1/generateAddressLabel" CLIENT_ID = "XXX" CLIENT_SECRET = "XXX" LICENSE = "XXX" class TestPostlogistics(common.SavepointCase): @classmethod def setUpClass(cls): super().setUpClass()
- customer:key are replaced with 'X:Y' """ body = request.body if helpers.PY3: body = request.body.decode('utf-8') payload = json.loads(body) payload['SignRequest']['OptionalInputs']['ClaimedIdentity']['Name'] = 'X:Y' request.body = json.dumps(payload) return request my_vcr = VCR( serializer='json', record_mode='once', cassette_library_dir=join(dirname(__file__), 'cassettes'), path_transformer=VCR.ensure_suffix('.json'), before_record=before_record_callback ) if helpers.PY3: my_vcr.register_serializer('json', JSONSerializer) def fixture_path(filename): """Build the full path of a fixture file.""" return join(dirname(__file__), 'fixtures', filename) class BaseCase(unittest.TestCase): pass
# -*- coding: utf-8 -*- import os from babelfish import Language, language_converters import pytest from vcr import VCR from subliminal.exceptions import AuthenticationError, ConfigurationError from subliminal.providers.addic7ed import Addic7edProvider, Addic7edSubtitle vcr = VCR( path_transformer=lambda path: path + '.yaml', record_mode=os.environ.get('VCR_RECORD_MODE', 'once'), match_on=['method', 'scheme', 'host', 'port', 'path', 'query', 'body'], cassette_library_dir=os.path.join('tests', 'cassettes', 'addic7ed')) @pytest.mark.converter def test_converter_convert_alpha3_country_script(): assert language_converters['addic7ed'].convert( 'srp', None, 'Cyrl') == 'Serbian (Cyrillic)' @pytest.mark.converter def test_converter_convert_alpha3_country(): assert language_converters['addic7ed'].convert( 'por', 'BR') == 'Portuguese (Brazilian)' @pytest.mark.converter def test_converter_convert_alpha3():
"""Defines all test wide settings and variables""" from os import environ from domaintools import API from vcr import VCR def remove_server(response): response.get('headers', {}).pop('server', None) return response vcr = VCR(before_record_response=remove_server, filter_query_parameters=['api_key', 'api_username'], cassette_library_dir='tests/fixtures/vcr/', path_transformer=VCR.ensure_suffix('.yaml'), record_mode='new_episodes') with vcr.use_cassette('init_user_account'): api = API(environ.get('TEST_USER', 'test_user'), environ.get('TEST_KEY', 'test_key'))
"""Replace confidential information in the recorded cassettes. - customer:key are replaced with 'X:Y' """ payload = json.loads(request.body) payload['SignRequest']['OptionalInputs']['ClaimedIdentity']['Name'] = 'X:Y' request.body = json.dumps(payload) return request my_vcr = VCR( serializer='json', record_mode='once', cassette_library_dir=join(dirname(__file__), 'cassettes'), path_transformer=VCR.ensure_suffix('.json'), before_record=before_record_callback ) def fixture_path(filename): """Build the full path of a fixture file.""" return join(dirname(__file__), 'fixtures', filename) class TestAIS(unittest.TestCase): """Generic tests of the AIS client.""" def test_constructor(self): """The constructor builds a client instance.""" alice_instance = AIS(customer='alice', key_static='alice_secret',
import mock import tzlocal import datetime from mock import call, ANY from click.testing import CliRunner import piexif from piexif._exceptions import InvalidImageDataError from pyicloud_ipd.services.photos import PhotoAsset, PhotoAlbum from pyicloud_ipd.base import PyiCloudService from pyicloud_ipd.exceptions import PyiCloudAPIResponseError from requests.exceptions import ConnectionError from icloudpd.base import main import icloudpd.constants from tests.helpers.print_result_exception import print_result_exception vcr = VCR(decode_compressed_response=True) class DownloadPhotoTestCase(TestCase): @pytest.fixture(autouse=True) def inject_fixtures(self, caplog): self._caplog = caplog def test_download_and_skip_existing_photos(self): if os.path.exists("tests/fixtures/Photos"): shutil.rmtree("tests/fixtures/Photos") os.makedirs("tests/fixtures/Photos") os.makedirs("tests/fixtures/Photos/2018/07/30/") open("tests/fixtures/Photos/2018/07/30/IMG_7408.JPG", "a").close() open("tests/fixtures/Photos/2018/07/30/IMG_7407.JPG", "a").close()
from pathlib import Path from vcr import VCR from vcr.request import Request __all__ = ['vcr'] vcr = VCR( cassette_library_dir=(Path(__file__).parent / 'fixtures').as_posix(), )
import os import re from vcr import VCR USER_REGEX = re.compile(r'<usuario>\w+</usuario>') PASS_REGEX = re.compile(r'<senha>.*</senha>') def replace_auth(request): if not request.body: return request body = request.body.decode() body = USER_REGEX.sub(r'<usuario>teste</usuario>', body) body = PASS_REGEX.sub(r'<senha>****</senha>', body) request.body = body.encode() return request FIXTURES_DIR = os.path.join(os.path.dirname(__file__), "fixtures") vcr = VCR( record_mode='once', serializer='yaml', cassette_library_dir=os.path.join(FIXTURES_DIR, 'cassettes'), path_transformer=VCR.ensure_suffix('.yaml'), match_on=['method'], before_record_request=replace_auth, )
import logging import aiohttp import unittest import aiounittest from vcr import VCR from hypotonic import Hypotonic logger = logging.getLogger('hypotonic') logger.setLevel(logging.INFO) logger.addHandler(logging.StreamHandler()) vcr = VCR(cassette_library_dir='./tests/cassettes') class TestHypotonic(aiounittest.AsyncTestCase): def setUp(self): # TODO The test suite currently has a lot of resource warning. Those should # be removed. Until then, this enhances the readability of the test output. import warnings warnings.simplefilter("ignore", ResourceWarning) def test_synchronous_run(self): data, errors = (Hypotonic('http://books.toscrape.com/').find( '.nav-list ul a').set('category').data()) self.assertFalse(errors) self.assertEqual(50, len(data)) async def test_get_unreachable_url(self): data, errors = await (
from unittest import TestCase from vcr import VCR from burst.api.brs.v1 import BrsApi from burst.api.brs.v1.queries import QueryBase from burst.api.exceptions import APIException, ClientException my_vcr = VCR( cassette_library_dir="burst/api/brs/v1/tests/fixtures/vcr", record_mode="once", decode_compressed_response=True, ) class TestQuery(QueryBase): _request_type = "Test" _http_method = "GET" class BrsApiTest(TestCase): def test_node_url_ok(self): self.assertEqual( BrsApi("http://127.0.0.1:80").node_url, "http://127.0.0.1:80") self.assertEqual( BrsApi("127.0.0.1:80").node_url, "http://127.0.0.1:80") def test_node_url_fail(self): with self.assertRaises(ClientException) as em: BrsApi("")
from django.test import TestCase from django.test.client import RequestFactory from django.test.utils import override_settings from paypal.pro.exceptions import PayPalFailure from paypal.pro.fields import CreditCardField from paypal.pro.helpers import VERSION, PayPalError, PayPalWPP from paypal.pro.signals import payment_was_successful from paypal.pro.views import PayPalPro from .settings import TEMPLATE_DIRS, TEMPLATES RF = RequestFactory() REQUEST = RF.get("/pay/", REMOTE_ADDR="127.0.0.1:8000") vcr = VCR(path_transformer=VCR.ensure_suffix('.yaml')) class DummyPayPalWPP(PayPalWPP): pass # """Dummy class for testing PayPalWPP.""" # responses = { # # @@@ Need some reals data here. # "DoDirectPayment": """ack=Success×tamp=2009-03-12T23%3A52%3A33Z&l_severitycode0=Error&l_shortmessage0=Security+error&l_longmessage0=Security+header+is+not+valid&version=54.0&build=854529&l_errorcode0=&correlationid=""", # noqa # } # # def _request(self, data): # return self.responses["DoDirectPayment"]
def my_vcr(gocd_docker): return VCR( path_transformer=VCR.ensure_suffix('.yaml'), cassette_library_dir=os.path.join(root_cassette_library_dir, gocd_docker), )
@staticmethod def serialize(cassette_dict): cassette_dict["recorded_at"] = datetime.now().isoformat()[:-7] return ( f"{json.dumps(serialize_dict(cassette_dict), sort_keys=True, indent=2)}\n" ) @staticmethod def deserialize(cassette_string): return json.loads(cassette_string) vcr = VCR( before_record_response=filter_access_token, cassette_library_dir="tests/integration/cassettes", match_on=["uri", "method"], path_transformer=VCR.ensure_suffix(".json"), serializer="custom_serializer", ) vcr.register_serializer("custom_serializer", CustomSerializer) vcr.register_persister(CustomPersister) def after_init(func, *args): func(*args) def add_init_hook(original_init): """Wrap an __init__ method to also call some hooks.""" @wraps(original_init)
try: from unittest.mock import Mock except ImportError: from mock import Mock from vcr import VCR from subliminal import (ProviderPool, check_video, download_best_subtitles, download_subtitles, list_subtitles, provider_manager, save_subtitles) from subliminal.providers.addic7ed import Addic7edSubtitle from subliminal.providers.thesubdb import TheSubDBSubtitle from subliminal.providers.tvsubtitles import TVsubtitlesSubtitle from subliminal.subtitle import Subtitle vcr = VCR( path_transformer=lambda path: path + '.yaml', match_on=['method', 'scheme', 'host', 'port', 'path', 'query', 'body'], cassette_library_dir=os.path.join('tests', 'cassettes', 'api')) @pytest.fixture def mock_providers(monkeypatch): for provider in provider_manager: monkeypatch.setattr(provider.plugin, 'initialize', Mock()) monkeypatch.setattr(provider.plugin, 'list_subtitles', Mock(return_value=[provider.name])) monkeypatch.setattr(provider.plugin, 'download_subtitle', Mock()) monkeypatch.setattr(provider.plugin, 'terminate', Mock()) def test_provider_pool_del_keyerror(): pool = ProviderPool()
class Fayuan(object): def __str__(self): return 'Fayuan Zhixing Enging.' def __init__(self, max_pages=5): self.headers = {'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Host': 'zhixing.court.gov.cn', 'Upgrade-Insecure-Requests': '1', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36' } self.j_captcha = '0000' # 验证码 self.s = None # session self.total_pages = 1 self.case_ids = set() self.detail_info = [] self.vcr = VCR() self.MAX_PAGES = max_pages def get_code(self): code_url = "http://zhixing.court.gov.cn/search/security/jcaptcha.jpg?" + str(random.randint(1, 99)) code_response = self.s.get(code_url) # 获取验证码图片和cookies (必须) with open('code.jpg', 'wb') as f: f.write(code_response.content) # self.j_captcha = raw_input("Input Code: ") self.j_captcha = self.vcr.recognize(os.path.join(os.getcwd(), 'code.jpg')) def get_page(self, name, page=1): self.get_code() # 获取验证码 data = {'searchCourtName': u'全国法院(包含地方各级法院)', 'selectCourtId': 1, 'selectCourtArrange': 1, 'pname': name, 'cardNum': '', 'currentPage': page, 'j_captcha': self.j_captcha } self.s.headers.update({'Origin': 'http://zhixing.court.gov.cn', 'Referer': 'http://zhixing.court.gov.cn/search/', 'Upgrade-Insecure-Requests': '1'}) response = self.s.post('http://zhixing.court.gov.cn/search/newsearch', data=data) tried = 0 while u"验证码出现错误,请重新输入" in response.text: # 验证码出错 tried += 1 if tried >= 3: # try 3 times return False self.get_code() # 获取验证码 data['j_captcha'] = self.j_captcha response = self.s.post('http://zhixing.court.gov.cn/search/newsearch', data=data) self.total_pages = int(re.search(u' .+页 \d+/(.+) 共.+', response.text).group(1)) soup = BeautifulSoup(response.text, 'lxml') rows = soup.find('tbody').find_all('tr')[1:] for row in rows: case_id = row.find_all('td')[4].find('a')['id'] self.case_ids.add(case_id) return True def get_basic_info(self, name): self.get_page(name, 1) if self.total_pages > 1: for i in range(2, min(self.total_pages+1, self.MAX_PAGES+1)): self.get_page(name, i) def get_detail(self): for case_id in self.case_ids: self.get_code() # 获取验证码 detail_url = "http://zhixing.court.gov.cn/search/newdetail?id=" + str(case_id) + "&j_captcha=" + str(self.j_captcha) detail_response = self.s.get(detail_url) tried = 0 while detail_response.text == '{}': # 验证码出错 tried += 1 if tried >= 3: # try 3 times return False self.get_code() # 获取验证码 detail_url = "http://zhixing.court.gov.cn/search/newdetail?id=" + str(case_id) + "&j_captcha=" + str(self.j_captcha) detail_response = self.s.get(detail_url) self.detail_info.append(json.loads(detail_response.text)) return True def search(self, name='英孚'): # 初始化 self.s = requests.Session() self.total_pages = 1 self.case_ids = set() self.detail_info = [] # 开始查询 self.s.get("http://zhixing.court.gov.cn/search/", headers=self.headers) # 第一次访问(必需) # s.get("http://zhixing.court.gov.cn/search/explain.html?v=20130408", headers=headers) # 获取下方文字(非查询必须) self.get_basic_info(name) self.get_detail() return self.detail_info
def test_vcr_use_cassette(): record_mode = mock.Mock() test_vcr = VCR(record_mode=record_mode) with mock.patch( 'vcr.cassette.Cassette.load', return_value=mock.MagicMock(inject=False) ) as mock_cassette_load: @test_vcr.use_cassette('test') def function(): pass assert mock_cassette_load.call_count == 0 function() assert mock_cassette_load.call_args[1]['record_mode'] is record_mode # Make sure that calls to function now use cassettes with the # new filter_header_settings test_vcr.record_mode = mock.Mock() function() assert mock_cassette_load.call_args[1]['record_mode'] == test_vcr.record_mode # Ensure that explicitly provided arguments still supercede # those on the vcr. new_record_mode = mock.Mock() with test_vcr.use_cassette('test', record_mode=new_record_mode) as cassette: assert cassette.record_mode == new_record_mode