在不执行父脚本的情况下仅使用pytest执行测试
Executing only tests using pytest without executing parent script
如何只 运行 测试而不执行 py.test 中的父脚本?目前我 运行 从目录 Project_dir 命令 pytest -v
,这个 运行s script.py 最后测试.理想情况下,只有测试需要 运行。这是我当前的目录设置:
Project_dir
script.py
test
test_script.py
script.py
def add(a,b):
added = a + b
return added
x = add(1,3)
print x, 'yup'
test_script.py
import script
def test_add():
assert script.add(3,4) == 7
工作目录: Project_dir
命令: pytest -vs
========================================== test session starts ==========================================
platform darwin -- Python 2.7.10, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /usr/bin/python
cachedir: .cache
rootdir: **, inifile:
plugins: cov-2.4.0
collecting 0 items
Sum is 4
collected 1 items
test/test_script.py::test_add PASSED
======================================= 1 passed in 0.00 seconds ========================================
Sum is 4
显示 script.py 完全执行而不仅仅是测试。它发生在 script.py 作为模块导入时。但是我一直在想一定有办法避免这种情况,直接执行测试。
尝试Ignore paths during test collection
pytest -v --ignore=script.py
或运行目录上的pytest:
pytest -v test/
运行pytest test/
怎么样?
只是为了说清楚:
https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests
pytest somepath # run all tests below somepath
在 Python 中导入模块会执行其中的所有顶级代码。
您应该将您的代码放在 if __name__ == '__main__':
中,这样它只会在您 运行 您的脚本时执行(而不是在您导入它时) - 参见例如this answer 了解详情。
如何只 运行 测试而不执行 py.test 中的父脚本?目前我 运行 从目录 Project_dir 命令 pytest -v
,这个 运行s script.py 最后测试.理想情况下,只有测试需要 运行。这是我当前的目录设置:
Project_dir
script.py
test
test_script.py
script.py
def add(a,b):
added = a + b
return added
x = add(1,3)
print x, 'yup'
test_script.py
import script
def test_add():
assert script.add(3,4) == 7
工作目录: Project_dir
命令: pytest -vs
========================================== test session starts ==========================================
platform darwin -- Python 2.7.10, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 -- /usr/bin/python
cachedir: .cache
rootdir: **, inifile:
plugins: cov-2.4.0
collecting 0 items
Sum is 4
collected 1 items
test/test_script.py::test_add PASSED
======================================= 1 passed in 0.00 seconds ========================================
Sum is 4
显示 script.py 完全执行而不仅仅是测试。它发生在 script.py 作为模块导入时。但是我一直在想一定有办法避免这种情况,直接执行测试。
尝试Ignore paths during test collection
pytest -v --ignore=script.py
或运行目录上的pytest:
pytest -v test/
运行pytest test/
怎么样?
只是为了说清楚:
https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests
pytest somepath # run all tests below somepath
在 Python 中导入模块会执行其中的所有顶级代码。
您应该将您的代码放在 if __name__ == '__main__':
中,这样它只会在您 运行 您的脚本时执行(而不是在您导入它时) - 参见例如this answer 了解详情。