【问题标题】:How can I de-duplicate responses for pytest?如何删除 pytest 的重复响应?
【发布时间】:2023-04-03 16:31:01
【问题描述】:

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

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 固定装置或类似的东西。

【问题讨论】:

    标签: pytest python-responses


    【解决方案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 ======================================
    

    【讨论】:

    • 我猜你需要将mocked_responses 作为参数传递给test_footest_another_foo
    • 还是因为scope="module", autouse=True而自动添加的?
    猜你喜欢
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 2021-06-22
    • 2021-08-06
    • 1970-01-01
    • 2014-05-08
    • 1970-01-01
    相关资源
    最近更新 更多