【发布时间】:2020-11-23 15:27:39
【问题描述】:
您好,我是单元测试的新手,我正在研究 mocks 和 pytest。我正在尝试对两个 rest api 请求进行单元测试,其中 GET 请求检查 API 中是否不存在某个项目以及它是否不创建它与 POST 请求并创建一个文件夹,否则如果它存在只是创建一个文件夹。
我尝试使用Mocker(),但当我尝试模拟GET 请求时,我被困在AttributeError: Mocker 上。
这是我要测试的代码:
client = requests.session()
# get item by name
response = client.get(
f"https://url.com/rest/item/info?name=test_item",
auth=username, password),
)
if (
response.status_code == 200
and response.json()["status"]
== "Item doesn't exist!"
):
logging.info(f"Creating item")
client.post(
"https://url.com/rest/item/create?name=test_item",
auth=username, password),
)
# directory creation
dir_make = "mkdir -p test_item/temperature"
exec_cmd(dir_make)
elif response.status_code == 200 and response.json()["status"]=="OK":
# directory creation
dir_make = "mkdir -p test_item/temperature"
exec_cmd(dir_make)
这是以AttributeError 失败的单元测试:
def test_existing_item(requests_mock, monkeypatch):
with requests_mock.Mocker() as mock:
mock.get("https://url.com/rest/item/info?name=test_item", text="OK")
resp = requests.get("https://url.com/rest/item/info?name=test_item")
assert resp.text == "OK"
编辑:测试未找到项目和 POST 模拟。似乎它没有为else 语句添加覆盖范围。如果该项目存在并且在这种情况下只需要添加文件夹,如何测试?
编辑 2:添加了 elif 语句而不是 else 和 2 个单独的测试,仍然是一个 test_existing_items() 不包括 elif 语句......在这种情况下我做错了什么?
def test_existing_item(monkeypatch):
with requests_mock.Mocker() as mock_request:
mock_request.get(requests_mock.ANY, text="success!")
resp = requests.get(
"https://url.com/rest/item/info?name=test_item",
auth=("mock_username", "mock_password"),
)
if resp.status_code == 200 and resp.json()["status"] == "OK":
dir_make = "mkdir -p test_item/temperature"
exec_cmd(dir_make)
encoded_auth = b64encode(b"mock_username:mock_password").decode("ascii")
assert mock_request.last_request.headers["Authorization"] == f"Basic {encoded_auth}"
def test_post_item(monkeypatch):
with requests_mock.Mocker() as mock_request:
mock_request.get(requests_mock.ANY, text="success!")
resp = requests.get(
"https://url.com/rest/item/info?name=test_item",
auth=("mock_username", "mock_password"),
)
if resp.status_code == 200 and resp.json()["status"] == "ERROR":
mock_request.get(requests_mock.ANY, text="success!")
requests.post(
"https://url.com/rest/item/create?name=test_item",
auth=("mock_username", "mock_password"),
)
dir_make = "mkdir -p test_item/temperature"
exec_cmd(dir_make)
encoded_auth = b64encode(b"mock_username:mock_password").decode("ascii")
assert mock_request.last_request.headers["Authorization"] == f"Basic {encoded_auth}"
我不熟悉单元测试,所以如果能对这段代码进行单元测试,我们将不胜感激。
【问题讨论】:
标签: python unit-testing mocking pytest