Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Record matcher #641

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions responses/_recorder.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import inspect
from functools import wraps
from typing import TYPE_CHECKING

from responses.matchers import header_matcher
from responses.matchers import query_param_matcher

if TYPE_CHECKING: # pragma: no cover
import os

Expand Down Expand Up @@ -58,6 +62,11 @@ def _dump(
}
}
)
if rsp.match:
matchers = data["responses"][-1]["response"]["matchers"] = []
for matcher in rsp.match:
matchers.append(parse_matchers_function(matcher))

except AttributeError as exc: # pragma: no cover
raise AttributeError(
"Cannot dump response object."
Expand All @@ -66,6 +75,17 @@ def _dump(
dumper(_remove_nones(data), destination)


def parse_matchers_function(func: "Callable[..., Any]") -> "Dict[str, Any]":
matcher_name = func.__qualname__.split(".")[0]
matcher_constructor: Dict[str, Any] = {
matcher_name: {
"args": inspect.getclosurevars(func).nonlocals,
"matcher_import_path": func.__module__,
}
}
return matcher_constructor


class Recorder(RequestsMock):
def __init__(
self,
Expand Down Expand Up @@ -121,6 +141,10 @@ def _on_request(
url=str(requests_response.request.url),
status=requests_response.status_code,
body=requests_response.text,
match=(
query_param_matcher(request.params), # type: ignore[attr-defined]
header_matcher(dict(request.headers)),
),
)
self._registry.add(responses_response)
return requests_response
Expand Down
10 changes: 5 additions & 5 deletions responses/matchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,13 +207,13 @@ def query_param_matcher(

"""

params_dict = params or {}
def match(request: PreparedRequest) -> Tuple[bool, str]:
params_dict = params or {}

for k, v in params_dict.items():
if isinstance(v, (int, float)):
params_dict[k] = str(v)
for k, v in params_dict.items():
if isinstance(v, (int, float)):
params_dict[k] = str(v)

def match(request: PreparedRequest) -> Tuple[bool, str]:
reason = ""
request_params = request.params # type: ignore[attr-defined]
request_params_dict = request_params or {}
Expand Down
135 changes: 117 additions & 18 deletions responses/tests/test_recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,42 +21,141 @@ def get_data(host, port):
"responses": [
{
"response": {
"method": "GET",
"url": f"http://{host}:{port}/404",
"auto_calculate_content_length": False,
"body": "404 Not Found",
"status": 404,
"content_type": "text/plain",
"auto_calculate_content_length": False,
"matchers": [
{
"query_param_matcher": {
"args": {"params": {}, "strict_match": True},
"matcher_import_path": "responses.matchers",
}
},
{
"header_matcher": {
"args": {
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"User-Agent": "python-requests/2.30.0",
},
"strict_match": False,
},
"matcher_import_path": "responses.matchers",
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hi @markstory

pls have a look on the draft of the recorder.
I have a question/concern how to proceed with replay

considering that we need to support custom matchers, we probably want to import matchers as well.
I found a way how to extract the location of the mather. however, then we need to do import during runtime and local to each function, which does not sound really smart

what could be the options?

I think asking users to import required matchers defeats the purpose of record/replay

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hrm, importing userland code is possible but it could get messy. I think we're also taking a risk that userland matcher parameters will be 'serializable' into JSON, which isn't guaranteed. We could require that in order to use recording 🤷

}
},
],
"method": "GET",
"status": 404,
"url": f"http://{host}:{port}/404",
}
},
{
"response": {
"method": "GET",
"url": f"http://{host}:{port}/status/wrong",
"auto_calculate_content_length": False,
"body": "Invalid status code",
"status": 400,
"content_type": "text/plain",
"auto_calculate_content_length": False,
"matchers": [
{
"query_param_matcher": {
"args": {"params": {}, "strict_match": True},
"matcher_import_path": "responses.matchers",
}
},
{
"header_matcher": {
"args": {
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"User-Agent": "python-requests/2.30.0",
},
"strict_match": False,
},
"matcher_import_path": "responses.matchers",
}
},
],
"method": "GET",
"status": 400,
"url": f"http://{host}:{port}/status/wrong",
}
},
{
"response": {
"method": "GET",
"url": f"http://{host}:{port}/500",
"auto_calculate_content_length": False,
"body": "500 Internal Server Error",
"status": 500,
"content_type": "text/plain",
"auto_calculate_content_length": False,
"matchers": [
{
"query_param_matcher": {
"args": {
"params": {"query": "smth"},
"strict_match": True,
},
"matcher_import_path": "responses.matchers",
}
},
{
"header_matcher": {
"args": {
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"User-Agent": "python-requests/2.30.0",
},
"strict_match": False,
},
"matcher_import_path": "responses.matchers",
}
},
{
"query_string_matcher": {
"args": {"query": "query=smth"},
"matcher_import_path": "responses.matchers",
}
},
],
"method": "GET",
"status": 500,
"url": f"http://{host}:{port}/500?query=smth",
}
},
{
"response": {
"method": "PUT",
"url": f"http://{host}:{port}/202",
"auto_calculate_content_length": False,
"body": "OK",
"status": 202,
"content_type": "text/plain",
"auto_calculate_content_length": False,
"matchers": [
{
"query_param_matcher": {
"args": {"params": {}, "strict_match": True},
"matcher_import_path": "responses.matchers",
}
},
{
"header_matcher": {
"args": {
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "keep-alive",
"Content-Length": "0",
"User-Agent": "python-requests/2.30.0",
"XAuth": "54579",
},
"strict_match": False,
},
"matcher_import_path": "responses.matchers",
}
},
],
"method": "PUT",
"status": 202,
"url": f"http://{host}:{port}/202",
}
},
]
Expand All @@ -77,8 +176,8 @@ def test_recorder(self, httpserver):
url202, url400, url404, url500 = self.prepare_server(httpserver)

def another():
requests.get(url500)
requests.put(url202)
requests.get(url500, params={"query": "smth"})
requests.put(url202, headers={"XAuth": "54579"})

@_recorder.record(file_path=self.out_file)
def run():
Expand Down