如何於測試中使用暫存目錄和檔案

裝置 tmp_path

你可以使用裝置 tmp_path,它會提供每個測試函式獨有的暫存目錄。

tmp_pathpathlib.Path 物件。以下是範例測試用法

# content of test_tmp_path.py
CONTENT = "content"


def test_create_file(tmp_path):
    d = tmp_path / "sub"
    d.mkdir()
    p = d / "hello.txt"
    p.write_text(CONTENT, encoding="utf-8")
    assert p.read_text(encoding="utf-8") == CONTENT
    assert len(list(tmp_path.iterdir())) == 1
    assert 0

執行此程式碼會產生一個通過的測試,但最後一行 assert 0 除外,我們使用它來查看值

$ pytest test_tmp_path.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-8.x.y, pluggy-1.x.y
rootdir: /home/sweet/project
collected 1 item

test_tmp_path.py F                                                   [100%]

================================= FAILURES =================================
_____________________________ test_create_file _____________________________

tmp_path = PosixPath('PYTEST_TMPDIR/test_create_file0')

    def test_create_file(tmp_path):
        d = tmp_path / "sub"
        d.mkdir()
        p = d / "hello.txt"
        p.write_text(CONTENT, encoding="utf-8")
        assert p.read_text(encoding="utf-8") == CONTENT
        assert len(list(tmp_path.iterdir())) == 1
>       assert 0
E       assert 0

test_tmp_path.py:11: AssertionError
========================= short test summary info ==========================
FAILED test_tmp_path.py::test_create_file - assert 0
============================ 1 failed in 0.12s =============================

預設情況下,pytest 會保留最後 3 次 pytest 呼叫的暫存目錄。透過設定基本暫存目錄為每個並行執行獨有,可以支援相同測試函式的並行呼叫。有關詳細資訊,請參閱 暫存目錄位置和保留

裝置 tmp_path_factory

裝置 tmp_path_factory 是會話範圍的裝置,可從任何其他裝置或測試建立任意暫存目錄。

例如,假設你的測試套件需要一個大型磁碟映像,且會以程式化方式產生。你可以每會話產生一次,以節省時間,而不是為每個使用它的測試計算相同的映像到其自己的 tmp_path

# contents of conftest.py
import pytest


@pytest.fixture(scope="session")
def image_file(tmp_path_factory):
    img = compute_expensive_image()
    fn = tmp_path_factory.mktemp("data") / "img.png"
    img.save(fn)
    return fn


# contents of test_image.py
def test_histogram(image_file):
    img = load_image(image_file)
    # compute and test histogram

有關詳細資訊,請參閱 tmp_path_factory API

固定裝置 tmpdirtmpdir_factory

固定裝置 tmpdirtmpdir_factory 類似於 tmp_pathtmp_path_factory,但使用/傳回舊版的 py.path.local 物件,而非標準 pathlib.Path 物件。

注意

現在建議使用 tmp_pathtmp_path_factory

為了幫助現代化舊的程式碼庫,可以使用停用 legacypath 外掛程式來執行 pytest

pytest -p no:legacypath

這會觸發使用舊路徑的測試錯誤。它也可以永久設定為設定檔中 addopts 參數的一部分。

請參閱 tmpdir tmpdir_factory API 以取得詳細資料。

暫時目錄位置和保留

暫時目錄預設建立為系統暫時目錄的子目錄。基本名稱會是 pytest-NUM,其中 NUM 會隨著每次測試執行而遞增。預設會移除超過 3 個暫時目錄的項目。此行為可以使用 tmp_path_retention_counttmp_path_retention_policy 來設定。

使用 --basetemp 選項將會在每次執行前移除目錄,這表示只有最近一次執行的暫存目錄會被保留。

您可以這樣覆寫預設的暫存目錄設定

pytest --basetemp=mydir

警告

mydir 的內容將會被完全移除,因此請務必僅將目錄用於此目的。

在使用 pytest-xdist 在本機上分發測試時,會小心自動設定子程序的 basetemp 目錄,以便所有暫存資料都落在單一測試執行暫存目錄之下。