如何在使用pytest和命令行选项时跳过unittest情况下的设置和拆卸?

时间:2018-03-30 05:19:24

标签: python pytest python-unittest

当前设置

使用

  • 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更简单。

1 个答案:

答案 0 :(得分:2)

修复addoption

def pytest_addoption(parser):
    parser.addoption("--skip-updown", action='store_true')

请参阅https://docs.python.org/3/library/argparse.html

上的文档
  

或许我首先做错了,使用sys.argv更容易。

不,你正在做的是正确和唯一的方式。

相关问题