Chicrala
Chicrala

Reputation: 1054

How to ask Pytest to run a specific test in a python script?

If I have multiple tests running in a script, e.g.:

import pytest

@pytest.mark.parametrize("test_input,expected", [
    ("3+5", 8),
    ("2+4", 6),
    ("6*9", 42),
])
def test_eval(test_input, expected):
    assert eval(test_input) == expected

@pytest.mark.parametrize('test_input,expected', [
        (1,1),
        (2,2),
        (2,3),
        ])
def test_equal(test_input,expected):
    assert test_input == expected


if __name__ == '__main__':
    '''
    Test Zone!
    '''
    #executing the tests
    pytest.main([__file__]) 

How can I use the last line pytest.main([__file__]) to run one of the tests at a time instead of running all of them at once?

Upvotes: 3

Views: 5446

Answers (1)

eijen
eijen

Reputation: 439

Using pytest.main() acts like calling pytest from the command line according to the pytest documentation. You can pass in commands and arguments to this, allowing you to use the -k flag to specify tests via a keyword expression:

pytest.main(["-k", "test_func"])

You can also you specify tests via node id:

pytest.main(["test_mod.py::test_func"])

Upvotes: 5

Related Questions