首页 > 解决方案 > 如何使用 Pytest 参数化和响应来模拟 url

问题描述

我是 Python 单元测试的新手。我正在尝试模拟响应,但 url 没有被模拟返回错误,即模拟未注册,并提示我使用真实的 URL,使用真实的 URL,但它需要以某种方式进行模拟。尝试了 pytest 参数化但没有成功。

这是我到目前为止所尝试的:

FAKE_HOST = "https://fake-host.com"
@pytest.mark.parametrize(
    ("fake_url"),
    [(FAKE_HOST, "https://fake-host.com")],
)
@responses.activate
def test_item(fake_url):
    responses.add(
        responses.GET,
        f"{fake_url}/rest/info?name=item",
        status=200,
    )

    resp = requests.get(
        "https://{fake_url}/rest/info?name=item"

    )
    assert resp.status_code == 200

标签: pythonunit-testingpytest

解决方案


import requests


def example2():
    r = requests.get("http://httpbin.org/" + "get")
    if r.status_code == 200:
        response_data = r.json()
        return r.status_code, response_data["url"]
    else:
        return r.status_code, ""


def test_get_response_success(monkeypatch):
    class MockResponse(object):
        def __init__(self):
            self.status_code = 200
            self.url = "http://httpbin.org/get"
            self.headers = {"foobar": "foooooo"}

        def json(self):
            return {"fooaccount": "foo123", "url": "https://fake-host.com"}

    def mock_get(url):
        return MockResponse()

    monkeypatch.setattr(requests, "get", mock_get)
    assert example2() == (200, "https://fake-host.com")

您是否考虑过使用monkeypyatching


推荐阅读