2017-04-21 127 views
0

如何只需运行测试,而在py.test执行父脚本?目前,笔者从目录PROJECT_DIR运行命令pytest -v,这终于运行script.py和试验进行到底。理想情况下只需要运行测试。这里是我当前的目录设置:执行仅测试使用pytest不执行父脚本

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导入为模块。但我始终认为必须有一种方法来避免这种情况,直接执行测试。

回答

2

导入一个Python模块执行所有的顶级代码在里面。

你应该有一个if __name__ == '__main__':你的代码,所以当你运行你的脚本(而不是当你导入)它只是执行 - 例如见this answer了解详情。

0

尝试Ignore paths during test collection

pytest -v --ignore=script.py 

或者运行pytest上的目录:

pytest -v test/ 

Specifying tests/selecting tests

+0

没有工作。仍然表现相同的方式。谢谢! – JeeYem

+0

您可以在目录 –

+0

运行pytest仍执行主脚本。不知道'pytest -v'与'pytest -v test /'有什么不同,因为我们这里只有一个测试目录。要明确,主脚本在作为模块导入测试脚本时会被执行。 – JeeYem

0

如何运行pytest test/? 只是要清楚: https://docs.pytest.org/en/latest/usage.html#specifying-tests-selecting-tests

pytest somepath  # run all tests below somepath 
+0

含义'pytest test_script.py'为我的例子?这与pytest -v没有什么不同(python除外),因为pytest使用发现规则来做同样的事情。 – JeeYem

+0

所以..你想测试一些脚本行为,而不执行它?那你怎么测试它? :)如果可能,我想你应该向我们展示'test_script.py'和'scripts.py'。 – marcinowski

+0

我不确定是否可能。现在添加一个示例。谢谢! – JeeYem