【发布时间】:2019-11-22 17:39:32
【问题描述】:
我有一个 python 函数,它使用请求函数调用 API。我想测试一个 200 的路径,然后测试一个 500 的错误。查看 requests-mock 文档时,我似乎不知道该怎么做。
这是我要测试的内容。
def get_sku_data(sku: str):
"""
Retrieve a single product from api
"""
uri = app.config["SKU_URI"]
url = f"{uri}/{sku}"
headers = {
"content-type": "application/json",
"cache-control": "no-cache",
"accept": "application/json",
}
try:
retry_times = 3
response = retry_session(retries=retry_times).get(url, headers=headers)
return response.json()
except ConnectionError as ex:
raise Exception(f"Could not connect to sku api at {uri}. {ex}.")
except requests.exceptions.RetryError:
raise Exception(f"Attempted to connect to {uri} {retry_times} times.")
def retry_session(
retries, backoff_factor=0.3, status_forcelist=(500, 502, 503, 504)
) -> requests.Session:
"""
Performs a retry
"""
session = requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session
这是我正在尝试的测试存根
# These test use pytest https://pytest.readthedocs.io/en/latest/
# Note: client is a pytest fixture that is dependency injected from src/tests/conftest.py
import json
import pytest
from src.app import create_app
import requests
import requests_mock
@pytest.fixture
def app():
app = create_app()
return app
def test():
session = requests.Session()
adapter = requests_mock.Adapter()
session.mount("mock", adapter)
adapter.register_uri("GET", "mock://12", text="data")
resp = session.get("mock://12")
assert resp.status_code == 200
assert resp.text == "data"
我对 python 测试有点陌生,所以非常感谢任何帮助。
【问题讨论】:
-
按照这个:-docs.pytest.org/en/latest/contents.html 然后迁移到故障处理部分
-
我不确定这是否是我想要的。我通读了它,但实际上这是为了模拟请求并调用使用它的方法。
-
不太清楚你的测试在测试什么。对于
requests_mock的用法,请查看pytest示例in its docs。 -
这就是我目前拥有的,但我不明白它在测试什么?该值作为返回值提供,然后被调用。是否符合端点逻辑?
标签: python python-3.x python-requests pytest