2015-02-09 82 views
2

我有以下結構:爲什麼不能測試函數看我的py.test夾具?

demo/ 
    conftest.py 
    test_1.py 
    test_2.py 

conftest.py與含量爲:

import pytest 
@pytest.fixture() 

def my_fixture(): 
print "testing"* 

test_1.py含量爲:

def test_my_fixture(my_fixture): 
    my_fixture 

test_2.py含量爲:

import pytest 

@pytest.mark.usefixtures('my_fixture') 
def test_my_fixture(): 
    my_fixture 

當執行測試py.test -s時,我得到NameError爲夾具在test_2.py但不在test_1.py;爲什麼?

這裏是輸出:

================ test session starts ================ 
platform linux2 -- Python 2.7.3 -- py-1.4.26 -- pytest-2.6.4 
plugins: timeout, random 
collected 2 items 

test_1.py testing 
. 
test_2.py testing 
F 

===================== FAILURES ====================== 
__________________ test_my_fixture __________________ 

    def test_my_fixture(): 
>  my_fixture 
E  NameError: global name 'my_fixture' is not defined 

test_2.py:7: NameError 

回答

3

使用pytest.mark.usefixtures標記時,你不需要直接訪問夾具對象(夾具函數的返回值)。

如果您需要訪問fixture對象,請使用fixture-as-function-argument(代碼中的第一種方法)。


在第二代碼中的錯誤的原因是:my_fixture未在功能(未局部變量)中所定義或模塊(未全局變量)中,它不是一個內置對象;但代碼試圖訪問它; NameError

只是不要嘗試訪問my_fixture。夾具對象將爲None,因爲my_fixture函數不返回任何內容。

+0

在這裏,我使用my_fixture作爲一個通用的設置函數,以便在需要時調用我所有的測試。我不需要直接訪問燈具對象。就像http://pytest.org/latest/fixture.html#using-fixtures-from-classes-modules-or-projects – 2015-02-09 14:18:52

+0

@reddymr中的cleandir夾具一樣,如果你用'pytest.mark.usefixtures(' my_fixture')','my_fixture' fixture函數被調用,你可以在輸出中看到。 – falsetru 2015-02-09 14:26:58

+0

當我在test_2.py中使用@ pytest.mark.usefixtures('my_fixture')時,它不會被調用,但在用作測試函數test_my_fixture(my_fixture)的參數時會調用test_.py – 2015-02-09 16:11:07

相關問題