0

响应库为请求提供模拟。就我而言,它通常看起来像这样:

import responses

@responses.activate
def test_foo():
    # Add mocks for service A
    responses.add(responses.POST, 'http://service-A/foo', json={'bar': 'baz'}, status=200)
    responses.add(responses.POST, 'http://service-A/abc', json={'de': 'fg'}, status=200)


@responses.activate
def test_another_foo():
    # Add mocks for service A
    responses.add(responses.POST, 'http://service-A/foo', json={'bar': 'baz'}, status=200)
    responses.add(responses.POST, 'http://service-A/abc', json={'de': 'fg'}, status=200)


如何避免这种代码重复?

我很想有一个mock_service_a固定装置或类似的东西。

4

1 回答 1

1

正如您所建议的,创建一个夹具可以解决这些问题。

import pytest
import responses
import requests

@pytest.fixture(scope="module", autouse=True)
def mocked_responses():
    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.POST, "http://service-a/foo", json={"bar": "baz"}, status=200
        )
        rsps.add(
            responses.POST, "http://service-a/abc", json={"de": "fg"}, status=200
        )
        yield rsps


def test_foo():
    resp = requests.post("http://service-a/foo", json={"bar": "baz"})
    assert resp.status_code == 200


def test_another_foo():
    resp = requests.post("http://service-a/abc", json={"de": "fg"})
    assert resp.status_code == 200

运行它返回:

==================================== test session starts =====================================
platform darwin -- Python 3.9.1, pytest-6.2.2, py-1.10.0, pluggy-0.13.1
rootdir: **
collected 2 items                                                                            

tests/test_grab.py ..                                                                  [100%]

===================================== 2 passed in 0.21s ======================================
于 2021-07-24T13:11:54.553 回答