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

Feedback on responses._recorder / How to make it better #740

Open
last-partizan opened this issue Oct 6, 2024 · 0 comments
Open

Feedback on responses._recorder / How to make it better #740

last-partizan opened this issue Oct 6, 2024 · 0 comments

Comments

@last-partizan
Copy link

This is awesome feature, and I started using it right away.

But, it's tedious to have separate code for creating responses. So, I'm using following plugin:

It allows to run pytest --update-responses and they will be saved to a file, and loaded when used without this argument.

Maybe, include this as plugin? I can make PR adding this, so we can make proper code review.

from __future__ import annotations

import pytest
import responses
from _pytest.config.argparsing import Parser
from pytest_cases import fixture
from responses._recorder import recorder


def pytest_addoption(parser: Parser):
    group = parser.getgroup("responses")
    group.addoption(
        "--update-responses",
        action="store_true",
        dest="update_responses",
        default=False,
        help="Don't mock responses, instead write actual responses to snapshot files.",
    )


@fixture
def mocked_responses():
    with responses.RequestsMock() as rsps:
        yield rsps


@fixture
def responses_snapshot(request: pytest.FixtureRequest):
    """
    Before using response you need to write snapshots.

    Run with `pytest --update-responses`.

    https://github.com/getsentry/responses#record-responses-to-files
    """

    update = request.config.getoption("update_responses")
    snapshot = _get_snapshot_file(request)

    if update:
        with recorder as r:
            yield r
            recorder.dump_to_file(
                file_path=snapshot,
                registered=r.get_registry().registered,
            )
    else:
        with responses.RequestsMock() as r:
            r._add_from_file(snapshot)
            yield r


def _get_snapshot_file(request: pytest.FixtureRequest):
    f = request.node.name.replace("[", "-").replace("]", "")
    p = request.path.parent / "__responses__/"
    p.mkdir(exist_ok=True)
    return p / f"{f}.yaml"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

No branches or pull requests

2 participants