在 pytest 中参数化测试类 [英] parametrizing test classes in pytest

查看:35
本文介绍了在 pytest 中参数化测试类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类来测试我的一些代码.我想参数化设置并使用不同的参数重新运行类:

I have a class for testing some of my code. I would like to parametrize the setup and rerun the class with different parameters:

class TestNormalLTEPlasma:


    def setup(self, t=10000):
        self.plasma = plasma.LTEPlasma.from_abundance(t, {'Si':1.0}, 1e-13, atom_data, 10*86400)

    def test_beta_rad(self):
        assert self.plasma.beta_rad == 1 / (10000 * constants.k_B.cgs.value)

    def test_t_electron(self):
        assert self.plasma.t_electron == 0.9 * self.plasma.t_rad

    def test_saha_calculation_method(self):
        assert self.plasma.calculate_saha == self.plasma.calculate_saha_lte

我想以 1000 的步长从 t=2000 到 t=20000 运行这个类.

I would like to run this class going from t=2000 to t=20000 in steps of 1000.

推荐答案

创建一个参数化的测试装置,而不是你的设置函数:

Instead of your setup function, create a parametrized test fixture:

ts = range(2000, 20001, 1000)  # This creates a list of numbers from 2000 to 20000 in increments of 1000.

@pytest.fixture(params=ts)
def plasma(request):
    return plasma.LTEPlasma.from_abundance(request.param, {'Si':1.0}, 1e-13, atom_data, 10*86400)

参数化测试装置"是指当您在测试用例中使用它时,pytest 将为每个参数创建一个新的测试用例并分别运行.

A "parametrized test fixture" is one where, when you use it in a test case, pytest will create a new test case for each parameter and run each separately.

您可以通过向每个需要它的测试函数添加一个名为plasma"的函数参数来使用测试装置:

You use the test fixture by adding a function argument called "plasma" to each of the test functions that want it:

class TestNormalLTEPlasma:

    def test_beta_rad(self, plasma):
        assert plasma.beta_rad == 1 / (10000 * constants.k_B.cgs.value)

    def test_t_electron(self, plasma):
        assert plasma.t_electron == 0.9 * plasma.t_rad

    def test_saha_calculation_method(self, plasma):
        assert plasma.calculate_saha == plasma.calculate_saha_lte

pytest 负责收集fixture,收集测试函数,找出哪些测试函数需要哪些fixture,并将fixture 值传递给测试函数执行.

pytest takes care of collecting fixtures, collecting test functions, figuring out which test functions need which fixtures, and passing the fixture values to the test functions for execution.

查看文档了解更多详情:https://docs.pytest.org/en/latest/fixture.html#fixture-parametrize

Check out the docs for more details: https://docs.pytest.org/en/latest/fixture.html#fixture-parametrize

这篇关于在 pytest 中参数化测试类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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