Calling a Specific Test with pytest

27 Nov 2016

Here's how to call specific unit tests with pytest. I always forget the syntax, so I'm posting it here for reference.

If your test-suite takes a noticeable time to complete, then this can really speed up testing.

tests/file.py:

import unittest

def test_function():
   assert 1 == 1

class TestClass(unittest.TestCase):
    def test_method1(self):
        assert 1 == 1
    def test_method2(self):
        assert 3 == 3

Calling a Specific File

To call a specific file, specify the file's path as the argument to pytest:

py.test tests/file.py

pytest will evaluate test_function, test_method1, and test_method2

Calling a Specific Function in a File

To call a specific unit-test inside that file, you can use the :: separator followed by the method's name:

py.test tests/file.py::test_function

This will run only test_function

Calling a Specific Class

To call tests inside a unittest.TestCase class, you can use the double-colon separator as well:

py.test tests/file.py::TestClass

This will evaluate test_method1 and test_method2

Note

Test classes do not need to inherit from unittest.TestCase to be found via pytest however, pytest is compatible with the unittest module

Calling a Specific Method

To test a specific method of that class use the colon yet again:

py.test tests/file.py::TestClass::test_method1

This will call exclusively test_method1.

Comments !