Search code examples
pythonunit-testingpytest

pytest equivalent of unittest.main()


I can run in debug mode a unit test test_foo.py by simplying pressing F5 in my IDE of choice:

# test_foo_module.py
import unittest

class TestFoo(unittest.TestCase):

    def test_foo(self):
        self.assertTrue(True)

if __name__ == '__main__':
    unittest.main()

I'd have thought the pytest exact equivalent to be:

# test_foo_module.py
import pytest

def test_foo():
    assert True

if __name__ == '__main__':
    pytest.main()

But pytest.main() scans the whole project directory. I want to execute only this module in debug mode.


Solution

  • pytest.main optionally takes pytest CLI arguments (args) as its first argument (if not specified, it defaults to sys.argv). So, giving the current file name via args should do it,

    # test_foo_module.py
    import pytest
    
    def test_foo():
        assert True
    
    if __name__ == '__main__':
        pytest.main([__file__])