cannot collect test class 'TestMain' because it has a __init__ constructor (from: Login.py)

Viewed 2057

I am trying to run pytest from cmd and I'm getting this result when I execute pytest Login.py:

================================================== warnings summary ===================================================
C:\automation\test\test.py:36
  C:\automation\test\test.py:36: PytestCollectionWarning: cannot collect test class 'TestMain' because it has a __init__ constructor (from: Login.py)
    class TestBase():

-- Docs: https://docs.pytest.org/en/latest/warnings.html
================================================= 1 warning in 59.69s =================================================

Inside Login.py, I have an import and I think that might be the problem, but I need that import for the test. Does anyone know how to fix this?

3 Answers

Collecting Tests

"Collecting tests" in pytest-speak means discovering/deciding which functions to run as test cases. PyTest discovers tests according to a small set of rules including the following:

test prefixed test functions or methods inside Test prefixed test classes (without an __init__ method)

The Warning

This PytestCollectionWarning is pointing out that the member methods of TestMain won't be treated as test cases since the class has an __init__ method. It's a warning because you might really want those to be used as test cases but mistakenly added an __init__ method. However, it may be that you just have a class that starts with the word Test and so the warning is a false alarm.

Solutions

The solution depends on what you are aiming for:

  • If TestMain is meant to be a collection of tests then you should remove the __init__ method as @fstamour suggested (or look for an alternative as @EscBlack is suggesting).
  • If TestMain is not a collection of tests but you do want/need its name to start with "Test", then there are ways to filter the warning explicitly.
  • If TestMain is not a collection of tests and you really don't need its name to start with "Test" anyway, then just rename it. This was the solution for me when I had made a dummy class called TestData to use inside some test cases. Changing the name to MyData got rid of the warning. (Since you are running pytest Login.py, I'm guessing that Login.py contains both implementation and tests which makes it all the more likely to have non-test classes with names that start with "Test".)
Related