pytest 核心功能-在測試中使用臨時目錄和文件

2022-03-29 17:25 更新

tmp_path fixture

您可以使用?tmp_path fixture?,它將為測試調(diào)用提供一個在基本臨時目錄中創(chuàng)建的惟一臨時目錄。

?Tmp_path?是一個?pathlib.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)
    assert p.read_text() == CONTENT
    assert len(list(tmp_path.iterdir())) == 1
    assert 0

運行它會導(dǎo)致測試通過,除了我們用來查看值的最后一個 ?assert 0? 行:

$ pytest test_tmp_path.py
=========================== test session starts ============================
platform linux -- Python 3.x.y, pytest-7.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)
        assert p.read_text() == 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 =============================

tmp_path_factory fixture

?tmp_path_factory?是一個會話范圍的?fixture?,可用于從任何其他?fixture?或測試創(chuàng)建任意臨時目錄。

假設(shè)您的測試套件需要在磁盤上生成一個大的映像,這個映像是程序生成的。為每個測試計算相同的圖像,并將其使用到自己的?tmp_path?中,您可以每次生成一個圖像,以節(jié)省時間:

# 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

tmpdir和tmpdir_factory fixture

?tmpdir ?和 ?tmpdir_factory fixtures?類似于 ?tmp_path ?和 ?tmp_path_factory?,但使用/返回舊版 ?py.path.local? 對象而不是標(biāo)準(zhǔn) ?pathlib.Pat?h 對象?,F(xiàn)在,更喜歡使用 ?tmp_path ?和 ?tmp_path_factory?。

默認(rèn)的基本臨時目錄

默認(rèn)情況下,臨時目錄作為系統(tǒng)臨時目錄的子目錄創(chuàng)建?;久Q將是?pytest-NUM?,其中?NUM?將隨著每次測試運行而遞增。此外,超過3個臨時目錄的條目將被刪除。

當(dāng)前不能更改條目的數(shù)量,但是使用?--basetemp?選項將在每次運行之前刪除目錄,這意味著只有最近運行的臨時目錄將被保留。

你可以像這樣覆蓋默認(rèn)的臨時目錄設(shè)置:

pytest --basetemp=mydir

?mydir的內(nèi)容將被完全刪除,因此請確保僅將目錄用于此目的。

使用 ?pytest-xdist? 在本地機器上分發(fā)測試時,注意為子進程自動配置一個 ?basetemp目錄,以便所有臨時數(shù)據(jù)都位于單個每次測試運行的 ?basetemp? 目錄下。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號