Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest: run test from code, not from command line

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)
like image 811
Stan Prokop Avatar asked Apr 21 '17 08:04

Stan Prokop


People also ask

How do I run a specific test in pytest?

Running pytest We can run a specific test file by giving its name as an argument. A specific function can be run by providing its name after the :: characters. Markers can be used to group tests. A marked grouped of tests is then run with pytest -m .

How do I bypass pytest?

Skipping a test The simplest way to skip a test is to mark it with the skip decorator which may be passed an optional reason . It is also possible to skip imperatively during test execution or setup by calling the pytest. skip(reason) function.

How do I run a test file in Python?

If you're using the PyCharm IDE, you can run unittest or pytest by following these steps: In the Project tool window, select the tests directory. On the context menu, choose the run command for unittest . For example, choose Run 'Unittests in my Tests…'.

Can you run pytest in Jupyter notebook?

nose. tools offers functions for testing assertions, e.g. assert_equal() . These functions are callable in a Jupyter notebook (REPL) and produce a detailed output if an error is raised.


1 Answers

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.

like image 165
Cyrille Pontvieux Avatar answered Sep 24 '22 02:09

Cyrille Pontvieux