def test_auth_failed(get_client, tmpdir, scheme): '''Ensure that we can save failed auth statuses''' auth = ('user', 'wrongwrongwrong') url = scheme + '://httpbin.org/basic-auth/user/passwd' with vcr.use_cassette(str(tmpdir.join('auth-failed.yaml'))) as cass: # Ensure that this is empty to begin with assert_cassette_empty(cass) with pytest.raises(http.HTTPError) as exc_info: yield get( get_client(), url, auth_username=auth[0], auth_password=auth[1], ) one = exc_info.value.response assert exc_info.value.code == 401 with vcr.use_cassette(str(tmpdir.join('auth-failed.yaml'))) as cass: with pytest.raises(http.HTTPError) as exc_info: two = yield get( get_client(), url, auth_username=auth[0], auth_password=auth[1], ) two = exc_info.value.response assert exc_info.value.code == 401 assert one.body == two.body assert one.code == two.code == 401 assert 1 == cass.play_count
def test_flickr_multipart_upload(httpbin, tmpdir): """ The python-flickr-api project does a multipart upload that confuses vcrpy """ def _pretend_to_be_flickr_library(): content_type, body = "text/plain", "HELLO WORLD" h = httplib.HTTPConnection(httpbin.host, httpbin.port) headers = { "Content-Type": content_type, "content-length": str(len(body)) } h.request("POST", "/post/", headers=headers) h.send(body) r = h.getresponse() data = r.read() h.close() return data testfile = str(tmpdir.join('flickr.yml')) with vcr.use_cassette(testfile) as cass: _pretend_to_be_flickr_library() assert len(cass) == 1 with vcr.use_cassette(testfile) as cass: assert len(cass) == 1 _pretend_to_be_flickr_library() assert cass.play_count == 1
def test_flickr_multipart_upload(): """ The python-flickr-api project does a multipart upload that confuses vcrpy """ def _pretend_to_be_flickr_library(): content_type, body = "text/plain", "HELLO WORLD" h = httplib.HTTPConnection("httpbin.org") headers = { "Content-Type": content_type, "content-length": str(len(body)) } h.request("POST", "/post/", headers=headers) h.send(body) r = h.getresponse() data = r.read() h.close() with vcr.use_cassette('fixtures/vcr_cassettes/flickr.json') as cass: _pretend_to_be_flickr_library() assert len(cass) == 1 with vcr.use_cassette('fixtures/vcr_cassettes/flickr.json') as cass: assert len(cass) == 1 _pretend_to_be_flickr_library() assert cass.play_count == 1
def test_new_episodes_record_mode(tmpdir): testfile = str(tmpdir.join('recordmode.yml')) with vcr.use_cassette(testfile, record_mode="new_episodes"): # cassette file doesn't exist, so create. response = urlopen('http://httpbin.org/').read() with vcr.use_cassette(testfile, record_mode="new_episodes") as cass: # make the same request again response = urlopen('http://httpbin.org/').read() # all responses have been played assert cass.all_played # in the "new_episodes" record mode, we can add more requests to # a cassette without repurcussions. response = urlopen('http://httpbin.org/get').read() # one of the responses has been played assert cass.play_count == 1 # not all responses have been played assert not cass.all_played with vcr.use_cassette(testfile, record_mode="new_episodes") as cass: # the cassette should now have 2 responses assert len(cass.responses) == 2
def test_stops_in_area(self): legion = StopPoint.objects.get(pk='5820AWN26274') self.assertEqual(self.stop_area, legion.stop_area) with catch_warnings(record=True) as caught_warnings: import_stops_in_area.Command().handle_row({ 'StopAreaCode': 'poo', 'AtcoCode': 'poo' }) self.assertEqual(1, len(caught_warnings)) with vcr.use_cassette(os.path.join(FIXTURES_DIR, '5820AWN26361.yaml')): self.assertContains(self.client.get('/stops/5820AWN26361'), 'Port Talbot Circular') with vcr.use_cassette(os.path.join(FIXTURES_DIR, '5820AWN26274.yaml')): res = self.client.get('/stops/5820AWN26274') self.assertContains(res, 'On Talbot Road, near Eagle Street, near Port Talbot British Legion') self.assertContains(res, 'Services') self.assertContains(res, '44 - Port Talbot Circular') self.assertContains(res, """ <div class="aside box"> <h2>Nearby stops</h2> <ul class="has-smalls"> <li itemscope itemtype="https://schema.org/BusStop" data-indicator="NE-bound" data-heading="45"> <a href="/stops/5820AWN26438"> <span itemprop="name">Ty'n y Twr Club (NE-bound)</span> </a> <span itemprop="geo" itemscope itemtype="https://schema.org/GeoCoordinates"> <meta itemprop="latitude" content="51.6171316877" /> <meta itemprop="longitude" content="-3.8000765776" /> </span> </li> </ul> </div> """, html=True)
def test_original_response_is_not_modified_by_before_filter(tmpdir, httpbin): testfile = str(tmpdir.join('sensitive_data_scrubbed_response.yml')) host, port = httpbin.host, httpbin.port field_to_scrub = 'url' replacement = '[YOU_CANT_HAVE_THE_MANGO]' conn = httplib.HTTPConnection(host, port) conn.request('GET', '/get') outside = conn.getresponse() callback = _make_before_record_response([field_to_scrub], replacement) with vcr.use_cassette(testfile, before_record_response=callback): conn = httplib.HTTPConnection(host, port) conn.request('GET', '/get') inside = conn.getresponse() # The scrubbed field should be the same, because no cassette existed. # Furthermore, the responses should be identical. inside_body = json.loads(inside.read().decode('utf-8')) outside_body = json.loads(outside.read().decode('utf-8')) assert not inside_body[field_to_scrub] == replacement assert inside_body[field_to_scrub] == outside_body[field_to_scrub] # Ensure that when a cassette exists, the scrubbed response is returned. with vcr.use_cassette(testfile, before_record_response=callback): conn = httplib.HTTPConnection(host, port) conn.request('GET', '/get') inside = conn.getresponse() inside_body = json.loads(inside.read().decode('utf-8')) assert inside_body[field_to_scrub] == replacement
def test_original_decoded_response_is_not_modified(tmpdir, httpbin): testfile = str(tmpdir.join('decoded_response.yml')) host, port = httpbin.host, httpbin.port conn = httplib.HTTPConnection(host, port) conn.request('GET', '/gzip') outside = conn.getresponse() with vcr.use_cassette(testfile, decode_compressed_response=True): conn = httplib.HTTPConnection(host, port) conn.request('GET', '/gzip') inside = conn.getresponse() # Assert that we do not modify the original response while appending # to the casssette. assert 'gzip' == inside.headers['content-encoding'] # They should effectively be the same response. inside_headers = (h for h in inside.headers.items() if h[0] != 'Date') outside_headers = (h for h in outside.getheaders() if h[0] != 'Date') assert set(inside_headers) == set(outside_headers) assert inside.read() == outside.read() # Even though the above are raw bytes, the JSON data should have been # decoded and saved to the cassette. with vcr.use_cassette(testfile): conn = httplib.HTTPConnection(host, port) conn.request('GET', '/gzip') inside = conn.getresponse() assert 'content-encoding' not in inside.headers assert_is_json(inside.read())
def test_body(tmpdir, scheme): '''Ensure the responses are all identical enough''' url = scheme + '://httpbin.org/bytes/1024' with vcr.use_cassette(str(tmpdir.join('body.yaml'))) as cass: content = requests.get(url).content with vcr.use_cassette(str(tmpdir.join('body.yaml'))) as cass: assert content == requests.get(url).content
def test_body(tmpdir, scheme, verify_pool_mgr): '''Ensure the responses are all identical enough''' url = scheme + '://httpbin.org/bytes/1024' with vcr.use_cassette(str(tmpdir.join('body.yaml'))): content = verify_pool_mgr.request('GET', url).data with vcr.use_cassette(str(tmpdir.join('body.yaml'))): assert content == verify_pool_mgr.request('GET', url).data
def test_headers(scheme, tmpdir, verify_pool_mgr): '''Ensure that we can read the headers back''' url = scheme + '://httpbin.org/' with vcr.use_cassette(str(tmpdir.join('headers.yaml'))): headers = verify_pool_mgr.request('GET', url).headers with vcr.use_cassette(str(tmpdir.join('headers.yaml'))): assert headers == verify_pool_mgr.request('GET', url).headers
def test_status_code(scheme, tmpdir, verify_pool_mgr): '''Ensure that we can read the status code''' url = scheme + '://httpbin.org/' with vcr.use_cassette(str(tmpdir.join('atts.yaml'))): status_code = verify_pool_mgr.request('GET', url).status with vcr.use_cassette(str(tmpdir.join('atts.yaml'))): assert status_code == verify_pool_mgr.request('GET', url).status
def test_status_code(scheme, tmpdir): '''Ensure that we can read the status code''' url = scheme + '://httpbin.org/' with vcr.use_cassette(str(tmpdir.join('atts.yaml'))): status_code = requests.get(url).status_code with vcr.use_cassette(str(tmpdir.join('atts.yaml'))): assert status_code == requests.get(url).status_code
def test_filter_post_data(tmpdir): url = "http://httpbin.org/post" data = urlencode({"id": "secret", "foo": "bar"}).encode("utf-8") cass_file = str(tmpdir.join("filter_pd.yaml")) with vcr.use_cassette(cass_file, filter_post_data_parameters=["id"]): urlopen(url, data) with vcr.use_cassette(cass_file, filter_post_data_parameters=["id"]) as cass: assert b"id=secret" not in cass.requests[0].body
def test_filter_querystring(tmpdir): url = 'http://httpbin.org/?foo=bar' cass_file = str(tmpdir.join('filter_qs.yaml')) with vcr.use_cassette(cass_file, filter_query_parameters=['foo']): urlopen(url) with vcr.use_cassette(cass_file, filter_query_parameters=['foo']) as cass: urlopen(url) assert 'foo' not in cass.requests[0].url
def test_random_body(scheme, tmpdir): '''Ensure we can read the content, and that it's served from cache''' url = scheme + '://httpbin.org/bytes/1024' with vcr.use_cassette(str(tmpdir.join('body.yaml'))) as cass: body = urllib2.urlopen(url).read() with vcr.use_cassette(str(tmpdir.join('body.yaml'))) as cass: assert body == urllib2.urlopen(url).read()
def test_response_code(scheme, tmpdir): '''Ensure we can read a response code from a fetch''' url = scheme + '://httpbin.org/' with vcr.use_cassette(str(tmpdir.join('atts.yaml'))) as cass: code = urllib2.urlopen(url).getcode() with vcr.use_cassette(str(tmpdir.join('atts.yaml'))) as cass: assert code == urllib2.urlopen(url).getcode()
def test_response_code(httpbin_both, tmpdir): '''Ensure we can read a response code from a fetch''' url = httpbin_both.url with vcr.use_cassette(str(tmpdir.join('atts.yaml'))): code = urlopen_with_cafile(url).getcode() with vcr.use_cassette(str(tmpdir.join('atts.yaml'))): assert code == urlopen_with_cafile(url).getcode()
def test_random_body(httpbin_both, tmpdir): '''Ensure we can read the content, and that it's served from cache''' url = httpbin_both.url + '/bytes/1024' with vcr.use_cassette(str(tmpdir.join('body.yaml'))): body = urlopen_with_cafile(url).read() with vcr.use_cassette(str(tmpdir.join('body.yaml'))): assert body == urlopen_with_cafile(url).read()
def test_filter_querystring(tmpdir): url = "http://httpbin.org/?foo=bar" cass_file = str(tmpdir.join("filter_qs.yaml")) with vcr.use_cassette(cass_file, filter_query_parameters=["foo"]): urlopen(url) with vcr.use_cassette(cass_file, filter_query_parameters=["foo"]) as cass: urlopen(url) assert "foo" not in cass.requests[0].url
def test_headers(scheme, tmpdir): '''Ensure that we can read the headers back''' url = scheme + '://httpbin.org/' with vcr.use_cassette(str(tmpdir.join('headers.yaml'))): headers = requests.get(url).headers with vcr.use_cassette(str(tmpdir.join('headers.yaml'))): assert headers == requests.get(url).headers
def test_filter_post_data(tmpdir): url = 'http://httpbin.org/post' data = urlencode({'id': 'secret', 'foo': 'bar'}).encode('utf-8') cass_file = str(tmpdir.join('filter_pd.yaml')) with vcr.use_cassette(cass_file, filter_post_data_parameters=['id']): urlopen(url, data) with vcr.use_cassette(cass_file, filter_post_data_parameters=['id']) as cass: assert b'id=secret' not in cass.requests[0].body
def test_headers(tmpdir, httpbin_both, verify_pool_mgr): '''Ensure that we can read the headers back''' url = httpbin_both.url with vcr.use_cassette(str(tmpdir.join('headers.yaml'))): headers = verify_pool_mgr.request('GET', url).headers with vcr.use_cassette(str(tmpdir.join('headers.yaml'))): assert headers == verify_pool_mgr.request('GET', url).headers
def test_status_code(httpbin_both, tmpdir): '''Ensure that we can read the status code''' url = httpbin_both.url + '/' with vcr.use_cassette(str(tmpdir.join('atts.yaml'))): status_code = requests.get(url).status_code with vcr.use_cassette(str(tmpdir.join('atts.yaml'))): assert status_code == requests.get(url).status_code
def test_body(tmpdir, httpbin_both): '''Ensure the responses are all identical enough''' url = httpbin_both + '/bytes/1024' with vcr.use_cassette(str(tmpdir.join('body.yaml'))): content = requests.get(url).content with vcr.use_cassette(str(tmpdir.join('body.yaml'))): assert content == requests.get(url).content
def test_headers(httpbin_both, tmpdir): '''Ensure that we can read the headers back''' url = httpbin_both + '/' with vcr.use_cassette(str(tmpdir.join('headers.yaml'))): headers = requests.get(url).headers with vcr.use_cassette(str(tmpdir.join('headers.yaml'))): assert headers == requests.get(url).headers
def test_effective_url(tmpdir, httpbin_both): '''Ensure that the effective_url is captured''' url = httpbin_both.url + '/redirect-to?url=/html' with vcr.use_cassette(str(tmpdir.join('url.yaml'))): effective_url = requests.get(url).url assert effective_url == httpbin_both.url + '/html' with vcr.use_cassette(str(tmpdir.join('url.yaml'))): assert effective_url == requests.get(url).url
def test_json(tmpdir, scheme): url = scheme + '://httpbin.org/get' with vcr.use_cassette(str(tmpdir.join('json.yaml'))): _, response_json = get(url, as_text=False) with vcr.use_cassette(str(tmpdir.join('json.yaml'))) as cassette: _, cassette_response_json = get(url, as_text=False) assert cassette_response_json == response_json assert cassette.play_count == 1
def test_text(tmpdir, scheme): url = scheme + '://httpbin.org' with vcr.use_cassette(str(tmpdir.join('text.yaml'))): _, response_text = get(url) with vcr.use_cassette(str(tmpdir.join('text.yaml'))) as cassette: _, cassette_response_text = get(url) assert cassette_response_text == response_text assert cassette.play_count == 1
def test_response_headers(scheme, tmpdir): '''Ensure we can get information from the response''' url = scheme + '://httpbin.org/' with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass: open1 = urllib2.urlopen(url).info().items() with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cass: open2 = urllib2.urlopen(url).info().items() assert open1 == open2
def test_headers(tmpdir, scheme): url = scheme + '://httpbin.org' with vcr.use_cassette(str(tmpdir.join('headers.yaml'))): response, _ = get(url) with vcr.use_cassette(str(tmpdir.join('headers.yaml'))) as cassette: cassette_response, _ = get(url) assert cassette_response.headers == response.headers assert cassette.play_count == 1
def test_filename_from_disposition(tmpdir): p = tmpdir.mkdir('directory') download = Download(url='https://www.eventideaudio.com/downloader/1165', path=p.strpath) with vcr.use_cassette( os.path.join(FIXTURE_PATH, 'download', 'eventide.yaml')): assert download.process() == ActionResponse( changed=True, data={ 'path': os.path.join(p.strpath, '2016-Stereo-Room-3.1.3-osx-installer.dmg') })
def test_patched_content_json(tmpdir, httpbin): """ Ensure that what you pull from a json cassette is what came from the request """ testfile = str(tmpdir.join("synopsis.json")) with vcr.use_cassette(testfile) as cass: response = urlopen(httpbin.url).read() assert cass.play_count == 0 with vcr.use_cassette(testfile) as cass: response2 = urlopen(httpbin.url).read() assert cass.play_count == 1 cass._save(force=True) with vcr.use_cassette(testfile) as cass: response3 = urlopen(httpbin.url).read() assert cass.play_count == 1 assert response == response2 assert response2 == response3
def test_nested_cassettes_with_session_created_before_nesting(scheme, tmpdir): ''' This tests ensures that a session that was created while one cassette was active is patched to the use the responses of a second cassette when it is enabled. ''' url = scheme + '://httpbin.org/bytes/1024' with vcr.use_cassette(str(tmpdir.join('first_nested.yaml'))): session = requests.session() first_body = session.get(url).content with vcr.use_cassette(str(tmpdir.join('second_nested.yaml'))): second_body = session.get(url).content third_body = requests.get(url).content with vcr.use_cassette(str(tmpdir.join('second_nested.yaml'))): session = requests.session() assert session.get(url).content == second_body with vcr.use_cassette(str(tmpdir.join('first_nested.yaml'))): assert session.get(url).content == first_body assert session.get(url).content == third_body # Make sure that the session can now get content normally. session.get('http://www.reddit.com')
def test_multiple_requests(scheme, tmpdir): '''Ensure that we can cache multiple requests''' urls = [ scheme + '://httpbin.org/', scheme + '://httpbin.org/get', scheme + '://httpbin.org/bytes/1024' ] with vcr.use_cassette(str(tmpdir.join('multiple.yaml'))) as cass: for index in range(len(urls)): url = urls[index] assert len(cass) == index assert cass.play_count == index assert urllib2.urlopen(url).read() == urllib2.urlopen(url).read() assert len(cass) == index + 1 assert cass.play_count == index + 1
def test_new_episodes_record_mode_two_times(tmpdir, httpbin): testfile = str(tmpdir.join("recordmode.yml")) url = httpbin.url + "/bytes/1024" with vcr.use_cassette(testfile, record_mode="new_episodes"): # cassette file doesn't exist, so create. original_first_response = urlopen(url).read() with vcr.use_cassette(testfile, record_mode="new_episodes"): # make the same request again assert urlopen(url).read() == original_first_response # in the "new_episodes" record mode, we can add the same request # to the cassette without repercussions original_second_response = urlopen(url).read() with vcr.use_cassette(testfile, record_mode="once"): # make the same request again assert urlopen(url).read() == original_first_response assert urlopen(url).read() == original_second_response # now that we are back in once mode, this should raise # an error. with pytest.raises(Exception): urlopen(url).read()
def test_patched_content_json(tmpdir): ''' Ensure that what you pull from a json cassette is what came from the request ''' testfile = str(tmpdir.join('synopsis.json')) with vcr.use_cassette(testfile) as cass: response = urlopen('http://httpbin.org/').read() assert cass.play_count == 0 with vcr.use_cassette(testfile) as cass: response2 = urlopen('http://httpbin.org/').read() assert cass.play_count == 1 cass._save(force=True) with vcr.use_cassette(testfile) as cass: response3 = urlopen('http://httpbin.org/').read() assert cass.play_count == 1 assert response == response2 assert response2 == response3
def test_aiohttp_test_client(aiohttp_client, tmpdir): loop = asyncio.get_event_loop() app = aiohttp_app() url = '/' client = loop.run_until_complete(aiohttp_client(app)) with vcr.use_cassette(str(tmpdir.join('get.yaml'))): response = loop.run_until_complete(client.get(url)) assert response.status == 200 response_text = loop.run_until_complete(response.text()) assert response_text == 'hello' response_text = loop.run_until_complete(response.text(errors='replace')) assert response_text == 'hello' with vcr.use_cassette(str(tmpdir.join('get.yaml'))) as cassette: response = loop.run_until_complete(client.get(url)) request = cassette.requests[0] assert request.url == str(client.make_url(url)) response_text = loop.run_until_complete(response.text()) assert response_text == 'hello' assert cassette.play_count == 1
def test_disk_saver_write(tmpdir): ''' Ensure that when you close a cassette after changing it it does rewrite the file ''' fname = str(tmpdir.join('synopsis.yaml')) with vcr.use_cassette(fname) as cass: urllib2.urlopen('http://www.iana.org/domains/reserved').read() assert cass.play_count == 0 last_mod = os.path.getmtime(fname) # Make sure at least 1 second passes, otherwise sometimes # the mtime doesn't change time.sleep(1) with vcr.use_cassette(fname, record_mode='any') as cass: urllib2.urlopen('http://www.iana.org/domains/reserved').read() urllib2.urlopen('http://httpbin.org/').read() assert cass.play_count == 1 assert cass.dirty last_mod2 = os.path.getmtime(fname) assert last_mod != last_mod2
def test_dyfi(): eventid = "se60247871" detail = get_event_by_id(eventid, includesuperseded=True) cassettes, datadir = get_datadir() tape_file = os.path.join(cassettes, "dataframes_dyfi.yaml") with vcr.use_cassette(tape_file, record_mode="new_episodes"): df1km = get_dyfi_data_frame(detail, dyfi_file="utm_1km") np.testing.assert_almost_equal(df1km["intensity"].sum(), 14628.3) df10km = get_dyfi_data_frame(detail, dyfi_file="utm_10km") np.testing.assert_almost_equal(df10km["intensity"].sum(), 3459.0) dfutm = get_dyfi_data_frame(detail, dyfi_file="utm_var") np.testing.assert_almost_equal(dfutm["intensity"].sum(), 3459.0) dfzip = get_dyfi_data_frame(detail, dyfi_file="zip") np.testing.assert_almost_equal(dfzip["intensity"].sum(), 2296.3)
def test_get_summary_data_frame(): cassettes, datadir = get_datadir() tape_file = os.path.join(cassettes, "dataframes_summary.yaml") with vcr.use_cassette(tape_file, record_mode="new_episodes"): events = search.search( starttime=datetime(1994, 6, 1), endtime=datetime(1994, 10, 6), minmagnitude=8.0, maxmagnitude=9.0, ) df = get_summary_data_frame(events) assert len(df) == 2 assert df.iloc[0]["magnitude"] == 8.2
def request_cache(self) -> Cassette: try: os.remove(self.cache_filename) except FileNotFoundError: pass return vcr.use_cassette( self.cache_filename, record_mode="new_episodes", serializer="yaml", match_on=[ "method", "scheme", "host", "port", "path", "query", "body" ], )
def test_update_remote_access(): """Tests for update remote method""" client = CBWApi(API_URL, API_KEY, SECRET_KEY) info = { "type": "CbwRam::RemoteAccess::Ssh::WithPassword", "address": "10.10.10.228", "port": "22", "login": "******", "password": "******", "key": "", "node": "master" } with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/update_remote_access.yaml'): response = client.update_remote_access('15', info) assert isinstance(response, CBWRemoteAccess) is True info["address"] = "10.10.11.228" with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/update_remote_access_id_none.yaml' ): response = client.update_remote_access(None, info) assert isinstance(response, CBWRemoteAccess) is False info["type"] = "" with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/update_remote_access_without_type.yaml' ): response = client.update_remote_access('15', info) assert response.type == "CbwRam::RemoteAccess::Ssh::WithPassword"
def test_cookies(tmpdir, scheme, do_request): def client_cookies(client): return [c for c in client.client.cookies] def response_cookies(response): return [c for c in response.cookies] with do_request() as client: assert client_cookies(client) == [] redirect_kwargs = {HTTPX_REDIRECT_PARAM.name: True} url = scheme + "://httpbin.org" testfile = str(tmpdir.join("cookies.yml")) with vcr.use_cassette(testfile): r1 = client("GET", url + "/cookies/set?k1=v1&k2=v2", **redirect_kwargs) assert response_cookies(r1.history[0]) == ["k1", "k2"] assert response_cookies(r1) == [] r2 = client("GET", url + "/cookies", **redirect_kwargs) assert len(r2.json()["cookies"]) == 2 assert client_cookies(client) == ["k1", "k2"] with do_request() as new_client: assert client_cookies(new_client) == [] with vcr.use_cassette(testfile) as cassette: cassette_response = new_client("GET", url + "/cookies/set?k1=v1&k2=v2") assert response_cookies( cassette_response.history[0]) == ["k1", "k2"] assert response_cookies(cassette_response) == [] assert cassette.play_count == 2 assert client_cookies(new_client) == ["k1", "k2"]
def test_find_returns_card(self): with vcr.use_cassette('fixtures/choice_of_damnations.yaml'): card = Card.find(88803) self.assertEqual('Choice of Damnations', card.name) self.assertEqual('{5}{B}', card.mana_cost) self.assertEqual(6, card.cmc) self.assertEqual('Sorcery — Arcane', card.type) self.assertTrue('Black' in card.colors) self.assertEqual(['B'], card.color_identity) self.assertTrue('Sorcery' in card.types) self.assertTrue('Arcane' in card.subtypes) self.assertEqual('Rare', card.rarity) self.assertEqual('SOK', card.set) self.assertEqual('Saviors of Kamigawa', card.set_name) self.assertEqual( "Target opponent chooses a number. You may have that player lose that much life. If you don't, that player sacrifices all but that many permanents.", card.text) self.assertEqual( "\"Life is a series of choices between bad and worse.\" —Toshiro Umezawa", card.flavor) self.assertEqual('Tim Hildebrandt', card.artist) self.assertEqual('62', card.number) self.assertEqual(88803, card.multiverse_id) self.assertEqual( 'http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=88803&type=card', card.image_url) self.assertTrue(len(card.rulings) > 0) self.assertTrue({ "name": "Scelta della Dannazione", "text": "L'avversario bersaglio sceglie un numero. Puoi far perdere a quel giocatore un ammontare di punti vita pari a quel numero. Se non lo fai, quel giocatore sacrifica tutti i permanenti tranne un numero di permanenti pari al numero scelto.", "flavor": "\"La vita è una sequela di scelte tra male e peggio.\"\n—Toshiro Umezawa", "imageUrl": "http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=105393&type=card", "language": "Italian", "multiverseid": 105393 } in card.foreign_names) self.assertTrue('SOK' in card.printings) self.assertEqual( "Target opponent chooses a number. You may have that player lose that much life. If you don't, that player sacrifices all but that many permanents.", card.original_text) self.assertEqual('Sorcery - Arcane', card.original_type) self.assertTrue({ "format": "Commander", "legality": "Legal" } in card.legalities) self.assertEqual('224a2a63-7be6-5e06-bf6b-e667727bf80b', card.id)
def test_find_returns_card(self): with vcr.use_cassette('fixtures/choice_of_damnations.yaml'): card = Card.find(88803) self.assertEqual('Choice of Damnations', card.name) self.assertEqual('{5}{B}', card.mana_cost) self.assertEqual(6, card.cmc) self.assertEqual('Sorcery — Arcane', card.type) self.assertTrue('Black' in card.colors) self.assertEqual(['B'], card.color_identity) self.assertTrue('Sorcery' in card.types) self.assertTrue('Arcane' in card.subtypes) self.assertEqual('Rare', card.rarity) self.assertEqual('SOK', card.set) self.assertEqual('Saviors of Kamigawa', card.set_name) self.assertEqual( "Target opponent chooses a number. You may have that player lose that much life. If you don't, that player sacrifices all but that many permanents.", card.text) self.assertEqual( "\"Life is a series of choices between bad and worse.\"\n—Toshiro Umezawa", card.flavor) self.assertEqual('Tim Hildebrandt', card.artist) self.assertEqual('62', card.number) self.assertEqual(88803, card.multiverse_id) self.assertEqual( 'http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=88803&type=card', card.image_url) self.assertTrue(len(card.rulings) > 0) self.assertTrue({ "name": "Scelta della Dannazione", "language": "Italian", "multiverseid": 105393, "imageUrl": "http://gatherer.wizards.com/Handlers/Image.ashx?multiverseid=105393&type=card" } in card.foreign_names) self.assertTrue('SOK' in card.printings) self.assertEqual( "Target opponent chooses a number. You may have that player lose that much life. If you don't, that player sacrifices all but that many permanents.", card.original_text) self.assertEqual('Sorcery — Arcane', card.original_type) self.assertTrue({ "format": "Commander", "legality": "Legal" } in card.legalities) self.assertEqual('1c4aab072d52d283e902f2302afa255b39e0794b', card.id)
def test_unsupported_features_raise_error_disabled(get_client, tmpdir): '''Ensure that the exception for an AsyncHTTPClient feature not being supported is not raised if raise_error=False.''' def callback(chunk): assert False, "Did not expect to be called." with vcr.use_cassette(str(tmpdir.join('invalid.yaml'))): response = yield get( get_client(), 'http://httpbin.org', streaming_callback=callback, raise_error=False, ) assert "not yet supported by VCR" in str(response.error)
def test_params_same_url_distinct_params(tmpdir, scheme): url = scheme + "://httpbin.org/get" headers = {"Content-Type": "application/json"} params = {"a": 1, "b": False, "c": "c"} with vcr.use_cassette(str(tmpdir.join("get.yaml"))) as cassette: _, response_json = get(url, output="json", params=params, headers=headers) with vcr.use_cassette(str(tmpdir.join("get.yaml"))) as cassette: _, cassette_response_json = get(url, output="json", params=params, headers=headers) assert cassette_response_json == response_json assert cassette.play_count == 1 other_params = {"other": "params"} with vcr.use_cassette(str(tmpdir.join("get.yaml"))) as cassette: with pytest.raises( vcr.errors.CannotOverwriteExistingCassetteException): get(url, output="text", params=other_params)
def test_session_and_connection_close(tmpdir, scheme): ''' This tests the issue in https://github.com/kevin1024/vcrpy/issues/48 If you use a requests.session and the connection is closed, then an exception is raised in the urllib3 module vendored into requests: `AttributeError: 'NoneType' object has no attribute 'settimeout'` ''' with vcr.use_cassette(str(tmpdir.join('session_connection_closed.yaml'))): session = requests.session() resp = session.get('http://httpbin.org/get', headers={'Connection': 'close'}) resp = session.get('http://httpbin.org/get', headers={'Connection': 'close'})
def test_harvester(monkeypatch, harvester_name, *args, **kwargs): monkeypatch.setattr(requests.time, 'sleep', lambda *_, **__: None) base.settings.RAISE_IN_TRANSFORMER = True harvester = registry[harvester_name] with vcr.use_cassette('tests/vcr/{}.yaml'.format(harvester_name), match_on=['host'], record_mode='none'): harvested = harvester.harvest() assert len(harvested) > 0 normalized = filter(lambda x: x is not None, map(harvester.normalize, harvested)) assert len(normalized) > 0
def test_applicative_scans(): """Tests for method applicative_scans""" client = CBWApi(API_URL, API_KEY, SECRET_KEY) applicative_scans_validate = [ "cbw_object(id=1, node_id=1, target='fenrisl.com', server_id=1)" ] with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/applicative_scans.yaml'): params = {'page': '1'} response = client.applicative_scans(params) assert isinstance(response, list) is True assert str(response[0]) == applicative_scans_validate[0], str( response[0]) == applicative_scans_validate[0]
def test_award_badge_gives_error_when_given_bad_badge_data(self): """.award_badge() raises an wardBadgeBadDataError when given data Note that the details from the API are given to the exception for more details. """ badgr = self.get_badgr_setup() with vcr.use_cassette('tests/vcr_cassettes/award_badge_bad_data.yaml'): with self.assertRaises(exceptions.AwardBadgeBadDataError): badgr.award_badge( self.get_sample_award_badge_id(), {'bad_badge_data': 1} )
def test_update_security_issue(): """Tests for update remote method""" client = CBWApi(API_URL, API_KEY, SECRET_KEY) info = { "description": "Test update", "level": "level_critical", "score": "5", } with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/update_security_issue.yaml'): response = client.update_security_issue('2', info) assert isinstance(response, CBWSecurityIssue) is True info["level"] = "level_test" with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/update_security_issue_wrong_level.yaml' ): response = client.update_security_issue("2", info) assert isinstance(response, CBWSecurityIssue) is False
def test_create_security_issue(): """Tests for method security_issue""" client = CBWApi(API_URL, API_KEY, SECRET_KEY) info = { "description": "Test", "level": "level_critical", "score": "5", } with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/create_security_issue.yaml'): response = client.create_security_issue(info) assert isinstance(response, CBWSecurityIssue) is True
def test_handle_dca_logic_error(self, capfd): """Test execution while already DCA.""" with vcr.use_cassette( "tests/fixtures/vcr_cassettes/test_handle_dca_logic_error.yaml", filter_headers=["API-Key", "API-Sign"], ): self.dca.handle_dca_logic() captured = capfd.readouterr() test_output = ( "It's 2021-04-16 18:54:53 on Kraken, 2021-04-16 18:54:53 on " "system.\n" "Current trade balance: 16524.7595 ZUSD.\n" "Pair balances: 359.728 ZEUR, 0.128994332 XETH.\n" "No DCA for XETHZEUR: Already placed an order today.\n") assert captured.out == test_output
def test_update_security_issue(): """Tests for update remote method""" client = CBWApi(API_URL, API_KEY, SECRET_KEY) info = { "description": "Test update", "level": "level_low", "score": "6", } with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/update_security_issue.yaml'): response = client.update_security_issue('30', info) assert response.description == "Test update" info["level"] = "level_test" with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/update_security_issue_wrong_level.yaml' ): response = client.update_security_issue("30", info) assert response is None
def validator_warn(self, record_mode, validator) -> Iterable[Tuple[SqlValidator, Dict]]: with vcr.use_cassette( "tests/cassettes/test_sql_validator/fixture_validator_pass_with_warning.yaml", match_on=["uri", "method", "raw_body"], filter_headers=["Authorization"], record_mode=record_mode, ): # Move to dev mode to test conditional logic warning validator.client.update_workspace("eye_exam", "dev") validator.client.checkout_branch("eye_exam", "pytest") validator.build_project(selectors=["eye_exam/users__warn"]) results = validator.validate(mode="hybrid") yield validator, results
def request_cache() -> Cassette: """ Builds VCR instance. It deletes file everytime we create it, normally should be called only once. We can't use NamedTemporaryFile here because yaml serializer doesn't work well with empty files. """ filename = "request_cache.yml" try: os.remove(filename) except FileNotFoundError: pass return vcr.use_cassette(str(filename), record_mode="new_episodes", serializer="yaml")
def test_list_and_upload(self): """List packages from blob storage""" with vcr.use_cassette("tests/vcr_cassettes/test_list.yaml", filter_headers=["authorization"]): package = make_package("mypkg", "1.2", "pkg.tar.gz", summary="test") self.storage.upload(package, BytesIO(b"test1234")) package = list(self.storage.list(Package))[0] self.assertEqual(package.name, "mypkg") self.assertEqual(package.version, "1.2") self.assertEqual(package.filename, "pkg.tar.gz") self.assertEqual(package.summary, "test")
def test_create_remote_access(): """Tests for method remote_access""" client = CBWApi(API_URL, API_KEY, SECRET_KEY) info = { 'type': 'CbwRam::RemoteAccess::Ssh::WithPassword', 'address': 'X.X.X.X', 'port': '22', 'login': '******', 'password': '******', 'key': '', 'node_id': '1', 'server_groups': 'test, production', 'priv_password': '', 'auth_password': '', } with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/create_remote_access.yaml'): response = client.create_remote_access(info) assert response.address == 'X.X.X.X', response.server_groups == [ 'test', 'production' ] assert response.type == 'CbwRam::RemoteAccess::Ssh::WithPassword' assert response.is_valid is None info['address'] = '' with vcr.use_cassette( 'spec/fixtures/vcr_cassettes/create_remote_access_failed_without_address.yaml' ): response = client.create_remote_access(info) assert response is False
def test_unsupported_features_raises_in_future(get_client, tmpdir): """Ensure that the exception for an AsyncHTTPClient feature not being supported is raised inside the future.""" def callback(chunk): assert False, "Did not expect to be called." with vcr.use_cassette(str(tmpdir.join("invalid.yaml"))): future = get(get_client(), "http://httpbin.org", streaming_callback=callback) with pytest.raises(Exception) as excinfo: yield future assert "not yet supported by VCR" in str(excinfo)