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
As stated in the Customizing test collection section:
You can easily instruct
pytestto discover tests from every Python file:# content of pytest.ini [pytest] python_files = *.pyHowever, many projects will have a
setup.pywhich 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 aconftest.pyfile:# content of conftest.py import sys collect_ignore = ["setup.py"] if sys.version_info[0] > 2: collect_ignore.append("pkg/module_py2.py")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With