簡體   English   中英

具有會話范圍的PyTest fixture不保持db數據的連續性

[英]PyTest fixture with session scope does not maintains continuity of db data

此測試會話正常工作:

from myapp.models import MyModel
@pytest.fixture(scope='function')
def mymodel():
    return G(MyModel)

@pytest.mark.django_db
def test_mymodel_one(mymodel):
    assert MyModel.objects.count() > 0

@pytest.mark.django_db
def test_mymodel_two(mymodel):
    assert MyModel.objects.count() > 0

並產生這個輸出:

========= test session starts =========
tests/myapp/test_pp.py::test_mymodel_one PASSED
tests/myapp/test_pp.py::test_mymodel_two PASSED

但如果我將夾具的范圍更改為'session',則測試2失敗:

========= test session starts =========
tests/myapp/test_pp.py::test_mymodel_one PASSED
tests/myapp/test_pp.py::test_mymodel_two FAILED

========= FAILURES ==============
_________ test_mymodel_two ________
tests/myapp/test_pp.py:85: in test_mymodel_two
    assert MyModel.objects.count() > 0
E   assert 0 > 0

創建的對象從fixture中正確返回(我可以訪問他的值),但不再存儲它。 如何在測試數據庫中使用會話范圍並維護存儲?

我試圖在我的測試包中復制上下文,並且我發現了你暴露的相同情況。

首先,我想與您分享兩頁pytest文檔,在那里我們可以找到這個問題的答案。 文檔 ¹中,方法的組織有點不同,事實上,委托創建夾具的方法在conftest.py中

    # content of conftest.py
    @pytest.fixture(scope="session")
    def smtp(...):
    # the returned fixture value will be shared for
    # all tests needing it

根據您的測試設置,您可以嘗試在conftest模塊中移動mymodel方法。 我試圖在conftest文件中移動我的fixture生成器,但是由於所需的django_db標記,我發現了幾個遍歷問題,這可能與會話范圍沖突(我猜?)。

我還在pytest的示例頁面 ²中找到了另一個幫助,其中廣泛用於不同python模塊的會話范圍,其中指出內部模塊測試不可能訪問在相同級別定義的相同會話范圍。父母的。

    # content of a/conftest.py
import pytest

class DB:
    pass

@pytest.fixture(scope="session")
def db():
    return DB()

# content of a/test_db.py
def test_a1(db):
    assert 0, db  # to show value

# content of a/test_db2.py
def test_a2(db):
    assert 0, db  # to show value

如果

# content of b/test_error.py
def test_root(db):  # no db here, will error out
    pass

將無法通過測試,因為

a目錄中的兩個測試模塊看到相同的db fixture實例,而sister-directory b中的一個測試看不到它。 我們當然也可以在姐妹目錄的conftest.py文件中定義數據庫夾具。 請注意,如果實際需要測試,則僅實例化每個夾具(除非您使用始終在第一次測試執行之前執行的“autouse”夾具)。

在第二個例子中,我注意到生成夾具的方法是為每個測試實例化的,即使范圍設置為會話模塊 ,它也像函數范圍一樣工作

您使用的是哪個版本的pytest?

可以嘗試從mympodel方法從當前模塊移動到conftest模塊嗎?

暫無
暫無

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

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