First, I hope I am not making duplicate (my first time using this kind of mailing list...)<br><br>&gt; The first thing is to be clear in your mind which code you are intending<br>
&gt; to test. In this case, it sounds like you want to test your<br>
&gt; &quot;render_reverse&quot; function, but without exercising Django&#39;s &quot;reverse&quot;<br>
&gt; (which makes it a unit test). Mocking &quot;reverse&quot; is a reasonable way to<br>
&gt; go about this.<br>
<br>Yes. Exactly. I want to perform a unittest on this function, which calls django&#39;s reverse (for whatever reason why I am doing this...)<br><br>Here is the actual function from lib.py (there is no class involved, all functions in lib.py)<br>
<br><div style="margin-left:40px">from django.core.urlresolvers import reverse<br>def render_reverse(f, kwargs):<br>    &quot;&quot;&quot;<br>    kwargs is a dictionary, usually of the form {&#39;args&#39;: [cbid]}<br>    &quot;&quot;&quot;<br>
    return reverse(f, **kwargs)<br></div><br>Because the name lookup is `reverse`, so I should patch `myproject.myapps.mylibrary.reverse` as opposed to `django.core.urlresolvers.reverse`<br><br>I did the first method. I want to assert that `render_reverse` generates whatever `reverse` generates (by calling `reverse` directly). That&#39;s the goal. So I have the following test code:<br>
<br><div style="margin-left:40px">from lib import render_reverse, print_ls<br><br>class LibTest(unittest.TestCase):<br><br><div style="margin-left:40px">def test_render_reverse_is_correct(self):<br>    with patch(&#39;myproject.myapps.mylibrary.reverse&#39;) as mock_reverse:<br>
        from lib import render_reverse<br>        mock_f = MagicMock(name=&#39;f&#39;, return_value=&#39;dummy_views&#39;)<br>        mock_kwargs = MagicMock(name=&#39;kwargs&#39;,return_value={&#39;args&#39;:[&#39;123&#39;]})<br>
        mock_reverse.return_value = &#39;/natrium/cb/details/123&#39;<br>        response = render_reverse(mock_f(), mock_kwargs())<br><br>        print mock_reverse.mock_calls  # prints []<br>    print mock_reverse.mock_calls  # prints []<br>
    self.assertTrue(&#39;/natrium/cb/details/&#39; in response)<br></div></div><br>Observations:<br>1. mock_reverse was never because `mock_calls` returns []. I&#39;ve asserted with `called` method, and it returns False. <br>
2. using render_reverse like this, the name `dummy_views` must exists - it must be a view function that actually exists in my Django project. Otherwise, it will return an error.<br>3. using render_reverse like this, the speed takes 0.2 - 0.3 seconds, as opposed to 0.06 s when I used `mock_reverse`. <br>
<br>Is there anything wrong the code? I understand that `mock_f` and `mock_kwargs` should be just simple input, rather than mock objects. <br><br>Thanks, Carl.<br>