py.test skips test class if constructor is defined

Zdenek Maxa picture Zdenek Maxa · Jan 29, 2014 · Viewed 32.5k times · Source

I have following unittest code running via py.test. Mere presence of the constructor make the entire class skip when running py.test -v -s

collected 0 items / 1 skipped

Can anyone please explain to me this behaviour of py.test?

I am interested in understanding py.test behaviour, I know the constructor is not needed.

Thanks, Zdenek

class TestClassName(object):
    def __init__(self):
       pass

    def setup_method(self, method):
       print "setup_method called"

    def teardown_method(self, method):
       print "teardown_method called"

    def test_a(self):
       print "test_a called"
       assert 1 == 1

    def test_b(self):
       print "test_b called"
       assert 1 == 1

Answer

Matti Lyra picture Matti Lyra · Jan 29, 2014

The documentation for py.test says that py.test implements the following standard test discovery:

  • collection starts from the initial command line arguments which may be directories, filenames or test ids. recurse into directories, unless they match norecursedirs
  • test_*.py or *_test.py files, imported by their package name.
  • Test prefixed test classes (without an __init__ method) [<-- notice this one here]
  • test_ prefixed test functions or methods are test items

So it's not that the constructor isn't needed, py.test just ignores classes that have a constructor. There is also a guide for changing the standard test discovery.