[英]Mocking, assert_called with, in python
我需要確保在python中使用特定參數調用函數。 我已經使用魔術模擬嘲笑了此功能。
self.function = MagicMock()
self.function(subject= "Hello World")
是否存在某些類似的東西
self.function.assert_called_with("Hello World")
要么
self.function.assert_called_with(subject= "Hello World")
抱歉,以前是否有人問過這個問題,但是我一直在嘲笑模擬文檔,而且似乎所有assert語句都不會對我有用。
編輯:我添加了一些調試輸出
當我嘗試調試時,我看到
AssertionError:
Expected call: mock('Hello World')
Actual call: mock('thing i dont care about', 'Hello World', 'thing i dont care about')
因此,顯然,該函數被調用,但是斷言的行為很奇怪。 它在參數列表或其他內容中無法識別“ Hello World”。
編輯2:
我稍微修改了一下代碼,但仍然無法正確匹配
self.function = MagicMock(field1 = None, field2 = None, subject = None, field4 = None)
#later on...
self.function(1,2,"Hello World",4) #these params will not always be 1,2,4 .. I made them so to
#show an example
#even further down the road
self.function.assert_called_with(ANY, ANY, "Hello World", ANY)
這樣的事情對我也不起作用。 仍然出現錯誤
AssertionError:
Expected call: mock(<ANY>, <ANY>, "Hello World", <ANY>)
Actual call: mock(1,2,"Hello World", 4)
再說一次,我不能做類似的事情
“ ANY”如何與匹配參數的模式相對應?
您所寫的內容完全可以按預期工作。 取出自我,這是一個簡化的版本-
func = mock.MagicMock()
func(subject="Hello World")
# assert that func was indeed called with subject="Hello World"
# this goes well since it was indeed called with "Hello World"
func.assert_called_with(subject="Hello World")
# this fails since func was not called with "Bye World"
AssertionError: Expected call: mock(subject='Bye World')
Actual call: mock(subject='Hello World')
# The mock also distinguishes between calls with positional and keyword arguments
# so func(subject="Hello World") is not same as func("Hello World") w.r.t.
# the assert statements
那是預期的。 因此,如果您想確保使用預期參數確實調用了模擬函數,只需使用-
func(key=<args>)
func.assert_called_with(key=<args>)
要么
func(<args>)
func.assert_called_with(<args>)
只要記住要在調用和斷言中匹配函數簽名即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.