python - 如何使用 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
解决方案
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?
推荐阅读
- react-native - Realm 在 ReactNative 中插入新模式
- asp.net-core-2.0 - 如何在 asp.net cor 2 中使用 ImageResizer
- django - 在 django 中将 Django_filter 和分页添加到 FilterView 类
- uwp - 从 Windows IoT Core 关闭 Raspbian
- python - 使用 RabbitMQ 的客户端 Celery 工作人员的套接字关闭,错过了心跳
- javascript - 为什么 new Date('2018-12-29') 返回 12 月 28 日?
- angular - 如何以角度突出显示contenteditable div中的文本?
- laravel - “方法 Illuminate\Http\UploadedFile::pixelate 不存在。”
- javascript - 比较两个数组的内容
- javascript - 如何在 TypeScript 中将箭头函数返回值分配给字符串 []