如何对参数列表中的每个项目运行 pytest 测试 [英] How to run a pytest test for each item in a list of arguments

查看:55
本文介绍了如何对参数列表中的每个项目运行 pytest 测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个像这样的 HTTP URL 列表

Suppose I have a list of HTTP URLs like

endpoints = ["e_1", "e_2", ..., "e_n"]

我想运行 n 测试,每个端点一个.我该怎么做?

And I want to run n tests, one for each endpoint. How can I do that?

一次测试所有端点的简单方法是

A simple way to test all the endpoints at once would be

def test_urls():
    for e in endpoints:
        r = get(e)
        assert r.status_code < 400

或者类似的东西.但正如您所看到的,这是对所有 n 端点的一项测试,我希望比这更细化一些.

or something like that. But as you can see, this is one test for all the n endpoints and I would like a little more granularity than that.

我尝试过使用类似的装置

I have tried using a fixture like

@fixture
def endpoint():
    for e in endpoints:
        yield e

但是,显然,Pytest 并不真正喜欢夹具中的多产量"并返回一个 yield_fixture 函数有多个产量" 错误

but, apparently, Pytest is not really fond of "multiple yields" in a fixture and returns a yield_fixture function has more than one 'yield' error

推荐答案

遵循 参数化夹具和测试函数,您可以将测试实现为:

Following the example in Parametrizing fixtures and test functions, you can implement the test as:

import pytest

endpoints = ['e_1', 'e_2', ..., 'e_n']

@pytest.mark.parametrize('endpoint', endpoints)
def test_urls(endpoint):
    r = get(endpoint)
    assert r.status_code < 400

这将运行 test_urls n 次,每个端点一次:

This will run test_urls n times, once per endpoint:

test_spam::test_urls[e_1] PASSED
test_spam::test_urls[e_2] PASSED
...
test_spam::test_urls[e_n] PASSED

这篇关于如何对参数列表中的每个项目运行 pytest 测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆