断言在Python单元测试中调用了一个方法

时间:2010-09-30 10:32:56

标签: python unit-testing

假设我在Python单元测试中有以下代码:

aw = aps.Request("nv1")
aw2 = aps.Request("nv2", aw)

有没有一种简单的方法断言在测试的第二行中调用了一个特定的方法(在我的情况下是aw.Clear())?例如是这样的:

#pseudocode:
assertMethodIsCalled(aw.Clear, lambda: aps.Request("nv2", aw))

5 个答案:

答案 0 :(得分:107)

我使用Mock(py3.3 +上现为unittest.mock):

from mock import patch
from PyQt4 import Qt


@patch.object(Qt.QMessageBox, 'aboutQt')
def testShowAboutQt(self, mock):
    self.win.actionAboutQt.trigger()
    self.assertTrue(mock.called)

对于您的情况,它可能如下所示:

import mock
from mock import patch


def testClearWasCalled(self):
   aw = aps.Request("nv1")
   with patch.object(aw, 'Clear') as mock:
       aw2 = aps.Request("nv2", aw)

   mock.assert_called_with(42) # or mock.assert_called_once_with(42)

Mock支持许多有用的功能,包括修补对象或模块的方法,以及检查正确的东西是否被调用等等。

Caveat emptor! (买家要小心!)

如果您错误输入assert_called_withassert_called_onceassert_called_wiht),您的测试可能仍会运行,因为Mock会认为这是一个模拟函数,并且很乐意继续使用,除非您使用{{ 1}}。有关详细信息,请阅读assert_called_once: Threat or Menace

答案 1 :(得分:19)

是的,如果您使用的是Python 3.3+。您可以使用内置的unittest.mock来断言调用的方法。对于Python 2.6+,使用滚动后端Mock,这是相同的。

以下是您案例中的一个简单示例:

from unittest.mock import MagicMock
aw = aps.Request("nv1")
aw.Clear = MagicMock()
aw2 = aps.Request("nv2", aw)
assert aw.Clear.called

答案 2 :(得分:13)

我不知道任何内置的东西。它实现起来非常简单:

class assertMethodIsCalled(object):
    def __init__(self, obj, method):
        self.obj = obj
        self.method = method

    def called(self, *args, **kwargs):
        self.method_called = True
        self.orig_method(*args, **kwargs)

    def __enter__(self):
        self.orig_method = getattr(self.obj, self.method)
        setattr(self.obj, self.method, self.called)
        self.method_called = False

    def __exit__(self, exc_type, exc_value, traceback):
        assert getattr(self.obj, self.method) == self.called,
            "method %s was modified during assertMethodIsCalled" % self.method

        setattr(self.obj, self.method, self.orig_method)

        # If an exception was thrown within the block, we've already failed.
        if traceback is None:
            assert self.method_called,
                "method %s of %s was not called" % (self.method, self.obj)

class test(object):
    def a(self):
        print "test"
    def b(self):
        self.a()

obj = test()
with assertMethodIsCalled(obj, "a"):
    obj.b()

这要求对象本身不会修改self.b,这几乎总是正确的。

答案 3 :(得分:7)

是的,我可以给你大纲,但我的Python有点生疏,我太忙了,无法详细解释。

基本上,您需要在调用原始方法的方法中放置代理,例如:

 class fred(object):
   def blog(self):
     print "We Blog"


 class methCallLogger(object):
   def __init__(self, meth):
     self.meth = meth

   def __call__(self, code=None):
     self.meth()
     # would also log the fact that it invoked the method

 #example
 f = fred()
 f.blog = methCallLogger(f.blog)

这个关于可调用的StackOverflow answer可以帮助您理解上述内容。

更详细:

虽然答案被接受,但由于与Glenn进行了有趣的讨论并且有几分钟免费,我想扩大我的答案:

# helper class defined elsewhere
class methCallLogger(object):
   def __init__(self, meth):
     self.meth = meth
     self.was_called = False

   def __call__(self, code=None):
     self.meth()
     self.was_called = True

#example
class fred(object):
   def blog(self):
     print "We Blog"

f = fred()
g = fred()
f.blog = methCallLogger(f.blog)
g.blog = methCallLogger(g.blog)
f.blog()
assert(f.blog.was_called)
assert(not g.blog.was_called)

答案 4 :(得分:4)

您可以手动或使用pymox等测试框架模拟aw.Clear。手动,你可以用这样的东西来做:

class MyTest(TestCase):
  def testClear():
    old_clear = aw.Clear
    clear_calls = 0
    aw.Clear = lambda: clear_calls += 1
    aps.Request('nv2', aw)
    assert clear_calls == 1
    aw.Clear = old_clear

使用pymox,你会这样做:

class MyTest(mox.MoxTestBase):
  def testClear():
    aw = self.m.CreateMock(aps.Request)
    aw.Clear()
    self.mox.ReplayAll()
    aps.Request('nv2', aw)