当前设置
使用
- pytest 3.4.1
- python 3.5 及以上
这是我在tests/test_8_2_openpyxl.py
下的测试用例
class TestSomething(unittest.TestCase):
def setUp(self):
# do setup stuff here
def tearDown(self):
# do teardown stuff here
def test_case_1(self):
# test case here...
我使用unittest
风格来编写我的测试用例。我使用 pytest 来运行测试。
我还按照 unittest
约定设置和拆卸函数
我运行测试的命令行变成了
pytest -s -v tests/test_8_2_openpyxl.py
它按预期工作
我想要什么
当我有时调试时,我希望能够使用某种命令行选项轻松地关闭设置或拆卸或同时关闭这两者
pytest -s -v tests/test_8_2_openpyxl.py --skip-updown
为了跳过拆解和设置
pytest -s -v tests/test_8_2_openpyxl.py --skip-setup
为了跳过设置
pytest -s -v tests/test_8_2_openpyxl.py --skip-teardown
为了跳过拆解
我尝试过但没有奏效的方法
已尝试 sys.argv
我试过使用sys.argv
class TestSomething(unittest.TestCase):
def setUp(self):
if '--skip-updown' in sys.argv:
return
# do setup stuff here
然后
`pytest -s -v tests/test_8_2_openpyxl.py --skip-updown
这没有用,我的错误信息是
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: argument --skip-updown: expected one argument
尝试过 sys.argv
我试过使用sys.argv
class TestSomething(unittest.TestCase):
def setUp(self):
if '--skip-updown' in sys.argv:
return
# do setup stuff here
然后
pytest -s -v tests/test_8_2_openpyxl.py --skip-updown
这没有用,我的错误信息是
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: argument --skip-updown: expected one argument
尝试了 conftest.py 和 config.getoption
我在项目根目录下设置了一个conftest.py
def pytest_addoption(parser):
parser.addoption("--skip-updown", default=False)
@pytest.fixture
def skip_updown(request):
return request.config.getoption("--skip-updown")
然后
class TestSomething(unittest.TestCase):
def setUp(self):
if pytest.config.getoption("--skip-updown"):
return
# do setup stuff here and then
pytest -s -v tests/test_8_2_openpyxl.py --skip-updown
然后我得到
usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: argument --skip-updown: expected one argument
我尝试和工作但不理想的东西
尝试了 conftest 和 config.getoption 但这次声明 --skip-updown=True
除了这次在我的命令行中我声明了 --skip-updown=True
pytest -s -v tests/test_8_2_openpyxl.py --skip-updown=True
我的问题
这非常接近我想要的,但我希望不必声明值 --skip-updown=True
或者也许我一开始就做错了,使用 sys.argv
有更简单的方法。
最佳答案
修复添加选项
:
def pytest_addoption(parser):
parser.addoption("--skip-updown", action='store_true')
请参阅 https://docs.python.org/3/library/argparse.html 上的文档
Or maybe I am doing it all wrong in the first place and there's an easier way using sys.argv.
不,您正在做的是正确且唯一的方法。
关于python - 如何在使用 pytest 和命令行选项时跳过 unittest 案例中的设置和拆卸?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49568798/