How to combine multiple RequestMock contexts (pytest fixture)?

オープン
#779 コメント 0 件 リアクション 0 件 担当者 0 名 GitHub で見る

メンテナーはふだん 3 日以内に返信

まだ誰も着手していません。

評価

難易度
4/5
見積もり時間
3〜5日
初心者へのやさしさ
45/100
issue の種類
機能追加
明瞭さ
おおむね明確
活発さ
停滞
技術スタック
python
領域
testing

調査の方向性

まず RequestsMock のコンテキストと登録動作を確認し、次に関連する issue #542 と、ここに示されている pytest のフィクスチャを確認してください。test_api と test_api2 を再現してください。example.foo と example.bar へのリクエストの両方が、片方の mock がもう片方を上書きすることなく、登録された 200 レスポンスを返せば完了です。

索引モデルが 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時間
マージ済み PR(30日)
2

環境構築

  • Dockerfile・Docker Compose ファイルなし
  • プルリクエストのテンプレートあり
  • コントリビューションガイドなし

はじめの一歩

  1. issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
  2. 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
  3. リポジトリをフォークし、ブランチを切って変更します。
  4. issue 番号を参照したプルリクエストを送ります。

getsentry/responses のほかの issue

getsentry/responses の issue をすべて見る

似ている issue

Python の issue をもっと見る

新しい issue をメールで受け取る

初心者向けの GitHub issue を短くまとめたダイジェスト。