簡體   English   中英

將 pytest 工作目錄更改為測試用例目錄

[英]Change pytest working directory to test case directory

我有以下 pytest 目錄結構:

system_tests/
  ├── conftest
  ├── pytest.ini
  │
  ├── suite_1/
  │    └── test_A.py
  │   
  └── suite_2/
       └── sub_suite_2a/
            └── test_B.py

當每個測試方法運行時,許多第三方庫/進程會在當前工作目錄中生成工件。

  • 當 pytest 從sub_suite文件夾(使用 CLI 或 IDE “播放”按鈕)執行時,文件將在sub_suite文件夾中生成,我希望它們在其中。
  • 但是,當 pytest 從system_tests文件夾運行以運行所有測試時,所有工件都在system_tests文件夾中創建,這不是我想要的。

有沒有一種簡單的方法可以強制 pytest 始終使用測試 class 文件夾作為工作目錄,所以無論我如何或從何處運行測試,我都會得到相同的結果?

編輯:改進的解決方案

按照@Kound的建議使用monkeypatch 刪除樣板代碼以恢復cwd。 您還可以啟用autouse以自動將此夾具應用於所有測試功能。 將以下夾具添加到conftest.py以更改所有測試的 cwd:

@pytest.fixture(autouse=True)
def change_test_dir(request, monkeypatch):
    monkeypatch.chdir(request.fspath.dirname)

任何由測試啟動的進程都將使用測試用例文件夾作為它們的工作目錄,並將它們的日志、輸出等復制到那里,而不管測試套件在哪里執行。

原始解決方案

以下函數級夾具將更改為測試用例目錄,運行測試(yield),然后更改回調用目錄以避免副作用,正如@hi2meuk 所建議的:

@pytest.fixture
def change_test_dir(request):
    os.chdir(request.fspath.dirname)
    yield
    os.chdir(request.config.invocation_dir)
  • request是內置 pytest 夾具
  • fspath是正在執行的測試模塊的LocalPath
  • dirname是測試模塊的目錄
  • request.config.invocationdir - 執行 pytest 的文件夾
  • request.config.rootdir - pytest 根目錄,不會根據您運行 pytest 的位置而改變。 此處未使用,但可能有用。

而不是像@DV82XL 建議的那樣為每個目錄創建一個固定裝置,您可以簡單地使用monkeypatch來實現相同的目的:

import pytest
from pathlib import Path

@pytest.fixture
def base_path() -> Path:
    """Get the current folder of the test"""
    return Path(__file__).parent



def test_something(base_path: Path, monkeypatch: pytest.MonkeyPatch):
    monkeypatch.chdir(base_path / "data" )
    # Do something in the data folder

恕我直言,另一種更強大的方法:始終通過完整路徑引用您的文件。

__file__是一個自動聲明的 Python 變量,它是當前模塊的名稱。 因此,在您的test_B.py文件中,它將具有以下值: system_tests/suite_2/sub_suite_2a/test_B.py 只需獲取父母並選擇在哪里寫入文件即可。

from pathlib import Path
test_data_dir = Path(__file__).parent / "test_data"

現在您將它們全部放在同一個位置,並且可以告訴您的版本控制系統忽略它們。

如果代碼在庫中,最好使用絕對路徑:

import os
from pathlib import Path

test_data_dir = Path(__file__).parent.absolute() / "test_data"

許多選項可供您實現這一目標。 這里有幾個。

1. 寫一個 pytest 夾具,檢查當前工作目錄是否等於所需工作目錄,如果不等於,則將所有工件文件移動到所需目錄。 如果您生成的工件都是相同類型的文件(例如 *.jpg、*.png、*.gif)並且您只是希望它們位於不同的目錄中,那么這可能就足夠了。 像這樣的東西可以工作

from pathlib import Path
import shutil

@pytest.fixture
def cleanup_artifacts():
    yield None
    cwd = Path.cwd()
    desired_dir = Path.home() / 'system-tests' / 'suite-2' / 'sub_suite_2a'
    if cwd != desired_dir:
        for f in cwd.glob('*.jpg'):
            shutil.move(f, desired_dir)

然后您可以根據需要將此夾具添加到您的測試中。

2. 您可以將rootdir根目錄配置為所需的目錄,因為rootdir使用根目錄來存儲項目/測試運行的特定信息。

當您運行 pytest 時,將其運行為

pytest --rootdir=desired_path

請參閱此處了解更多信息: https://docs.pytest.org/en/latest/customize.html#initialization-determining-rootdir-and-inifile

如果兩者都不適合您,請詳細說明您的要求。 當然,這可以通過 pytest 來完成。

暫無
暫無

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

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