How can I get pytest to ignore Test* classes that don't subclass unittest?

大城市里の小女人 提交于 2020-02-20 09:12:24

问题


I'm trying to get tests for testfixtures passing with pytest, but it keeps trying to collect things that aren't tests:

======================================================= pytest-warning summary ========================================================
WC1 /Users/chris/vcs/git/testfixtures/testfixtures/tests/test_comparison.py cannot collect test class 'TestClassA' because it has a __init__ constructor
WC1 /Users/chris/vcs/git/testfixtures/testfixtures/tests/test_components.py cannot collect test class 'TestComponents' because it has a __init__ constructor
WC1 /Users/chris/vcs/git/testfixtures/testfixtures/tests/test_datetime.py cannot collect test class 'TestTZInfo' because it has a __new__ constructor
WC1 /Users/chris/vcs/git/testfixtures/testfixtures/tests/test_datetime.py cannot collect test class 'TestTZ2Info' because it has a __new__ constructor
cannot collect test class 'TestContainer' because it has a __init__ constructor
cannot collect test class 'TestTZInfo' because it has a __new__ constructor

How can I get pytest to only collect Test* classes that subclass unittest.TestCase?


回答1:


I found this in the Pytest 2.6 release notes:

support nose-style __test__ attribute on modules, classes and functions, including unittest-style Classes. If set to False, the test will not be collected.

This can help if your class is being collected when you don't want it to be, but it doesn't help with the "cannot collect test class because it has a __init__ constructor" warning.




回答2:


Pytest uses glob-style name patterns to collect tests, and the discovery can be customized by the options python_files, python_classes, and python_functions in the configuration file.

I think the defaults are something like this:

[pytest]
python_files=test_*.py
python_classes=Test*
python_functions=test_*

Perhaps you could just customize it not to collect classes by overriding that:

# pytest.ini (or in tox.ini, or in setup.cfg)
[pytest]  # if using setup.cfg, this section name should instead be [tool:pytest]
python_classes=NoThanks

Note: it's not limited to one pattern here, you may specify a list of them.

Classes which inherit unittest.TestCase should still be collected regardless of this option. This is because the unittest framework itself is used to collect those tests.




回答3:


You can also just run pytest with the following flag:

-W ignore::pytest.PytestCollectionWarning


来源:https://stackoverflow.com/questions/42268401/how-can-i-get-pytest-to-ignore-test-classes-that-dont-subclass-unittest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!