Skip to content

Commit

Permalink
Add feature for allowing the body of a request to be matched Closes #716
Browse files Browse the repository at this point in the history
 (#717)

Add feature for allowing the body of a request to be matched

Fixes #716
  • Loading branch information
TheJacobWalters authored Jun 6, 2024
1 parent 83f2e28 commit 19efe5b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
15 changes: 15 additions & 0 deletions responses/matchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,21 @@ def _filter_dict_recursively(
return filtered_dict


def body_matcher(params: str, *, allow_blank: bool = False) -> Callable[..., Any]:
def match(request: PreparedRequest) -> Tuple[bool, str]:
reason = ""
if isinstance(request.body, bytes):
request_body = request.body.decode("utf-8")
else:
request_body = request.body
valid = True if request_body == params else False
if not valid:
reason = f"request.body doesn't match {params} doesn't match {request_body}"
return valid, reason

return match


def urlencoded_params_matcher(
params: Optional[Mapping[str, str]], *, allow_blank: bool = False
) -> Callable[..., Any]:
Expand Down
34 changes: 34 additions & 0 deletions responses/tests/test_matchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,40 @@
from responses.tests.test_responses import assert_response


def test_body_match_get():
@responses.activate
def run():
url = "http://example.com"
responses.add(
responses.GET,
url,
body=b"test",
match=[matchers.body_matcher("123456")],
)
resp = requests.get("http://example.com", data="123456")
assert_response(resp, "test")

run()
assert_reset()


def test_body_match_post():
@responses.activate
def run():
url = "http://example.com"
responses.add(
responses.POST,
url,
body=b"test",
match=[matchers.body_matcher("123456")],
)
resp = requests.post("http://example.com", data="123456")
assert_response(resp, "test")

run()
assert_reset()


def test_query_string_matcher():
@responses.activate
def run():
Expand Down

0 comments on commit 19efe5b

Please sign in to comment.