【问题标题】:Python 3 unittest cannot mock method used inside functionsPython 3 unittest 不能模拟函数内部使用的方法
【发布时间】:2018-01-04 02:03:43
【问题描述】:

我正在尝试在 Python 中进行单元测试。

test.py

from unittest import TestCase,main
from unittest.mock import patch

import file

def mock_return(*args):
    return -1

class Tests(TestCase):
    @patch("file.Foo.a", side_effect=mock_return)
    def test_1(self, mock_fun):
        self.assertEqual(file.Foo().a(), -1)

    @patch("os.urandom", side_effect=mock_return)
    def test_2(self, mock_fun):
        self.assertEqual(file.Foo().b(), -1)

if __name__ == "__main__":
    main()

file.py

from os import urandom

class Foo:
    def a(self):
        return 1

    def b(self):
        return urandom(1)

为什么test_1 通过但test_2 失败?有没有办法模拟其他类使用的方法?

【问题讨论】:

    标签: python python-3.x mocking python-unittest


    【解决方案1】:

    您必须修补被测试函数使用的绑定。

    from os import urandom  # in file.py
    

    将名称 urandom 绑定到函数 os.urandom in file 模块。 Foo.b 通过 file.urandom 绑定访问该函数。所以Foo.b 的测试必须修补file.urandom,而不是os.urandom

    【讨论】:

    • 这是我需要的答案。 from os import urandom 需要 file.urandomimport os 需要 os.urandom
    • 我正在考虑将@patch("os.urandom",... 更改为@patch("file.urandom",...,然后两个测试都通过了。另一种方法是将from os import urandom 更改为import os 并将Foo.b 中的调用更改为os.urandom。我个人更喜欢前者,因为我更喜欢在测试代码中进行修补,而不是 stdlib。但重要的一点是,测试,包括模拟,必须仔细匹配被测试的代码。
    猜你喜欢
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    • 1970-01-01
    • 2010-11-22
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    • 2015-12-17
    相关资源
    最近更新 更多