假设我有一个在Python中设置如下的类。
由于某些原因,我收到了错误信息。
from somewhere import sendmail
class MyClass:
def __init__(self, **kargs):
self.sendmail = kwargs.get("sendmail", sendmail) #if we can't find it, use imported def
def publish():
#lots of irrelevant code
#and then
self.sendmail(mail_to, mail_from, subject, body, format= 'html')
正如您所见,我已经为self.sendmail函数提供了参数化选项。
现在,在测试文件中。
Class Tester():
kwargs = {"sendmail": MagicMock(mail_from= None, mail_to= None, subject= None, body= None, format= None)}
self.myclass = MyClass(**kwargs)
##later on
def testDefaultEmailHeader():
default_subject = "Hello World"
self.myclass.publish()
self.myclass.sendmail.assert_called() #this is doing just fine
self.myclass.sendmail.assert_called_with(default_subject) #this is having issues
由于某些原因,我收到了错误信息。
AssertionError: Expected call: mock('Hello World')
Actual Call : mock('defaultmt', 'defaultmf', 'Hello World', 'default_body', format= 'html')
基本上,assert期望sendmail只使用一个变量进行调用,但实际上却使用了全部5个变量。问题在于,我并不关心其他4个变量是什么!我只想确保它被正确地调用了主题。
我尝试使用模拟占位符ANY,但结果相同。
self.myclass.sendmail.assert_called_with(ANY, ANY, 'Hello World', ANY, ANY)
AssertionError: Expected call: mock(<ANY>, <ANY>, 'Hello World', <ANY>, <ANY>)
Actual Call : mock('defaultmt', 'defaultmf', 'Hello World', 'default_body, 'format= 'html')
我不确定如何处理这个问题。如果我们只关心其中一个变量并希望忽略其他变量,有没有人有建议?
format='html'
而不是'format='html'
,后者含义不明确?试试这个:self.myclass.sendmail.assert_called_with(ANY, ANY, 'Hello World', ANY, format=ANY)
。 - alko