我需要使用一個夾具,在一個將用于模擬第三方庫的類中準備一些資料。現在,我有一個相當于這樣的方案:
我需要在類的建構式中使用這個夾具,類似于:
我需要在類的建構式中使用這個夾具。
class mock。
def __init__(self, file):
self._file = file
def get(self, *args, **kwargs)。
return self._file
我需要將file夾具放在Mock類之外,因為它被用在其他地方。Mock類的使用與此非常相似:
def my_test() 。
with patch("thirdparty.Class", new=Mock) 。
...
我嘗試使用@pytest.mark.usefixtures("file")裝飾器,但它沒有作業。我怎樣才能將夾具注入到類中?
uj5u.com熱心網友回復:
如果你用新的類Mock修補了thirdparty.Class,那么這意味著源代碼中所有對實體化thirdparty.Class的呼叫將使用Mock代替。
解決方案1
為了能夠在Mock類中注入要使用的夾具檔案,你必須在Mock類能訪問的地方定義它。你不能從__init__中控制它,因為它將被從源代碼中呼叫。你可以做的是把這個Mock類放在一個函式或夾具中,然后把檔案作為一個變數在函式/夾具中訪問。
thirdparty.py
class MyClass。
def __init__(self, file):
self._file = file
def get(self, *args, **kwargs)。
return self._file
def func()。
obj = MyClass("/path/to/real")
file = obj.get()
print("File to process:"/span>, file)
return file
test_thirdparty.py
from unittest.mock import patch
import pytest
from thirdparty import func
@pytest.fixture(scope="session")
def file()。
return "/path/to/mock"。
@pytest.fixture
def my_mock_class(file)。 # 這也可以是一個普通的函式(不是一個夾具)。你只需要傳遞<file>。
class MyMockClass。
def __init__(self, *args, **kwargs)。
self._file = file # 忽略初始化(__init__)中的輸入檔案。相反,從當前夾具本身(my_mock_class)讀取注入的檔案。
def get(self, *args, **kwargs)。
return self._file
return MyMockClass。
def test_real_file()。
assert func() == "/path/to/real"。
def test_mock_file(my_mock_class)。
with patch("thirdparty.MyClass", new=my_mock_class) 。
assert func() == "/path/to/mock"。
輸出
$ pytest -q -rP
.. [100%]
=============================== PASSES ===============================
___________________________ test_real_file ___________________________
------------------------ 捕獲的stdout呼叫 ------------------------
要處理的檔案。讀取檔案:/path/to/real
___________________________ test_mock_file ___________________________
------------------------ 捕獲的stdout呼叫 ------------------------
要處理的檔案。/path/to/mock
2通過in 0.05s
解決方案2
在源代碼中,找到那些實體化的代碼:
在源代碼中,找到那些實體化的代碼。
the_class = thirdparty.Class(some_file)
然后,追蹤some_file的創建位置。比方說,這是來自一個函式呼叫:
some_file = get_file()
然后你需要修補get_file()以回傳夾具file的值,這樣當thirdparty.Class被創建時(或者說Mock,因為我們已經修補了它),self._file的值將是夾具中的那個。
mocker.patch('get_file", return_value=file) # Where <file> is the fixture
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/318649.html
標籤:
