mirror of
https://github.com/kevin1024/vcrpy.git
synced 2025-12-09 01:03:24 +00:00
Enable rule B (flake8-bugbear) on ruff
This commit is contained in:
@@ -14,6 +14,7 @@ markers = [
|
|||||||
|
|
||||||
[tool.ruff]
|
[tool.ruff]
|
||||||
select = [
|
select = [
|
||||||
|
"B", # flake8-bugbear
|
||||||
"C4", # flake8-comprehensions
|
"C4", # flake8-comprehensions
|
||||||
"COM", # flake8-commas
|
"COM", # flake8-commas
|
||||||
"E", # pycodestyle error
|
"E", # pycodestyle error
|
||||||
|
|||||||
@@ -13,8 +13,10 @@ def assert_cassette_has_one_response(cass):
|
|||||||
|
|
||||||
def assert_is_json_bytes(b: bytes):
|
def assert_is_json_bytes(b: bytes):
|
||||||
assert isinstance(b, bytes)
|
assert isinstance(b, bytes)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
json.loads(b.decode("utf-8"))
|
json.loads(b.decode("utf-8"))
|
||||||
except Exception:
|
except Exception as error:
|
||||||
assert False
|
raise AssertionError() from error
|
||||||
|
|
||||||
assert True
|
assert True
|
||||||
|
|||||||
@@ -397,7 +397,8 @@ def test_cookies_redirect(httpbin_both, httpbin_ssl_context, tmpdir):
|
|||||||
cookies = session.cookie_jar.filter_cookies(cookies_url)
|
cookies = session.cookie_jar.filter_cookies(cookies_url)
|
||||||
assert cookies["Cookie_1"].value == "Val_1"
|
assert cookies["Cookie_1"].value == "Val_1"
|
||||||
assert cassette.play_count == 0
|
assert cassette.play_count == 0
|
||||||
cassette.requests[1].headers["Cookie"] == "Cookie_1=Val_1"
|
|
||||||
|
assert cassette.requests[1].headers["Cookie"] == "Cookie_1=Val_1"
|
||||||
|
|
||||||
# -------------------------- Play --------------------------- #
|
# -------------------------- Play --------------------------- #
|
||||||
with vcr.use_cassette(tmp, record_mode=vcr.mode.NONE) as cassette:
|
with vcr.use_cassette(tmp, record_mode=vcr.mode.NONE) as cassette:
|
||||||
@@ -407,7 +408,8 @@ def test_cookies_redirect(httpbin_both, httpbin_ssl_context, tmpdir):
|
|||||||
cookies = session.cookie_jar.filter_cookies(cookies_url)
|
cookies = session.cookie_jar.filter_cookies(cookies_url)
|
||||||
assert cookies["Cookie_1"].value == "Val_1"
|
assert cookies["Cookie_1"].value == "Val_1"
|
||||||
assert cassette.play_count == 2
|
assert cassette.play_count == 2
|
||||||
cassette.requests[1].headers["Cookie"] == "Cookie_1=Val_1"
|
|
||||||
|
assert cassette.requests[1].headers["Cookie"] == "Cookie_1=Val_1"
|
||||||
|
|
||||||
# Assert that it's ignoring expiration date
|
# Assert that it's ignoring expiration date
|
||||||
with vcr.use_cassette(tmp, record_mode=vcr.mode.NONE) as cassette:
|
with vcr.use_cassette(tmp, record_mode=vcr.mode.NONE) as cassette:
|
||||||
|
|||||||
@@ -66,8 +66,8 @@ class DoAsyncRequest(BaseDoRequest):
|
|||||||
def client(self):
|
def client(self):
|
||||||
try:
|
try:
|
||||||
return self._client
|
return self._client
|
||||||
except AttributeError:
|
except AttributeError as e:
|
||||||
raise ValueError('To access async client, use "with do_request() as client"')
|
raise ValueError('To access async client, use "with do_request() as client"') from e
|
||||||
|
|
||||||
def __call__(self, *args, **kwargs):
|
def __call__(self, *args, **kwargs):
|
||||||
if hasattr(self, "_loop"):
|
if hasattr(self, "_loop"):
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from urllib.request import urlopen
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import vcr
|
import vcr
|
||||||
|
from vcr.errors import CannotOverwriteExistingCassetteException
|
||||||
|
|
||||||
|
|
||||||
def test_making_extra_request_raises_exception(tmpdir, httpbin):
|
def test_making_extra_request_raises_exception(tmpdir, httpbin):
|
||||||
@@ -18,5 +19,5 @@ def test_making_extra_request_raises_exception(tmpdir, httpbin):
|
|||||||
with vcr.use_cassette(str(tmpdir.join("test.json")), match_on=["method"]):
|
with vcr.use_cassette(str(tmpdir.join("test.json")), match_on=["method"]):
|
||||||
assert urlopen(httpbin.url + "/status/200").getcode() == 200
|
assert urlopen(httpbin.url + "/status/200").getcode() == 200
|
||||||
assert urlopen(httpbin.url + "/status/201").getcode() == 201
|
assert urlopen(httpbin.url + "/status/201").getcode() == 201
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(CannotOverwriteExistingCassetteException):
|
||||||
urlopen(httpbin.url + "/status/200")
|
urlopen(httpbin.url + "/status/200")
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ from urllib.request import urlopen
|
|||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
import vcr
|
import vcr
|
||||||
|
from vcr.errors import CannotOverwriteExistingCassetteException
|
||||||
|
|
||||||
|
|
||||||
def test_once_record_mode(tmpdir, httpbin):
|
def test_once_record_mode(tmpdir, httpbin):
|
||||||
@@ -18,7 +19,7 @@ def test_once_record_mode(tmpdir, httpbin):
|
|||||||
# the first time, it's played from the cassette.
|
# the first time, it's played from the cassette.
|
||||||
# but, try to access something else from the same cassette, and an
|
# but, try to access something else from the same cassette, and an
|
||||||
# exception is raised.
|
# exception is raised.
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(CannotOverwriteExistingCassetteException):
|
||||||
urlopen(httpbin.url + "/get").read()
|
urlopen(httpbin.url + "/get").read()
|
||||||
|
|
||||||
|
|
||||||
@@ -94,7 +95,7 @@ def test_new_episodes_record_mode_two_times(tmpdir, httpbin):
|
|||||||
assert urlopen(url).read() == original_second_response
|
assert urlopen(url).read() == original_second_response
|
||||||
# now that we are back in once mode, this should raise
|
# now that we are back in once mode, this should raise
|
||||||
# an error.
|
# an error.
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(CannotOverwriteExistingCassetteException):
|
||||||
urlopen(url).read()
|
urlopen(url).read()
|
||||||
|
|
||||||
|
|
||||||
@@ -124,7 +125,7 @@ def test_none_record_mode(tmpdir, httpbin):
|
|||||||
# raise hell.
|
# raise hell.
|
||||||
testfile = str(tmpdir.join("recordmode.yml"))
|
testfile = str(tmpdir.join("recordmode.yml"))
|
||||||
with vcr.use_cassette(testfile, record_mode=vcr.mode.NONE):
|
with vcr.use_cassette(testfile, record_mode=vcr.mode.NONE):
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(CannotOverwriteExistingCassetteException):
|
||||||
urlopen(httpbin.url).read()
|
urlopen(httpbin.url).read()
|
||||||
|
|
||||||
|
|
||||||
@@ -140,5 +141,5 @@ def test_none_record_mode_with_existing_cassette(tmpdir, httpbin):
|
|||||||
urlopen(httpbin.url).read()
|
urlopen(httpbin.url).read()
|
||||||
assert cass.play_count == 1
|
assert cass.play_count == 1
|
||||||
# but if I try to hit the net, raise an exception.
|
# but if I try to hit the net, raise an exception.
|
||||||
with pytest.raises(Exception):
|
with pytest.raises(CannotOverwriteExistingCassetteException):
|
||||||
urlopen(httpbin.url + "/get").read()
|
urlopen(httpbin.url + "/get").read()
|
||||||
|
|||||||
@@ -220,7 +220,7 @@ def test_unsupported_features_raises_in_future(get_client, tmpdir):
|
|||||||
supported is raised inside the future."""
|
supported is raised inside the future."""
|
||||||
|
|
||||||
def callback(chunk):
|
def callback(chunk):
|
||||||
assert False, "Did not expect to be called."
|
raise AssertionError("Did not expect to be called.")
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join("invalid.yaml"))):
|
with vcr.use_cassette(str(tmpdir.join("invalid.yaml"))):
|
||||||
future = get(get_client(), "http://httpbin.org", streaming_callback=callback)
|
future = get(get_client(), "http://httpbin.org", streaming_callback=callback)
|
||||||
@@ -238,7 +238,7 @@ def test_unsupported_features_raise_error_disabled(get_client, tmpdir):
|
|||||||
supported is not raised if raise_error=False."""
|
supported is not raised if raise_error=False."""
|
||||||
|
|
||||||
def callback(chunk):
|
def callback(chunk):
|
||||||
assert False, "Did not expect to be called."
|
raise AssertionError("Did not expect to be called.")
|
||||||
|
|
||||||
with vcr.use_cassette(str(tmpdir.join("invalid.yaml"))):
|
with vcr.use_cassette(str(tmpdir.join("invalid.yaml"))):
|
||||||
response = yield get(
|
response = yield get(
|
||||||
|
|||||||
@@ -113,7 +113,7 @@ def make_get_request():
|
|||||||
@mock.patch("vcr.stubs.VCRHTTPResponse")
|
@mock.patch("vcr.stubs.VCRHTTPResponse")
|
||||||
def test_function_decorated_with_use_cassette_can_be_invoked_multiple_times(*args):
|
def test_function_decorated_with_use_cassette_can_be_invoked_multiple_times(*args):
|
||||||
decorated_function = Cassette.use(path="test")(make_get_request)
|
decorated_function = Cassette.use(path="test")(make_get_request)
|
||||||
for i in range(4):
|
for _ in range(4):
|
||||||
decorated_function()
|
decorated_function()
|
||||||
|
|
||||||
|
|
||||||
@@ -159,7 +159,7 @@ def test_cassette_allow_playback_repeats():
|
|||||||
a = Cassette("test", allow_playback_repeats=True)
|
a = Cassette("test", allow_playback_repeats=True)
|
||||||
a.append("foo", "bar")
|
a.append("foo", "bar")
|
||||||
a.append("other", "resp")
|
a.append("other", "resp")
|
||||||
for x in range(10):
|
for _ in range(10):
|
||||||
assert a.play_response("foo") == "bar"
|
assert a.play_response("foo") == "bar"
|
||||||
assert a.play_count == 10
|
assert a.play_count == 10
|
||||||
assert a.all_played is False
|
assert a.all_played is False
|
||||||
|
|||||||
@@ -315,7 +315,7 @@ class Cassette:
|
|||||||
"""
|
"""
|
||||||
best_matches = []
|
best_matches = []
|
||||||
request = self._before_record_request(request)
|
request = self._before_record_request(request)
|
||||||
for index, (stored_request, response) in enumerate(self.data):
|
for _, (stored_request, _) in enumerate(self.data):
|
||||||
successes, fails = get_matchers_results(request, stored_request, self._match_on)
|
successes, fails = get_matchers_results(request, stored_request, self._match_on)
|
||||||
best_matches.append((len(successes), stored_request, successes, fails))
|
best_matches.append((len(successes), stored_request, successes, fails))
|
||||||
best_matches.sort(key=lambda t: t[0], reverse=True)
|
best_matches.sort(key=lambda t: t[0], reverse=True)
|
||||||
@@ -365,7 +365,7 @@ class Cassette:
|
|||||||
|
|
||||||
def __contains__(self, request):
|
def __contains__(self, request):
|
||||||
"""Return whether or not a request has been stored"""
|
"""Return whether or not a request has been stored"""
|
||||||
for index, response in self._responses(request):
|
for index, _ in self._responses(request):
|
||||||
if self.play_counts[index] == 0 or self.allow_playback_repeats:
|
if self.play_counts[index] == 0 or self.allow_playback_repeats:
|
||||||
return True
|
return True
|
||||||
return False
|
return False
|
||||||
|
|||||||
@@ -88,7 +88,7 @@ class VCR:
|
|||||||
try:
|
try:
|
||||||
serializer = self.serializers[serializer_name]
|
serializer = self.serializers[serializer_name]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise KeyError(f"Serializer {serializer_name} doesn't exist or isn't registered")
|
raise KeyError(f"Serializer {serializer_name} doesn't exist or isn't registered") from None
|
||||||
return serializer
|
return serializer
|
||||||
|
|
||||||
def _get_matchers(self, matcher_names):
|
def _get_matchers(self, matcher_names):
|
||||||
@@ -97,7 +97,7 @@ class VCR:
|
|||||||
for m in matcher_names:
|
for m in matcher_names:
|
||||||
matchers.append(self.matchers[m])
|
matchers.append(self.matchers[m])
|
||||||
except KeyError:
|
except KeyError:
|
||||||
raise KeyError(f"Matcher {m} doesn't exist or isn't registered")
|
raise KeyError(f"Matcher {m} doesn't exist or isn't registered") from None
|
||||||
return matchers
|
return matchers
|
||||||
|
|
||||||
def use_cassette(self, path=None, **kwargs):
|
def use_cassette(self, path=None, **kwargs):
|
||||||
|
|||||||
@@ -48,6 +48,7 @@ class Request:
|
|||||||
warnings.warn(
|
warnings.warn(
|
||||||
"Request.add_header is deprecated. Please assign to request.headers instead.",
|
"Request.add_header is deprecated. Please assign to request.headers instead.",
|
||||||
DeprecationWarning,
|
DeprecationWarning,
|
||||||
|
stacklevel=2,
|
||||||
)
|
)
|
||||||
self.headers[key] = value
|
self.headers[key] = value
|
||||||
|
|
||||||
|
|||||||
@@ -17,13 +17,5 @@ def serialize(cassette_dict):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
return json.dumps(cassette_dict, indent=4) + "\n"
|
return json.dumps(cassette_dict, indent=4) + "\n"
|
||||||
except UnicodeDecodeError as original: # py2
|
except TypeError:
|
||||||
raise UnicodeDecodeError(
|
raise TypeError(error_message) from None
|
||||||
original.encoding,
|
|
||||||
b"Error serializing cassette to JSON",
|
|
||||||
original.start,
|
|
||||||
original.end,
|
|
||||||
original.args[-1] + error_message,
|
|
||||||
)
|
|
||||||
except TypeError: # py3
|
|
||||||
raise TypeError(error_message)
|
|
||||||
|
|||||||
Reference in New Issue
Block a user