DEV Community 👩‍💻👨‍💻

Yao-Ching Huang
Yao-Ching Huang

Posted on • Updated on

Python :: 用tmp_path處理pytest暫存檔案

在設計Python測試項目時,經常會有讀寫暫存檔案需求。以機器學習專案的測試為例,就會有中繼資料暫存或是存放機器學習模型等需求。

通常會用以下2種方法處理暫存檔案:

  • 儲存在當下目錄。
  • 透過tempfile寫入系統的暫存目錄內。

其實pytest內建了tmp_path fixture,tmp_filepathlib.Path物件,指向系統暫存目錄內的子目錄。

我們可以直接利用tmp_path寫入測試過程中所產生的暫存檔案。

範例:

寫入 hello.txt 至 tmp_path 目錄。

# set up Python venv
python3 -m venv .venv
source .venv/bin/activate
pip install 'pytest~=7.1.0'  # install pytest 7.1.x

# create test file
mkdir tests
cat << EOF > tests/test_hello.py
import pytest


def test_tmp_path(tmp_path):
    file_path = tmp_path / "hello.txt"

    print(f"{tmp_path = }")
    print(f"{file_path = }")

    with file_path.open("w", encoding="utf-8") as file:
        file.write("hello")
EOF
Enter fullscreen mode Exit fullscreen mode
$ pytest -vvs tests

...
tests/test_hello.py::test_tmp_path tmp_path = PosixPath('/tmp/pytest-of-tom/pytest-0/test_tmp_path0')
file_path = PosixPath('/tmp/pytest-of-tom/pytest-0/test_tmp_path0/hello.txt')
PASSED

================================================== 1 passed in 0.01s ===================================================
Enter fullscreen mode Exit fullscreen mode

完成測試後,其實pytest並不會像tempfile.TemporaryDirectory提供自動清理功能,如有必要我們仍需要手動刪除pytest自動建立的暫存目錄。

Reference: https://docs.pytest.org/en/7.1.x/how-to/tmp_path.html

Top comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠