pytest测试用例编写----跳过测试用例(Skipping Tests)

@pytest.mark.skip(reason='misunderstood the API')
def test_unique_id_1():
    """Calling unique_id() twice should return different numbers."""
    id_1 = tasks.unique_id()
    id_2 = tasks.unique_id()
    assert id_1 != id_2

内置标记skip跳过某个测试

除了上面的方法,还可以使用pytest.skip(reason)在测试运行过程中,跳过单个测试用例或整个模块:

跳过整个模块的例子,直接在文件中设置一个条件,当条件满足时,使用 pytest.skip('xxx', allow_module_level = True)跳过整个模块,allow_module_level参数必须为True:
if True: pytest.skip('skip all module', allow_module_level = True)
@pytest.mark.skipif(tasks.__version__ < '0.2.0',
                    reason='not supported until version 0.2.0')
def test_unique_id_1():
    """Calling unique_id() twice should return different numbers."""
    id_1 = tasks.unique_id()
    id_2 = tasks.unique_id()
    assert id_1 != id_2

内置标记skipif(要给要跳过的测试添加条件)跳过某个测试

注:-rs(reason) 可以查看跳过的原因

使用下面方法可以在多个模块中共享skipif信息:

 你还使用以下方法可以跳过一个类:

 pytest还继承了历史版本中的pytestmark属性:使用它在某些条件下跳过一个类或者一个模块的所有测试用例,pytest.mark.skipif()指定跳过条件。

下面例子中语句pytestmark = pytest.mark,skipif(1 == 1,reason="verigy whether it can skip this module")会起作用,pytest会跳过整个模块的执行:

 执行结果如下,所有用例被跳过:

 

 如果你想跳过多个文件或整个目录,你可以改变pytest的“用例搜索策略”,在配置文件中设置跳过那些文件或目录

  还可以使用pytest.importorskip来跳过依赖包不能正常import的模块:

 

在不同的情况下,如何在模块内跳过执行该模块的方法总结:

@pytest.mark.xfail(tasks.__version__ < '0.2.0',
                   reason='not supported until version 0.2.0')
def test_unique_id_1():
    """Calling unique_id() twice should return different numbers."""
    id_1 = tasks.unique_id()
    id_2 = tasks.unique_id()
    assert id_1 != id_2


@pytest.mark.xfail()
def test_unique_id_is_a_duck():
    """Demonstrate xfail."""
    uid = tasks.unique_id()
    assert uid == 'a duck'


@pytest.mark.xfail()
def test_unique_id_not_a_duck():
    """Demonstrate xpass."""
    uid = tasks.unique_id()
    assert uid != 'a duck'

内置标记xfail(expected to fail)预期会失败

猜你喜欢

转载自www.cnblogs.com/gmjianchi/p/12931008.html