如何使用Python Mock断言接受序列参数的调用?

时间:2013-01-22 17:50:02

标签: python unit-testing mocking

我正在处理一系列用户定义的对象。它看起来类似于以下内容:

class Thing(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

我目前正在测试的方法具有与以下类似的功能:

def my_function(things):
    x_calc = calculate_something(t.x for t in things)
    y_calc = calculate_something(t.y for t in things)
    return x_calc / y_calc

我面临的问题是测试对calculate_something的调用。我想断言这些调用发生了,就像这样:

calculateSomethingMock.assert_any_call(the_sequence)

我不关心传递给calculate_something的序列的顺序,但我确实知道这些元素都存在。我可以在调用set时包装生成器函数,但我不认为我的测试应该指示将哪种类型的序列传递到calculate_something。我应该能够以任何顺序传递它。我也可以创建一个生成序列的方法,而不是使用生成器语法并模拟该方法,但这看起来有点矫枉过正。

我怎样才能最好地构建这个断言,或者我在这里测试是否存在结构不良的代码?

我使用的是Python 2.7.3和Mock 1.0.1。

(对于那些觉得有必要对此发表评论的人,我知道我最后一次做测试,这不是最好的做法。)

编辑:

在看了this marvelous talk entitled "Why You Don't Get Mock Objects by Gregory Moeck"之后,我又重新考虑过我是否应该嘲笑calculate_something方法。

2 个答案:

答案 0 :(得分:7)

查看Mock文档,有call_args_list可以执行您想要的操作。

因此,您将在测试中模拟出calculate_something

calculate_something = Mock(return_value=None)

my_function完成后,您可以通过执行以下操作检查传递的参数:

calculate_something.call_args_list

将返回所有调用的列表(传递相应的元素)。

修改

(抱歉,我花了这么长时间,我不得不在我的机器上安装Python3.3)

<强> mymodule.py

class Thing:
    ...
def calculate_something:
    ...

def my_function(things):
    # Create the list outside in order to avoid a generator object
    # from being passed to the Mock object.

    xs = [t.x for t in things]
    x_calc = calculate_something(xs)

    ys = [t.y for t in things]
    y_calc = calculate_something(ys)
    return True

<强> test_file.py

import unittest
from unittest.mock import patch, call
import mymodule



class TestFoo(unittest.TestCase):

    # You can patch calculate_something here or
    # do so inside the test body with 
    # mymodule.calcualte_something = Mock()
    @patch('mymodule.calculate_something')
    def test_mock(self, mock_calculate):

        things = [mymodule.Thing(3, 4), mymodule.Thing(7, 8)]

        mymodule.my_function(things)

        # call_args_list returns [call([3, 7]), call([4, 8])]
        callresult = mock_calculate.call_args_list


        # Create our own call() objects to compare against
        xargs = call([3, 7])
        yargs = call([4, 8])

        self.assertEqual(callresult, [xargs, yargs])

        # or
        # we can extract the call() info
        # http://www.voidspace.org.uk/python/mock/helpers.html#mock.call.call_list
        xargs, _ = callresult[0]
        yargs, _ = callresult[1]

        xexpected = [3, 7]
        yexpected = [4, 8]

        self.assertEqual(xargs[0], xexpected)
        self.assertEqual(yargs[0], yexpected)

if __name__ == '__main__':
    unittest.main()

答案 1 :(得分:2)

我没有触及我最初使用的代码,但我一直在重新考虑我的测试方法。我一直在努力更加小心我做什么,不要嘲笑。我最近意识到我无意识地开始遵循这个经验法则:如果它使我的测试变得更短更简单,那就嘲笑它,如果它使测试变得更复杂则不管它。在这种方法的情况下,简单的输入/输出测试就足够了。没有外部依赖项,如数据库或文件。简而言之,我认为我的问题的答案是,“我不应该嘲笑calculate_something。”这样做会使我的测试更难以阅读和维护。

相关问题