如何在Pytest中控制增量测试用例

时间:2018-05-29 12:20:55

标签: python python-2.7 pytest

@pytest.mark.incremental
class Test_aws():

    def test_case1(self):
        ----- some code here ----
        result = someMethodTogetResult
        assert result[0] == True
        orderID = result[1]

    def test_case2(self):
        result = someMethodTogetResult # can be only perform once test case 1 run successfully.
        assert result == True

    def test_deleteOrder_R53HostZonePrivate(self):
        result = someMethodTogetResult
        assert result[0] == True

当前行为是测试1通过然后测试2运行,如果测试2通过则测试3运行。

我需要的是: 如果test_case 1通过则应运行test_case 3。 test_case 2不应该改变任何行为。有什么想法吗?

3 个答案:

答案 0 :(得分:5)

我猜您正在寻找允许在测试之间设置条件运行依赖关系的pytest-dependency。例如:

import random
import pytest


class TestAWS:

    @pytest.mark.dependency
    def test_instance_start(self):
        assert random.choice((True, False))

    @pytest.mark.dependency(depends=['TestAWS::test_instance_start'])
    def test_instance_stop(self):
        assert random.choice((True, False))

    @pytest.mark.dependency(depends=['TestAWS::test_instance_start'])
    def test_instance_delete(self):
        assert random.choice((True, False))

test_instance_stoptest_instance_delete仅在test_instance_start成功时运行,否则将跳过。但是,由于test_instance_delete不依赖于test_instance_stop,所以无论后一个测试的结果是什么,前者都会执行。多次运行示例测试类以验证所需的行为。

答案 1 :(得分:1)

要补充hoefling's answer,另一种选择是使用pytest-steps执行增量测试。如果您希望在步骤之间共享某种增量状态/中间结果,则这尤其对您有帮助。

但是,它没有实现pytest-dependency之类的高级依赖机制,因此请使用更适合您目标的软件包。

通过pytest-steps,霍夫林的示例将写为:

import random
from pytest_steps import test_steps, depends_on

def step_instance_start():
    assert random.choice((True, False))

@depends_on(step_instance_start)
def step_instance_stop():
    assert random.choice((True, False))

@depends_on(step_instance_start)
def step_instance_delete():
    assert random.choice((True, False))

@test_steps(step_instance_start, step_instance_stop, step_instance_delete)
def test_suite(test_step):
    # Execute the step
    test_step()

编辑:有一个新的“生成器”模式使它更容易:

import random
from pytest_steps import test_steps, optional_step

@test_steps('step_instance_start', 'step_instance_stop', 'step_instance_delete')
def test_suite():
    # First step (Start)
    assert random.choice((True, False))
    yield

    # Second step (Stop)
    with optional_step('step_instance_stop') as stop_step:
        assert random.choice((True, False))
    yield stop_step

    # Third step (Delete)
    with optional_step('step_instance_delete') as delete_step:
        assert random.choice((True, False))
    yield delete_step

检查documentation以获得详细信息。 (顺便说一下,我是这个软件包的作者;))

答案 2 :(得分:0)

您可以使用pytest-ordering软件包使用pytest标记来订购测试。软件包的作者解释了用法here

示例:

@pytest.mark.first
def test_first():
    pass

@pytest.mark.second
def test_2():
    pass


@pytest.mark.order5
def test_5():
    pass