Patch - Patching the class introduces an extra parameter? Patch - Patching the class introduces an extra parameter? python python

Patch - Patching the class introduces an extra parameter?


Patch passes in an instance of the patched object to your test method (or to every test method if you are patching at the class level). This is handy because it lets you set return values and side effects, or check the calls made

from unittest.mock import patch@patch('some_module.sys.stdout')def test_something_with_a_patch(self, mock_sys_stdout):    mock_sys_stdout.return_value = 'My return value from stdout'    my_function_under_test()    self.assertTrue(mock_sys_stdout.called)    self.assertEqual(output, mock_sys_stdout.return_value)

If you just want to literally patch something out to ignore it then you can call patch with the following invocation

from unittest.mock import patch, Mock@patch('some_module.sys.stdout', Mock())def test_something_with_a_patch(self):

That replaces sys.stdout in the some_module with a Mock object and does not pass it to the method.


patch passes the patched object to the test function. Its documented here:

patch as function decorator, creating the mock for you and passing it into the decorated function:

>>>>>> @patch('__main__.SomeClass')... def function(normal_argument, mock_class):...     print(mock_class is SomeClass)...>>> function(None)True