Python:在测试函数

时间:2017-11-10 12:47:20

标签: python unit-testing mocking patch python-unittest.mock

我一直在使用Python的unittest.mock库,但是现在我正在努力解决可能无法正确使用的用例。

考虑包含以下代码段的文件mymodule/code.py

def sum():
  pass

def mul():
  pass

def div():
  pass

def get_functions():
  return [sum, mul, div]

def foo():
  functions = get_functions()
  for func in functions:
    func()

我想测试foo函数,修补sum函数,然后保留muldiv。这是我最初尝试过的:

class TestFoo(unittest.TestCase):
  @mock.patch('mymodule.code.foo.sum')
  def test_foo(foo_sum_mock):
    foo()
    foo_sum_mock.assert_called_once()

但是,上面说明的修补方法不起作用。我相信sum功能在加载mymodule.code.py时已正确修补,但由于def sum()阻止而重新定义。

通过阅读官方文档,我还尝试使用start库的stopunittest.mock函数,如下所示:

def test_foo():
  patcher = mock.patch('module.code.sum')
  mocked_sum_fun = patcher.start()

  foo()

  mocked_sum_fun.assert_called_once()
  mock_sum_fun.stop()

这种方法也行不通。我希望在sum文件加载后避免modules/code.py函数覆盖。

是否可以修补sum等本地功能?或者将sum函数移动到另一个文件是唯一的修补选项?

非常感谢提前!

2 个答案:

答案 0 :(得分:0)

通常来说,您希望将测试代码与生产代码分开:

code.py

def sum():
    pass

def mul():
    pass

def div():
    pass

def get_functions():
    return [sum, mul, div]

def foo():
    functions = get_functions()
    for func in functions:
        func()

code_test.py

import unittest
import mock_test as mock
import code

class TestFoo(unittest.TestCase):
    @mock.patch('code.sum')
    def test_foo(self, sum_mock):
        def new_sum_mock(*args, **kwargs):
            # mock code here
            pass
        sum_mock.side_effect = new_sum_mock
        code.foo()
        sum_mock.assert_called_once()

但是可以,您可以将它们全部放入一个文件中

code_test.py:

import unittest
import mock_test as mock
import code

def sum():
    pass


def mul():
    pass


def div():
    pass


def get_functions():
    return [sum, mul, div]


def foo():
    functions = get_functions()
    for func in functions:
        func()


class TestFoo(unittest.TestCase):

    @mock.patch('code_test.sum')
    def test_foo(self, sum_mock):
        def new_sum_mock(*args, **kwargs):
            # mock code here
            pass

        sum_mock.side_effect = new_sum_mock
        code.foo()
        sum_mock.assert_called_once()

答案 1 :(得分:0)

您可以使用mock.patch并将该模块称为__main__来模拟相同模块的功能

code.py

from unittest.mock import patch

def sum():
    print("called method sum")
    pass

def call_sum():
    sum()

def return_mock():
    print("I'm a mocked method")
    return True

with mock.patch('__main__.sum', return_value=return_mock()) as mock_test:
    call_sum()
    mock_test.assert_called_once() # assure that mocked method was called, not original.

您还可以使用lib(my_project.code.sum)的路径代替__main__.sum