Skip to content

Commit

Permalink
test and document dumping to file
Browse files Browse the repository at this point in the history
  • Loading branch information
niccokunzmann committed Dec 26, 2024
1 parent acd8d5b commit eb5c94f
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
16 changes: 16 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,22 @@ will produce next output:
status: 202
url: https://httpstat.us/202
If you are in the REPL, you can also activete the recorder for all following responses:

.. code-block:: python
import requests
from responses import _recorder
_recorder.recorder.start()
requests.get("https://httpstat.us/500")
_recorder.recorder.dump_to_file("out.yaml")
# you can stop or reset the recorder
_recorder.recorder.stop()
_recorder.recorder.reset()
Replay responses (populate registry) from files
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Expand Down
8 changes: 6 additions & 2 deletions responses/_recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing import Callable
from typing import Dict
from typing import List
from typing import Optional
from typing import Type
from typing import Union
from responses import FirstMatchRegistry
Expand Down Expand Up @@ -122,10 +123,13 @@ def wrapper(*args: "Any", **kwargs: "Any") -> "Any": # type: ignore[misc]

def dump_to_file(
self,
*,
file_path: "Union[str, bytes, os.PathLike[Any]]",
registered: "List[BaseResponse]",
*,
registered: "Optional[List[BaseResponse]]" = None,
) -> None:
"""Dump the recorded responses to a file."""
if registered is None:
registered = self.get_registry().registered
with open(file_path, "w") as file:
_dump(registered, file, yaml.dump)

Expand Down
29 changes: 29 additions & 0 deletions responses/tests/test_recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,35 @@ def prepare_server(self, httpserver):
url400 = httpserver.url_for("/status/wrong")
return url202, url400, url404, url500

def test_use_recorder_without_decorator(self, httpserver):
"""I want to be able to record in the REPL."""
url202, url400, url404, url500 = self.prepare_server(httpserver)

_recorder.recorder.start()

def another():
requests.get(url500)
requests.put(url202)

def run():
requests.get(url404)
requests.get(url400)
another()

run()

_recorder.recorder.stop()
_recorder.recorder.dump_to_file(self.out_file)

with open(self.out_file) as file:
data = yaml.safe_load(file)
assert data == get_data(httpserver.host, httpserver.port)

# Now, we test that the recorder is properly reset
assert _recorder.recorder.get_registry().registered
_recorder.recorder.reset()
assert not _recorder.recorder.get_registry().registered


class TestReplay:
def setup_method(self):
Expand Down

0 comments on commit eb5c94f

Please sign in to comment.