Skip to content

Commit

Permalink
Fix assert_all_requests_are_fired not reseting (#622)
Browse files Browse the repository at this point in the history
When multiple tests use assert_all_requests_are_fired=True and a test
fails because mocks were not called, those mocks should be reset when
the context manager exits.

Fixes #619
  • Loading branch information
markstory authored Feb 9, 2023
1 parent faf6dd9 commit ec6c755
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
* Fix type annotations of `CallList`. See #593
* Replaced toml with tomli and tomli-w.
* `request` object is attached to any custom exception provided as `Response` `body` argument. See #588
* Fixed mocked responses leaking between tests when `assert_all_requests_are_fired` and a request was not fired.

0.22.0
------
Expand Down
6 changes: 4 additions & 2 deletions responses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -924,8 +924,10 @@ def __enter__(self) -> "RequestsMock":

def __exit__(self, type: Any, value: Any, traceback: Any) -> bool:
success = type is None
self.stop(allow_assert=success)
self.reset()
try:
self.stop(allow_assert=success)
finally:
self.reset()
return success

@overload
Expand Down
22 changes: 22 additions & 0 deletions responses/tests/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1133,6 +1133,28 @@ def run():
assert_reset()


def test_assert_all_requests_fired_multiple():
@responses.activate(assert_all_requests_are_fired=True)
def test_some_function():
# Not all mocks are called so we'll get an AssertionError
responses.add(responses.GET, "http://other_url", json={})
responses.add(responses.GET, "http://some_api", json={})
requests.get("http://some_api")

@responses.activate(assert_all_requests_are_fired=True)
def test_some_second_function():
# This should pass as mocks should be reset.
responses.add(responses.GET, "http://some_api", json={})
requests.get("http://some_api")

with pytest.raises(AssertionError):
test_some_function()
assert_reset()

test_some_second_function()
assert_reset()


def test_allow_redirects_samehost():
redirecting_url = "http://example.com"
final_url_path = "/1"
Expand Down

0 comments on commit ec6c755

Please sign in to comment.