JohnEye
JohnEye

Reputation: 6895

Can pytest run tests within a test class?

I have a bunch of tests which I decided to put within a class, sample code is below:

class IntegrationTests:

    @pytest.mark.integrationtest
    @pytest.mark.asyncio
    async def test_job(self):
        assert await do_stuff()

However, when I try to run the tests: pipenv run pytest -v -m integrationtest, they are not detected at all, where I got the following before moving them to a class:

5 passed, 4 deselected in 0.78 seconds

I now get this:

2 passed, 4 deselected in 0.51 seconds

Why does pytest not detect these tests? Are test classes not supported?

Upvotes: 10

Views: 13374

Answers (4)

pelos
pelos

Reputation: 1876

put the decorator above the class, the class with tests inside is like a group already.

@pytest.mark.smoke1
class TestClass():

Upvotes: 0

user2659575
user2659575

Reputation: 13

To run all the tests under the class, "TestIntegration" you can use:

pytest -k TestIntegration

Upvotes: 1

lmiguelvargasf
lmiguelvargasf

Reputation: 70003

Create a pytest.ini

From the docs:

In case you need to change the naming convention for test files, classes and tests, you can create a file pytest.ini, and set the options python_files, python_classes, and python_functions:

Example:

# content of pytest.ini
# Example 1: have pytest look for "check" instead of "test"
# can also be defined in tox.ini or setup.cfg file, although the section
# name in setup.cfg files should be "tool:pytest"
[pytest]
python_files = check_*.py
python_classes = *Tests
python_functions = *_check

In your case, if you don't want to change the name of the class IntegrationTests, set python_classes to *Tests.

Running tests inside a class

pytest /path/to/test_file_name.py::ClassName

Running a test inside a class

pytest /path/to/test_file_name.py::ClassName::test_name

Upvotes: 8

Gary van der Merwe
Gary van der Merwe

Reputation: 9573

The name of the class needs to start with Test for the pytest discovery to find it.

class TestIntegration:

    @pytest.mark.integrationtest
    @pytest.mark.asyncio
    async def test_job(self):
        assert await do_stuff()

See Conventions for Python test discovery

Upvotes: 14

Related Questions