7

Is it possible to run tests from code using pytest? I did find pytest.main, but it's just a command line interface available from code. I would like to pass a test class / function from the code.

In unittest it's possible this way:

from unittest import TestLoader, TestCase, TestResult


class TestMy(TestCase):
    def test_silly(self):
        assert False

runner = TestLoader()
test_suite = runner.loadTestsFromTestCase(TestMy)
test_result = TestResult()
test_suite.run(test_result)
print(test_result)

1 Answer 1

7

Yes it's possible, that way for instance:

from pytest import main


class TestMy:
    def test_silly(self):
        assert False


main(['{}::{}'.format(__file__, TestMy.__name__)])

You can pass any argument to main as if called from command line.

Not the answer you're looking for? Browse other questions tagged or ask your own question.