How to Fix a PytestCollectionWarning about WebTest’s TestApp Class

Honk away, test warning goose

Here’s a small warning I’ve come across a couple of times, and how to fix it with a niche pytest feature.

If you have some tests using WebTest and run them with pytest, you might see this warning at the end of your test run:

$ pytest
...
========================== warnings summary ===========================
venv/lib/python3.8/site-packages/webtest/app.py:88
  /.../site-packages/webtest/app.py:88: PytestCollectionWarning: cannot collect test class 'TestApp' because it has a __init__ constructor (from: test_example.py)
    class TestApp(object):

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

This happens because pytest tries to collect the TestApp class as a test class, but it finds it is incompatible. pytest supports tests in plain classes, and the default glob pattern to match such classes is Test*, which TestApp matches. But such test classes can’t have an __init__() method.

The simplest solution is to mark the class as not to be collected as tests. This can be done by setting the __test__ = False on the class, a somewhat hidden pytest feature that was copied from the nose test runner. This is probably best done in your conftest.py or similar, since it only needs doing once:

from webtest import TestApp


# Prevent pytest from trying to collect webtest's TestApp as tests:
TestApp.__test__ = False

With that, your tests should collect without error - but it’s up to you to make them pass :)

I’ve submitted a pull request to WebTest, so hopefully that is merged and this isn’t necessary with future versions.

Fin

I hope this helps you with using pytest,

—Adam


Read my book Boost Your Git DX to Git better.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: