From 4f70152e7ce510cde41cf071585cbdb481e4e8f2 Mon Sep 17 00:00:00 2001 From: Jair Henrique Date: Tue, 27 Jun 2023 09:12:40 -0300 Subject: [PATCH] Enable rule B (flake8-bugbear) on ruff --- pyproject.toml | 1 + tests/assertions.py | 6 ++++-- tests/integration/test_aiohttp.py | 6 ++++-- tests/integration/test_httpx.py | 4 ++-- tests/integration/test_multiple.py | 3 ++- tests/integration/test_record_mode.py | 9 +++++---- tests/integration/test_tornado.py | 4 ++-- tests/unit/test_cassettes.py | 4 ++-- vcr/cassette.py | 4 ++-- vcr/config.py | 4 ++-- vcr/request.py | 1 + vcr/serializers/jsonserializer.py | 12 ++---------- 12 files changed, 29 insertions(+), 29 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 9f62bca..4830452 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,7 @@ markers = [ [tool.ruff] select = [ + "B", # flake8-bugbear "C4", # flake8-comprehensions "COM", # flake8-commas "E", # pycodestyle error diff --git a/tests/assertions.py b/tests/assertions.py index 60c432b..104bd62 100644 --- a/tests/assertions.py +++ b/tests/assertions.py @@ -13,8 +13,10 @@ def assert_cassette_has_one_response(cass): def assert_is_json_bytes(b: bytes): assert isinstance(b, bytes) + try: json.loads(b.decode("utf-8")) - except Exception: - assert False + except Exception as error: + raise AssertionError() from error + assert True diff --git a/tests/integration/test_aiohttp.py b/tests/integration/test_aiohttp.py index 4b7d783..0835c34 100644 --- a/tests/integration/test_aiohttp.py +++ b/tests/integration/test_aiohttp.py @@ -397,7 +397,8 @@ def test_cookies_redirect(httpbin_both, httpbin_ssl_context, tmpdir): cookies = session.cookie_jar.filter_cookies(cookies_url) assert cookies["Cookie_1"].value == "Val_1" 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 --------------------------- # 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) assert cookies["Cookie_1"].value == "Val_1" 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 with vcr.use_cassette(tmp, record_mode=vcr.mode.NONE) as cassette: diff --git a/tests/integration/test_httpx.py b/tests/integration/test_httpx.py index 0b1bf9a..4425e02 100644 --- a/tests/integration/test_httpx.py +++ b/tests/integration/test_httpx.py @@ -66,8 +66,8 @@ class DoAsyncRequest(BaseDoRequest): def client(self): try: return self._client - except AttributeError: - raise ValueError('To access async client, use "with do_request() as client"') + except AttributeError as e: + raise ValueError('To access async client, use "with do_request() as client"') from e def __call__(self, *args, **kwargs): if hasattr(self, "_loop"): diff --git a/tests/integration/test_multiple.py b/tests/integration/test_multiple.py index 70fc418..e9ea9c6 100644 --- a/tests/integration/test_multiple.py +++ b/tests/integration/test_multiple.py @@ -3,6 +3,7 @@ from urllib.request import urlopen import pytest import vcr +from vcr.errors import CannotOverwriteExistingCassetteException 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"]): assert urlopen(httpbin.url + "/status/200").getcode() == 200 assert urlopen(httpbin.url + "/status/201").getcode() == 201 - with pytest.raises(Exception): + with pytest.raises(CannotOverwriteExistingCassetteException): urlopen(httpbin.url + "/status/200") diff --git a/tests/integration/test_record_mode.py b/tests/integration/test_record_mode.py index e12e0c6..881ccf5 100644 --- a/tests/integration/test_record_mode.py +++ b/tests/integration/test_record_mode.py @@ -3,6 +3,7 @@ from urllib.request import urlopen import pytest import vcr +from vcr.errors import CannotOverwriteExistingCassetteException 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. # but, try to access something else from the same cassette, and an # exception is raised. - with pytest.raises(Exception): + with pytest.raises(CannotOverwriteExistingCassetteException): 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 # now that we are back in once mode, this should raise # an error. - with pytest.raises(Exception): + with pytest.raises(CannotOverwriteExistingCassetteException): urlopen(url).read() @@ -124,7 +125,7 @@ def test_none_record_mode(tmpdir, httpbin): # raise hell. testfile = str(tmpdir.join("recordmode.yml")) with vcr.use_cassette(testfile, record_mode=vcr.mode.NONE): - with pytest.raises(Exception): + with pytest.raises(CannotOverwriteExistingCassetteException): urlopen(httpbin.url).read() @@ -140,5 +141,5 @@ def test_none_record_mode_with_existing_cassette(tmpdir, httpbin): urlopen(httpbin.url).read() assert cass.play_count == 1 # but if I try to hit the net, raise an exception. - with pytest.raises(Exception): + with pytest.raises(CannotOverwriteExistingCassetteException): urlopen(httpbin.url + "/get").read() diff --git a/tests/integration/test_tornado.py b/tests/integration/test_tornado.py index 4dad1cc..e5c7569 100644 --- a/tests/integration/test_tornado.py +++ b/tests/integration/test_tornado.py @@ -220,7 +220,7 @@ def test_unsupported_features_raises_in_future(get_client, tmpdir): supported is raised inside the future.""" 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"))): 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.""" 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"))): response = yield get( diff --git a/tests/unit/test_cassettes.py b/tests/unit/test_cassettes.py index 27091b6..1d58d4a 100644 --- a/tests/unit/test_cassettes.py +++ b/tests/unit/test_cassettes.py @@ -113,7 +113,7 @@ def make_get_request(): @mock.patch("vcr.stubs.VCRHTTPResponse") def test_function_decorated_with_use_cassette_can_be_invoked_multiple_times(*args): decorated_function = Cassette.use(path="test")(make_get_request) - for i in range(4): + for _ in range(4): decorated_function() @@ -159,7 +159,7 @@ def test_cassette_allow_playback_repeats(): a = Cassette("test", allow_playback_repeats=True) a.append("foo", "bar") a.append("other", "resp") - for x in range(10): + for _ in range(10): assert a.play_response("foo") == "bar" assert a.play_count == 10 assert a.all_played is False diff --git a/vcr/cassette.py b/vcr/cassette.py index 66083c6..69c5575 100644 --- a/vcr/cassette.py +++ b/vcr/cassette.py @@ -315,7 +315,7 @@ class Cassette: """ best_matches = [] 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) best_matches.append((len(successes), stored_request, successes, fails)) best_matches.sort(key=lambda t: t[0], reverse=True) @@ -365,7 +365,7 @@ class Cassette: def __contains__(self, request): """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: return True return False diff --git a/vcr/config.py b/vcr/config.py index 160f49b..3cf48f7 100644 --- a/vcr/config.py +++ b/vcr/config.py @@ -88,7 +88,7 @@ class VCR: try: serializer = self.serializers[serializer_name] 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 def _get_matchers(self, matcher_names): @@ -97,7 +97,7 @@ class VCR: for m in matcher_names: matchers.append(self.matchers[m]) 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 def use_cassette(self, path=None, **kwargs): diff --git a/vcr/request.py b/vcr/request.py index 1645908..130f19c 100644 --- a/vcr/request.py +++ b/vcr/request.py @@ -48,6 +48,7 @@ class Request: warnings.warn( "Request.add_header is deprecated. Please assign to request.headers instead.", DeprecationWarning, + stacklevel=2, ) self.headers[key] = value diff --git a/vcr/serializers/jsonserializer.py b/vcr/serializers/jsonserializer.py index 5ffef3e..55cf780 100644 --- a/vcr/serializers/jsonserializer.py +++ b/vcr/serializers/jsonserializer.py @@ -17,13 +17,5 @@ def serialize(cassette_dict): try: return json.dumps(cassette_dict, indent=4) + "\n" - except UnicodeDecodeError as original: # py2 - raise UnicodeDecodeError( - original.encoding, - b"Error serializing cassette to JSON", - original.start, - original.end, - original.args[-1] + error_message, - ) - except TypeError: # py3 - raise TypeError(error_message) + except TypeError: + raise TypeError(error_message) from None