模拟内部方法 Python2

Mock inner methods Python2

我是新来模拟并且真的很挣扎。主要是在文档和大多数 SO 页面中,它显示了如何获取模拟 result_value,但我想检查我从方法中获取的值是否正确,而不是 result_value。这是示例:

#!/usr/bin/env python

class Example:

    def one(self):
        return 1

    def two(self, one):
        print(one + 1) # basically any void method, ex: result = one + 1 and check result value if correct

    def main(self):
        self.two(self.one())

if __name__ == '__main__':
    e = Example()
    e.main()

测试:

#!/usr/bin/env python

import unittest
import example
from mock import patch

class Example(unittest.TestCase):

    def test_one(self):
        self.assertEqual(1, et.one())

    def test_two(self):
        with patch('example.Example.two'):
            self.assertEqual(2, et.two(et.one())) # ..the part I'm stuck
                                                  # whick ofc throws AssertionError: 2 != <MagicMock name='two()' id='blablabla'>

    def test_main(self):
        # unknown part..

if __name__ == '__main__':
    et = example.Example()
    unittest.main()

unittest如何实现void方法检测?

更新:

所以我在 chepner 的帮助下得到的印刷品:

def test_twoi3(self):
        mock_print = MagicMock()
        with patch('sys.stdout', mock_print):
            print(2)
            expected = call.write('2')
            self.assertEqual(mock_print.mock_calls[0], expected)

main 我不太确定这是否是一个好的解决方案...:[=​​19=]

def test_main(self):
        with patch ('example.Example.main') as m:
            et.main(et.two(1))
        m.assert_called_with(et.two(1))

但我不想通过传递方法和值来检查,而是 main 是否调用其他两种方法。如何实现?

你不需要模拟任何东西(直接地,无论如何);您想要捕获标准输出并验证它是否符合您的期望。

from contextlib import redirect_stdout
from io import StringIO

def test_two(self):
    stdout = StringIO()

    with redirect_stdout(stdout):
        et.two(et.one())

    self.assertEqual(stdout.getvalue(), "2\n")

或者,您可以模拟 print 并检查它 是否使用预期参数调用

def test_two(self):
    with patch('__builtin__.print') as p:
        et.two(et.one())

    p.assert_called_with(2)

我已经想出如何测试是否调用了主要方法。测试看起来像这样:

#!/usr/bin/env python

import unittest
import example
from mock import patch, MagicMock, call

class Example(unittest.TestCase):

    def setUp(self):
        self.et = example.Example()

    def test_one(self):
        self.assertEqual(1, self.et.one())

    def test_two(self):
        mock_print = MagicMock()
        with patch('sys.stdout', mock_print):
            print(2)
            expected = call.write('2')
            self.assertEqual(mock_print.mock_calls[0], expected)

    def test_main(self):
        self.et.two = MagicMock(side_effect=self.et.two)
        self.et.one = MagicMock(side_effect=self.et.one)

        self.et.main()

        self.et.one.assert_called()
        self.et.two.assert_called()

        self.et.one.__str__ = self.et.one
        self.assertEqual(1, int(self.et.one))

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

main(全部)中的模拟方法和调用 main 方法后,onetwo 已成功调用。对于 one,您可以使用 __str__

return 值