【问题标题】:How to mock.patch library function from within unit test如何从单元测试中模拟.patch 库函数
【发布时间】:2019-09-10 16:33:41
【问题描述】:

我有一个名为learning 的模块使用random.uniform()。我有一个名为test_learning.py 的文件,其中包含单元测试。当我运行单元测试时,我希望learning 中的代码可以看到random.uniform() 的修补版本。我怎样才能做到这一点?这是我目前拥有的。

import random
import unittest
import unittest.mock as mock

class TestLearning(unittest.TestCase):

    def test_get_random_belief_bit(self):
        with mock.patch('learning.random.uniform', mock_uniform):
            bit = learning.get_random_belief_bit(0.4)
            self.assertEqual(bit, 0)

但测试(有时)失败,因为learning.get_random_belief_bit() 似乎使用的是真正的random.uniform()

【问题讨论】:

  • 我猜你必须在random 处修补uniform
  • 另外你在测试中导入random,这会破坏模拟,为什么不from random import uniformlearning? ...这样您就不必模拟 random?
  • @geckos 我该怎么做才能“从随机导入制服”导入模拟版本?
  • import random 替换为from random import uniform 并模拟为with mock.patch('learning.uniform', return_value=1) as uniform_mock
  • as .. 部分是可选的,但如果您需要自定义更多模拟行为时很有用

标签: python unit-testing mocking python-unittest


【解决方案1】:

单元测试解决方案:

learning.py:

import random


def get_random_belief_bit(f):
    return random.uniform()

test_learning.py:

import random
import unittest
import unittest.mock as mock
import learning


class TestLearning(unittest.TestCase):

    def test_get_random_belief_bit(self):
        with mock.patch('random.uniform', mock.Mock()) as mock_uniform:
            mock_uniform.return_value = 0
            bit = learning.get_random_belief_bit(0.4)
            self.assertEqual(bit, 0)
            mock_uniform.assert_called_once()


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

带有覆盖率报告的单元测试结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Name                                          Stmts   Miss  Cover   Missing
---------------------------------------------------------------------------
src/stackoverflow/57874971/learning.py            3      0   100%
src/stackoverflow/57874971/test_learning.py      13      0   100%
---------------------------------------------------------------------------
TOTAL                                            16      0   100%

【讨论】:

    猜你喜欢
    • 2010-11-17
    • 1970-01-01
    • 1970-01-01
    • 2020-10-27
    • 1970-01-01
    • 2013-10-08
    • 1970-01-01
    • 2017-06-14
    • 2021-11-10
    相关资源
    最近更新 更多