pytest "cannot collect test class because it has a __init__" in CI
pytest instantiates test classes itself and cannot do so if the class defines __init__. It emits a collection warning and skips the class, so its tests silently do not run - a real risk when the suite is supposed to be green.
What this error means
pytest prints "PytestCollectionWarning: cannot collect test class 'TestX' because it has a __init__ constructor" and the class's tests are not executed.
tests/test_service.py:5
PytestCollectionWarning: cannot collect test class 'TestService' because it has a
__init__ constructor (from: tests/test_service.py)Common causes
A test class defines __init__
pytest needs to construct the class with no arguments; an __init__ prevents that, so collection is skipped.
A non-test class matched the Test* pattern
A helper class named TestSomething is picked up by collection but has a constructor, triggering the warning.
How to fix it
Use fixtures instead of __init__
Move per-test setup into a fixture or setup_method so the class needs no constructor.
class TestService:
@pytest.fixture(autouse=True)
def setup(self):
self.svc = Service()Rename non-test helper classes
If the class is not a test, rename it so it does not match the Test* collection pattern.
class ServiceHarness: # not collected
def __init__(self):
...How to prevent it
- Do not give test classes an
__init__; use fixtures orsetup_method. - Name non-test helpers so they do not match
Test*. - Treat collection warnings as errors to catch silently-skipped tests.