Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run tests which are located in same file as production code with pytest?

Tags:

I know this violates any best practices which require/assume proper packaging of Python production code: In some cases it might be helpful to beeing able to define production and test code in the same file (e.g. in case of simple scripts). How can I run all or specific tests in a file with pytest then?

EDIT - The solution for my particular use case:

file structure in <root>:

pytest.ini
scrip_with_tests.py

content of pytest.ini:

[pytest]
python_files = script_with_tests.py

content of script_with_tests.py:

import pytest  # this is not required, works without as well

def test_always_pass():
    pass

if __name__ == "__main__":
    main()

pytest invocation in <root>:

pytest script_with_tests.py
like image 344
thinwybk Avatar asked Jul 09 '18 10:07

thinwybk


1 Answers

As stated in the Customizing test collection section:

You can easily instruct pytest to discover tests from every Python file:

# content of pytest.ini
[pytest]
python_files = *.py

However, many projects will have a setup.py which they don’t want to be imported. Moreover, there may files only importable by a specific python version. For such cases you can dynamically define files to be ignored by listing them in a conftest.py file:

# content of conftest.py
import sys

collect_ignore = ["setup.py"]
if sys.version_info[0] > 2:
   collect_ignore.append("pkg/module_py2.py")
like image 167
hoefling Avatar answered Oct 04 '22 18:10

hoefling