Hacktoberfest 2026:维护者为十月标记出来的 issue,仍然开放、适合新手。 浏览 Hacktoberfest issue

How to combine multiple RequestMock contexts (pytest fixture)?

未关闭
#779 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 3 天内回复

还没有人认领这个 Issue。

评估

难度
4/5
预计耗时
3-5 天
新手友好度
45/100
Issue 类型
功能
描述清晰度
基本清楚
活跃度
停滞
技术栈
python
领域
testing

调研方向

先从 RequestsMock 的上下文和注册行为入手,然后查看相关的 issue #542 以及此处展示的 pytest fixtures。复现 test_api 和 test_api2;当对 example.foo 和 example.bar 的请求都返回各自注册的 200 响应,且一个 mock 不会覆盖另一个 mock 时,即表示完成。

由索引模型根据 Issue 内容生成。

描述

question

How can I combine multiple RequestsMock contexts so that they don't overwrite each other?
In my specific case I'm using RequestsMock as pytest fixtures.

If there isn't a supported way to do this, what's the easiest way to programmatically copy the registered mocks from 2 different RequestsMock into a 3rd one?

from typing import Generator

import pytest
import requests
import responses

@pytest.fixture
def mock_foo_api() -> Generator[responses.RequestsMock, None, None]:
    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.GET,
            "https://example.foo",
            status=200,
            body="{'msg': 'foo'}"
            content_type="application/json",
        )
        yield rsps

@pytest.fixture
def mock_bar_api() -> Generator[responses.RequestsMock, None, None]:
    with responses.RequestsMock() as rsps:
        rsps.add(
            responses.GET,
            "https://example.bar",
            status=200,
            body="{'msg': 'bar'}"
            content_type="application/json",
        )
        yield rsps

def test_api(mock_foo_api: responses.RequestsMock, mock_bar_api: responses.RequestsMock):
    # this test fails    
    bar_req = requests.get("https://example.bar")
    assert bar_req.status_code == 200

    foo_req = requests.get("https://example.foo")
    assert foo_req.status_code == 200

# can I do something like this?? 👇 

@pytest.fixture
def hypothetical_combined_api_mocks(
    mock_foo_api: responses.RequestsMock,
    mock_bar_api: responses.RequestsMock
):
    with responses.RequestsMock() as rsps:
        for registered_mock in [*mock_foo_api.<SOMETHING>, *mock_bar_api.<SOMETHING>]
            rsps.add(registered_mock)
         yield rsps


def test_api2(hypothetical_combined_api_mocks: responses.RequestsMock):
    bar_req = requests.get("https://example.bar")
    assert bar_req.status_code == 200

    foo_req = requests.get("https://example.foo")
    assert foo_req.status_code == 200

主要语言
Python
星标
4.3k
派生
389
平均合并
1 天 17 小时
30 天内合并 PR
2

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 有 Pull Request 模板
  • 没有贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

getsentry/responses 的其他 Issue

查看 getsentry/responses 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。