为什么请求模拟装饰器模式会在 pytest 中抛出“找不到夹具‘m’”错误?

Rya*_*yne 5 mocking pytest python-requests python-decorators requests-mock

我正在使用请求库发出 HTTP GET 请求。例如(截断):

requests.get("http://123-fake-api.com")
Run Code Online (Sandbox Code Playgroud)

我已经按照请求模拟装饰器模式编写了一个测试。

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!"
Run Code Online (Sandbox Code Playgroud)

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

E       fixture 'm' not found
Run Code Online (Sandbox Code Playgroud)

为什么请求模拟装饰器会抛出“找不到夹具‘m’”错误?我该如何解决?

Rya*_*yne 7

您收到错误是因为在 Python 3 中无法识别 Requests Mock 装饰器(请参阅 GitHub 问题)。要解决该错误,请使用如何在具有模拟装饰器的测试中使用 pytest capsys 中引用的解决方法.

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!"
Run Code Online (Sandbox Code Playgroud)

其他选项

您还可以使用以下替代方法之一。

1. 用于请求模拟的 pytest 插件

使用 Requests Mock 作为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!"
Run Code Online (Sandbox Code Playgroud)

2. 上下文管理器

使用 Requests Mock 作为上下文管理器

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!"
Run Code Online (Sandbox Code Playgroud)