Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are two ways you can do this; with patch and with patch.object</p> <p>Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following</p> <pre><code>#foo.py def some_fn(): return 'some_fn' class Foo(object): def method_1(self): return some_fn() #bar.py import foo class Bar(object): def method_2(self): tmp = foo.Foo() return tmp.method_1() #test_case_1.py import bar from mock import patch @patch('foo.some_fn') def test_bar(mock_some_fn): mock_some_fn.return_value = 'test-val-1' tmp = bar.Bar() assert tmp.method_2() == 'test-val-1' mock_some_fn.return_value = 'test-val-2' assert tmp.method_2() == 'test-val-2' </code></pre> <p>If you are directly importing the module to be tested, you can use patch.object as follows:</p> <pre><code>#test_case_2.py import foo from mock import patch @patch.object(foo, 'some_fn') def test_foo(test_some_fn): test_some_fn.return_value = 'test-val-1' tmp = foo.Foo() assert tmp.method_1() == 'test-val-1' test_some_fn.return_value = 'test-val-2' assert tmp.method_1() == 'test-val-2' </code></pre> <p>In both cases some_fn will be 'un-mocked' after the test function is complete.</p> <p>Edit: In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters</p> <pre><code>@patch.object(foo, 'some_fn') @patch.object(foo, 'other_fn') def test_foo(test_other_fn, test_some_fn): ... </code></pre> <p>Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload