如何通过pytest命令行选项跳过unittest测试用例的setup与teardown?
如何通过Pytest命令行选项跳过Unittest的setUp/tearDown
嘿,刚好碰到过类似的需求!你用Unittest风格写测试,想通过Pytest的命令行参数跳过setUp和tearDown,这里有个简单可行的方案:
步骤1:添加自定义命令行选项
在你的项目根目录创建一个conftest.py文件,用来定义Pytest的自定义命令行参数:
def pytest_addoption(parser): parser.addoption( "--skip-setup-teardown", action="store_true", default=False, help="跳过Unittest测试类中的setUp和tearDown方法" )
步骤2:修改测试类判断选项
在你的测试文件tests/test_8_2_openpyxl.py里,修改setUp和tearDown方法,读取命令行参数来决定是否执行原有逻辑:
import unittest import pytest class TestSomething(unittest.TestCase): def setUp(self): # 获取命令行传入的跳过标记 skip_setup = pytest.config.getoption("--skip-setup-teardown") if skip_setup: return # 直接返回,跳过原有setup逻辑 # 原来的setup代码保留在这里 # do setup stuff here print("执行setUp逻辑...") def tearDown(self): skip_teardown = pytest.config.getoption("--skip-setup-teardown") if skip_teardown: return # 直接返回,跳过原有teardown逻辑 # 原来的teardown代码保留在这里 # do teardown stuff here print("执行tearDown逻辑...") def test_case_1(self): # test case here... assert 1 == 1
步骤3:带选项执行测试
现在你只需要在执行命令时加上--skip-setup-teardown参数,就能跳过setUp和tearDown了:
pytest -s -v --skip-setup-teardown tests/test_8_2_openpyxl.py
注意事项
- 你的Pytest版本3.4.1完全支持
pytest_addoption和pytest.config.getoption,Python3.5+也没有兼容性问题 - 如果不需要跳过,直接运行原来的命令就行,不会影响正常测试流程
内容的提问来源于stack exchange,提问作者Kim Stacks
相关产品推荐
相关产品推荐

