![](/img/trans.png)
[英]Why Doesn't This Python/Django Unit Test with Mock Objects Work?
[英]Mock constant in python unit test doesn't work
我試圖在我的 python 單元測試中模擬一個常量。
我有一個名為settings.py的模塊,其中包含一組常量,特別是我有這個:
REL_PATH = "my/path/{}/file.csv"
然后在另一個模塊中,我有這個 function 它使用這樣的 REL_PATH 變量:
from path.for.REL_PATH.setting import REL_PATH
def create_csv(missing_path_here):
columns = ["col_a", "col_b", ...]
empty_df = pd.DataFrame(columns=columns)
Writer(empty_df, REL_PATH.format(missing_path_here)).write_csv()
在我的單元測試中,我有以下代碼:
class TestCreateAnomaliesRepositoryCsv(unittest.TestCase):
@patch("path.for.setting.REL_PATH", "another/custom/path/file.csv")
def test_create_anomalies_repository_csv(self):
create_csv(missing_path_here="test")
我希望這樣 csv 文件將在“另一個/自定義/路徑/”路徑下創建,但 csv 文件仍會在原始目錄中創建。
我也試過這樣做:
def test_create_anomalies_repository_csv(self):
with path("path.for.setting.REL_PATH", "another/custom/path/file.csv")
create_csv(missing_path_here="test")
但最終的結果是一樣的。
我究竟做錯了什么?
如果修補 object,則必須始終修補模塊中使用的 object,例如,如果您以以下形式導入它: from x import y
in your module module
,您必須修補module.y
而不是xy
。 這在文檔中有描述,Ned Batchelder 有一篇很好的博客文章更詳細地描述了這個問題。 在您的情況下,您需要:
@patch("path.to.using_module.REL_PATH", "another/custom/path/file.csv")
def test_create_anomalies_repository_csv(self):
create_csv(missing_path_here="test")
假設path.to.using_module.py
像這樣導入常量:
from path.for.setting import REL_PATH
您嘗試的另一個變體是等效的,也可以工作:
def test_create_anomalies_repository_csv(self):
with path("path.to.using_module.REL_PATH", "another/custom/path/file.csv")
create_csv(missing_path_here="test")
總而言之,您始終必須檢查要使用的 object 是如何導入的。 基本上有兩種情況:
sut.py
像import module
或import module.object
一樣在 sut.py 中導入 - 在這種情況下,它可以修補為module.object
sut.py
like from module import object
- in this case sut.py
uses a local reference to refer to the object, and the patching shall be done for sut.object
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.