How does @mock.patch know which parameter to use for each mock object?

后端 未结 2 1044
谎友^
谎友^ 2021-02-15 11:33

Looking at this webpage: http://www.toptal.com/python/an-introduction-to-mocking-in-python -- The author talks about Mocking and Patching in Python and gives a pretty solid \"re

2条回答
  •  无人及你
    2021-02-15 12:09

    it goes by the order of the execution of the decorators and that is also the order of the parameters passed on to your test method...

    order of decorators execution is shown here: https://thadeusb.com/weblog/2010/08/23/python_multiple_decorators/

    When you use patch the way you wrote it, a Mock instance it is automatically created for you and passed as a parameter to your test method. there is another version of it:

    @mock.patch("subprocess.check_output", mock.MagicMock(return_value='True'))
    def test_mockCheckOutput(self):
        self.assertTrue(subprocess.check_output(args=[])=='True')
    

    in this case you pass your own Mock object and in this example, when you call subprocess.check_output(), it will return 'True'

    you could however do:

    def test_mockCheckOutput(self):
        m = mock.MagicMock(return_value='True')
        with mock.patch("subprocess.check_output", m):
            self.assertTrue(subprocess.check_output(args=[])=='True')
    

    and in this case you can pass any mock item you want because it will be evaluated during runtime... :)

提交回复
热议问题