簡體   English   中英

pypytest參數

[英]Parametrize pytest fixture

據我從有關pytest固定裝置參數化的文檔中了解到的-它使用給定的參數創建固定裝置的副本,因此調用需要此固定裝置具有不同副本的每個測試。

我的需求有些不同。 假設有一個燈具:

@pytest.fixture
def sample_foo():
    return Foo(file_path='file/path/test.json')

def test1(sample_foo):
    pass

def test2(sample_foo):
    pass

問題是測試test1test2需要類Foo的相同實例,但文件file_path值不同

所以目前我這樣做:

def build_foo(path):
   return Foo(file_path=path)

 def test1():
     sample_foo = build_foo('file/path/some.json')

 def test2():
     sample_foo = build_foo('file/path/another.json')

這看起來有點代碼重復。 我可以為每個文件創建一個單獨的裝置,但是看起來更糟。 看起來每個測試將需要它自己的唯一文件,因此也許可以通過查看請求固定裝置的測試函數的名稱來找出文件名來解決。 但這並不能保證。

您需要夾具參數

可以對夾具功能進行參數設置,在這種情況下,每次執行一組相關測試(即,依賴於該夾具的測試)時,它們將被多次調用。

def build_foo(path):
   return Foo(file_path=path)

@pytest.fixture(params=["file/path/some.json", "file/path/another.json"])
def file_path(request):
    return request.param

def test(file_path):    
    sample_foo = build_foo(file_path) 

也許你可以直接

def test(file_path):    
    sample_foo = Foo(file_path) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM