【问题标题】:how to pytest parametrize whole test flow如何pytest参数化整个测试流程
【发布时间】:2022-12-05 16:10:49
【问题描述】:

我有这样的测试用例测试流程

import pytest


@pytest.mark.parametrize("args", [1, 2])
class TestClass:
    def test_first(self, args):
        print(args)

    def test_second(self, args):
        print(args)

关键是我想按 test_first test_second 的顺序执行它们,然后再执行 test_first、test_second,但是 parametrize 每次执行它们两次。

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    在您的代码中,@pytest.mark.parametrize("args", [1, 2]) 正在装饰 TestClass 类,而不是各个测试方法。这意味着 args 参数将传递给类中的每个测试方法,其值设置为 1 用于第一个测试方法运行,然后设置为 2 用于第二个测试方法运行。

    如果你想以特定顺序执行测试方法,你可以使用 pytest.mark.run 装饰器来指定测试应该运行的顺序。例如:

    import pytest
    
    @pytest.mark.run(order=1)
    def test_first(self, args):
        print(args)
    
    @pytest.mark.run(order=2)
    def test_second(self, args):
        print(args)
    
    @pytest.mark.parametrize("args", [1, 2])
    class TestClass:
        def test_first(self, args):
            test_first(args)
    
        def test_second(self, args):
            test_second(args)
    

    在这段代码中,test_first 和 test_second 是单独的函数,用 pytest.mark.run 装饰器装饰以指定它们的执行顺序。 TestClass 类包含以所需顺序简单调用装饰测试函数的方法。

    请注意,您还可以在 TestClass 类本身上使用 pytest.mark.run 装饰器来指定方法的运行顺序。例如:

    import pytest
    
    @pytest.mark.parametrize("args", [1, 2])
    @pytest.mark.run(order=1)
    class TestClass:
        def test_first(self, args):
            print(args)
    
    @pytest.mark.parametrize("args", [1, 2])
    @pytest.mark.run(order=2)
    class TestClass:
        def test_second(self, args):
            print(args)
    

    在此代码中,TestClass 类本身用pytest.mark.run 修饰以指定其方法的运行顺序。 test_first 和 test_second 方法将以指定的顺序为每个 args 值运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多