py.test does not find tests under a class
Solution 1
By convention it searches for
Test prefixed test classes (without an init method)
eg.
# content of test_class.py
class TestClass:
def test_one(self):
x = "this"
assert 'h' in x
def test_two(self):
x = "hello"
assert hasattr(x, 'check')
See the docs here
Solution 2
The accepted answer is not incorrect, but it is incomplete. Also, the link it contains to the documentation no longer works, nor does the updated link in the a comment on that answer.
The current documentation can now be found here. The relevant bits of that doc are:
- ...
- In those directories, search for test_*.py or *_test.py files, imported by their test package name.
- From those files, collect test items:
- ...
- test prefixed test functions or methods inside Test prefixed test classes (without an __init__ method)
The key bit that is missing in the accepted answer is that not only must the class name start with Test and not have an __init__ method, but also, the name of the file containing the class MUST be of one of the forms test_*.py or *_test.py.
Where I got tripped up here, and I assume many others will too, is that I generally name my Python source files containing only a class definition to directly mirror the name of the class. So if my class is named TestClass, I normally put its code in a file named TestClass.py. This won't work with PyTest. To let PyTest do its thing with my test class, I need to name the file for this class test_class.py, test_TestClass.py, TestClass_test.py etc. I chose the last form so that I generally add a '_test' suffix to the file names I'd otherwise choose that need to be named so that PyTest will parse them looking for tests.
Michael
Updated on January 16, 2022Comments
-
Michael over 2 years
I am trying to create test classes that aren't unittest based.
This method under this class
class ClassUnderTestTests: def test_something(self):
cannot be detected and run when you call py.test from the command line or when you run this test in PyCharm (it's on its own module).
This
def test_something(self):
same method outside of a class can be detected and run.
I'd like to group my tests under classes and unless I'm missing something I'm following the py.test spec to do that.
Environment: Windows 7, PyCharm with py.test set as the test runner.