为什么 requests-mock 装饰器模式会在 pytest 中抛出 "fixture 'm' not found" 错误?

Why is the requests-mock decorator pattern throwing a "fixture 'm' not found" error with pytest?

我正在使用 requests 库发出 HTTP GET 请求。例如 (t运行cated):

requests.get("http://123-fake-api.com")

我已经按照 requests-mock decorator 模式编写了一个测试。

import requests
import requests_mock


@requests_mock.Mocker()
def test(m):
    m.get("http://123-fake-api.com", text="Hello!")

    response = requests.get("http://123-fake-api.com").text

    assert response.text == "Hello!"

当我 运行 使用 pytest 进行测试时,出现以下错误。

E       fixture 'm' not found

为什么 requests-mock 装饰器抛出 "fixture 'm' not found" 错误?我该如何解决?

您收到错误消息是因为 Requests Mock 装饰器在 Python 3 (see GitHub issue). To resolve the error, use the workaround referenced in How to use pytest capsys on tests that have mocking decorators?.

中无法识别
import requests
import requests_mock


@requests_mock.Mocker(kw="mock")
def test(**kwargs):
    kwargs["mock"].get("http://123-fake-api.com", text="Hello!")

    response = requests.get("http://123-fake-api.com")

    assert response.text == "Hello!"

其他选项

您还可以使用以下备选方案之一。

1。 requests-mock

的 pytest 插件

使用请求模拟作为 pytest fixture

import requests


def test_fixture(requests_mock):
    requests_mock.get("http://123-fake-api.com", text="Hello!")

    response = requests.get("http://123-fake-api.com")

    assert response.text == "Hello!"

2。上下文管理器

使用请求模拟作为 context manager

import requests
import requests_mock


def test_context_manager():
    with requests_mock.Mocker() as mock_request:
        mock_request.get("http://123-fake-api.com", text="Hello!")
        response = requests.get("http://123-fake-api.com")

    assert response.text == "Hello!"