pytest -- skip

pytest skip的使用

1. @pytest.mark.skip装饰器

跳过某个测试用例最简单的方法,直接挂这个装饰器即可,且可设置一个参数reason,表明跳过的原因

@pytest.mark.skip(reason="I don't want to exec")
def test_skip():
  ...

2. pytest.skip

测试过程中,需要强制跳过后续的测试步骤,可使用此方法,同样有一个reason参数

def test_skip():
  if 1 ==1:
    pytest.skip('just show')

这个方法有一个bool参数,allow_module_level(默认值False),可用来表明是否在模块中使用pytest.skip,如果为True,则跳过模块剩余部分
比如,当某进程启动的时候,测试这个模块

if 'pro' not in os.popen('ps -ef| grep pro | grep -v grep').read():
  pytest.skip('skip the modle, reason ...', allow_module_level=True) 

以上例子,如果不设置allow_module_level=True,那么就会继续执行模块下的内容,尽管满足了if条件。另外,在用例中使用此参数allow_module_level,不会生效。

3. @pytest.mark.skipif装饰器

如果我们满足某些条件,再跳过用例,可使用此装饰器

@pytest.mark.skipif(1==1, reason='ba la la ~')
def test_skipif():
  ...

特别用法:我们可以在一个文件中定义所有的执行条件,然后在测试模块中调用,当满足某个执行条件的时候,则跳过,如:

# skip_con.py
# -*- coding:utf8 -*-
import os
import pytest

skip_con1 = pytest.mark.skipif('pro' not in os.popen('ps -ef| grep pro | grep -v grep').read(),
                               reason='pro not exist')

skip_con2 = pytest.mark.skipif('pro2' not in os.popen('ps -ef| grep pro2 | grep -v grep').read(),
                               reason='pro2 not exist')
from skip_con import skip_con1

# 满足skip_con1条件,则跳过
@skip_con1
def test_s():
  ...

注意

  1. 当用例有多个跳过条件的时候,只要满足一个,则就跳过
  2. 没有pytest.skipif()方法

4. pytest.importorskip方法

顾名思义,当导入某个模块失败的时候,则跳过后续部分的执行,可以设置这个模块的最小版本,同样可传入参数reason

con = pytest.importorskip('requests',  minversion='2.20')

@con
def test_1():
  ...
def test_1():
  pytest.importorskip('requests',  minversion='2.20')
  ...

总结

跳过类

在类上应用@pytest.mark.skip()或者@pytest.mark.skipif()

@pytest.mark.skip('不执行这个类')
class TestMyCls:
  def test_3():
    ...

跳过模块

1. 在模块中定义变量pytestmark = pytest.mark.skip('skip the model')

import pytest
pytestmark = pytest.mark.skip('skip the model')
def test_1():
  assert 1==1

def test_2():
  assert 1==2

上边测试文件,会跳过两个测试用例

2. 使用pytest.skip, 参数allow_module_level=True

import pytest

pytest.skip('test', allow_module_level=True)

def test_1():
  assert 1==1

def test_2():
  assert 1==2

上边测试文件,会跳过两个测试用例

跳过目录或文件

在conftest.py中配置collect_ignore_glob项即可

collect_ignore_glob = ['test_**.py', 'testcase/testsub']
pytest.mark.skip pytest.mark.skipif pytest.skip pytest.importorskip conftest.py
用例 @pytest.mark.skip @pytest.mark.skipif() pytest.skip('') pytest.importorskip("selenium-python", reason="当前模块导入失败") /
@pytest.mark.skip() @pytest.mark.skipif() / / /
模块 pytestmark = pytest.mark.skip() pytestmark = pytest.mark.skipif() pytest.skip(allow_module_level=True) pytestmark = pytest.importorskip() /
文件或目录 / / / / collect_ignore_glob

你可能感兴趣的:(pytest -- skip)