Python 如何使用pytest运行与生产代码位于同一文件中的测试?

Python 如何使用pytest运行与生产代码位于同一文件中的测试?,python,testing,pytest,Python,Testing,Pytest,我知道这违反了Python生产代码的任何要求/假设:在某些情况下,能够在同一个文件中定义生产和测试代码可能会有所帮助(例如,在简单脚本的情况下)。那么,如何使用pytest运行文件中的所有或特定测试 编辑-针对我的特定用例的解决方案: 中的文件结构: pytest.ini的内容: [pytest] python_files = script_with_tests.py script\u与\u tests.py的内容: import pytest # this is not required,

我知道这违反了Python生产代码的任何要求/假设:在某些情况下,能够在同一个文件中定义生产和测试代码可能会有所帮助(例如,在简单脚本的情况下)。那么,如何使用
pytest
运行文件中的所有或特定测试

编辑-针对我的特定用例的解决方案:

中的文件结构:

pytest.ini的内容

[pytest]
python_files = script_with_tests.py
script\u与\u tests.py的内容

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

def test_always_pass():
    pass

if __name__ == "__main__":
    main()
pytest
中的调用

如本节所述:

您可以轻松指示
pytest
从每个Python文件中发现测试:

# content of pytest.ini
[pytest]
python_files = *.py
但是,许多项目将有一个
setup.py
,它们不希望导入该文件。此外,可能只有特定python版本的文件才可导入。对于这种情况,您可以通过在
conftest.py
文件中列出文件来动态定义要忽略的文件:

# content of conftest.py
import sys

collect_ignore = ["setup.py"]
if sys.version_info[0] > 2:
   collect_ignore.append("pkg/module_py2.py")
# content of pytest.ini
[pytest]
python_files = *.py
# content of conftest.py
import sys

collect_ignore = ["setup.py"]
if sys.version_info[0] > 2:
   collect_ignore.append("pkg/module_py2.py")