有一個處理csv檔案的django管理器命令。 app/my_app/my_command.py
。class Command(BaseCommand)。
def handle(self, *args, **options)。
path = (os.path.join(os.path.abspath(os.path.dirname(__name__)), 'data.csv')
# 其他的邏輯與檔案。
我正在用pytest寫一個測驗,問題是我不明白如何模擬變數path來測驗訪問的不是真實的data.csv而是一個臨時的test.csv檔案
@pytest.fixture。
def create_test_csv_file(tmpdir_factory)。
path = tmpdir_factory.mktemp('data') .join('test.csv')
# 其他邏輯 'test.csv'.
return str(path)
@pytest.mark.django_db
def test_function(mocker, create_test_csv_file)。
# smth like mock_path = create_test_csv_file <- NEW CODE HERE。
call_command('my_command')
uj5u.com熱心網友回復:
你可以讓path成為一個有默認值的引數。在測驗中,你可以傳給測驗檔案的路徑。
class Command(BaseCommand)。
def add_arguments(self, parser)。
parser.add_argument(
"-path"。
dest="path"。
default=os.path.join(os.path.abspath(os.path.dirname(__name__)), 'data.csv')
)
def handle(self, *args, **options)。
path = options.get("path")
...
然后在測驗中你可以呼叫call_command('my_command', path=<path>)/code>
uj5u.com熱心網友回復:
你不能模擬本地變數path,但你可以模擬它的檢索位置,這里是來自os.path.join。
src.py
import os
class Command:
def handle(self)。
path = (os.path.join(os.path.abspath(os.path.dirname(__name__)), 'data.csv')
print(path)
return path
test_src.py
from src import Command
def test_real_path(mocker, tmp_path)。
結果 = Command().handle()
assert str(result).endwith("data.csv") # real file
def test_mock_path(mocker, tmpdir_factory)。
path = tmpdir_factory.mktemp('data').join('test.csv')
mocker.patch("os.path.join", return_value=path) # Or "src.os.path.join"
result = Command().handle()
assert str(result).endwith("test.csv") # 測驗檔案。
assert result == path
輸出:
$ pytest -q -rP
..
[100%]
================================================================================================= PASSES ==================================================================================================
_____________________________________________________________________________________________ test_real_path ______________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
/home/nponcian/Documents/data.csv
_____________________________________________________________________________________________ test_mock_path ______________________________________________________________________________________________
------------------------------------------------------------------------------------------ Captured stdout call -------------------------------------------------------------------------------------------
/tmp/pytest-of-nponcian/pytest-15/Data0/test.csv
2通過in 0.06s
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/307448.html
標籤:
