簡體   English   中英

為什么我只能通過在測試腳本中使用夾具(來自 pytest)來獲取函數作為返回值?

[英]Why do I only get a function as a return value by using a fixture (from pytest) in a test script?

我想為我的代碼編寫測試函數並決定使用 pytest。 我查看了本教程: https : //semaphoreci.com/community/tutorials/testing-python-applications-with-pytest

我的真實代碼涉及另一個腳本,我寫的,所以我做了一個例子,它也產生了同樣的問題,但不依賴於我的其他代碼。

@pytest.fixture()
def example():
    value = 10
    return value

def test_value(example):
    print(example)
    assert(example == 10)

test_value(example)

當我用這個玩具示例運行我的腳本時,打印返回一個函數:

<0x0391E540 處的功能示例>

並且斷言失敗。

如果我嘗試用括號調用 example() ,我會得到:

失敗:直接調用夾具“example_chunks”。 Fixtures 不是直接調用的,而是在測試函數請求它們作為參數時自動創建的。 有關固定裝置的更多信息,請參閱https://docs.pytest.org/en/stable/fixture.html ,以及https://docs.pytest.org/en/stable/deprecations.html#calling-fixtures-directly了解如何更新您的代碼。

我敢肯定,我在這里遺漏了一些重要的東西,但搜索谷歌對我沒有幫助,這就是為什么我希望這里有人可以提供一些幫助。

  1. 從腳本中刪除此行
test_value(example)
  1. 使用pytest file.py運行您的腳本文件

Fixtures 會被 pytest 自動解析

在您的示例中,您直接運行代碼,而夾具只是簡單的函數

暫無
暫無

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

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