Python 使用函数为pytest提供参数
我有一个使用Python 使用函数为pytest提供参数,python,python-3.x,pytest,Python,Python 3.x,Pytest,我有一个使用pytest filename.py运行的基本端点测试: ENDPOINTS = ['/users'] def test_get_requests(application_headers): """ Test all endpoints with a GET method """ for endpoint in ENDPOINTS: response = requests.get(API_
pytest filename.py运行的基本端点测试:
ENDPOINTS = ['/users']
def test_get_requests(application_headers):
""" Test all endpoints with a GET method """
for endpoint in ENDPOINTS:
response = requests.get(API_URL + endpoint, headers=application_headers)
assert response.status_code == 200
这使用ENDPOINTS
列表和application\u headers
fixture向指定的端点发送HTTP请求,并断言其成功状态代码
这个很好用
我在一个远程JSON文件中有一个端点列表,我想加载它,从中筛选端点,然后测试,而不是使用手动定义的端点列表
我创建了一个像这样的装置:
@pytest.fixture(scope='module')
def application_endpoints():
endpoints = []
with request.urlopen('https://my.endpoint.file.json') as response:
if response.getcode() == 200:
source = response.read()
data = json.loads(source)
for path in data["paths"]:
endpoints.append(path)
return endpoints
然后,我将测试定义更改为def test\u get\u requests(应用程序标题、应用程序端点)
,但这会导致错误TypeError:只能将str(而不是“list”)连接到str
我还尝试了另一种方法,使用参数化,但也失败了:
@pytest.mark.parametrize('endpoint', application_endpoints)
def test_get_requests(application_headers):
""" Test all endpoints with a GET method """
for endpoint in ENDPOINTS:
response = requests.get(API_URL + endpoint, headers=application_headers)
assert response.status_code == 200
该故障的错误为NameError:name“application\u endpoints”未定义
我觉得我在做一件很简单的事情,却弄错了。我是以错误的方式思考这个问题,还是我的语法不正确?您可以使用参数化方法,但您不能对参数使用固定装置-只使用函数。此外,代码中的端点
和应用程序头
也存在一些混淆。忽略应用程序\u标题的来源,您可以尝试以下操作:
def application_endpoints():#不是固定装置!
端点=[]
...
返回端点
@pytest.mark.parametize('endpoint',application_endpoints())
def test_get_请求(端点):
response=requests.get(API\uURL+endpoint,headers=application\uheaders)
assert response.status_code==200
无需自己迭代端点-这就是标记。参数化
已经通过为每个端点创建单独的测试来完成。您可以使用参数化
方法,但您不能为参数使用夹具-只需使用函数即可。此外,代码中的端点
和应用程序头
也存在一些混淆。忽略应用程序\u标题的来源,您可以尝试以下操作:
def application_endpoints():#不是固定装置!
端点=[]
...
返回端点
@pytest.mark.parametize('endpoint',application_endpoints())
def test_get_请求(端点):
response=requests.get(API\uURL+endpoint,headers=application\uheaders)
assert response.status_code==200
无需自己迭代端点-这就是标记。通过为每个端点创建单独的测试,parametrize
已经完成了。应用程序头是一个完全独立的装置。你的答案完全有道理,但我现在一两天内都没有机会测试它。我会尽快联系的。非常感谢。应用程序头是一个完全独立的装置。你的答案完全有道理,但我现在一两天内都没有机会测试它。我会尽快联系的。非常感谢。