2017-04-21 105 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