簡體   English   中英

Python的assert_Called_with,有通配符嗎?

[英]Python's assert_called_with, is there a wildcard character?

假設我在 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')

所以基本上,斷言期望只用一個變量調用 sendmail,當它最終用所有 5 個變量調用時。問題是,我不關心其他 4 個變量是什么! 我只想確保使用正確的主題調用它。

我嘗試了模擬占位符,得到了同樣的結果

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') 

真的不確定如何進行這個。 如果我們只關心變量之一而想忽略其余變量,有人有什么建議嗎?

如果您使用命名參數subject調用sendmail ,那么最好檢查命名參數是否與您期望的匹配:

args, kwargs = self.myclass.sendmail.call_args
self.assertEqual(kwargs['subject'], "Hello World")

這確實假設sendmail兩個實現都有一個名為subject的命名參數。 如果不是這種情況,您可以使用位置參數執行相同操作:

args, kwargs = self.myclass.sendmail.call_args
self.assertTrue("Hello World" in args)

您可以明確說明參數的位置(即傳遞給sendmail的第一個參數或第三個參數,但這取決於被測試的sendmail的實現)。

python 庫沒有默認的通配符實現。 但是實現起來非常簡單。

class AnyArg(object):
    def __eq__(a, b):
        return True

然后使用AnyArg ,可以使用assert_called_with

self.myclass.sendmail.assert_called_with(
    subject="Hello World",
    mail_from=AnyArg(),
    mail_to=AnyArg(),
    body=AnyArg(),
    format=AnyArg(),
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM