简体   繁体   中英

How to mock.patch library function from within unit test

I have a module called learning that uses random.uniform() . I have a file called test_learning.py containing unit tests. When I run a unit test, I would like the code in learning to see the patched version of random.uniform() . How can I do this? Here is what I have currently.

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)

But the test (sometimes) fails because learning.get_random_belief_bit() seems to be using the real random.uniform() .

Unit test solution:

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()

unit test result with coverage report:

.
----------------------------------------------------------------------
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%

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM