First, I hope I am not making duplicate (my first time using this kind of mailing list...)<br><br>> The first thing is to be clear in your mind which code you are intending<br>
> to test. In this case, it sounds like you want to test your<br>
> "render_reverse" function, but without exercising Django's "reverse"<br>
> (which makes it a unit test). Mocking "reverse" is a reasonable way to<br>
> go about this.<br>
<br>Yes. Exactly. I want to perform a unittest on this function, which calls django'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> """<br> kwargs is a dictionary, usually of the form {'args': [cbid]}<br> """<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'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('myproject.myapps.mylibrary.reverse') as mock_reverse:<br>
from lib import render_reverse<br> mock_f = MagicMock(name='f', return_value='dummy_views')<br> mock_kwargs = MagicMock(name='kwargs',return_value={'args':['123']})<br>
mock_reverse.return_value = '/natrium/cb/details/123'<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('/natrium/cb/details/' in response)<br></div></div><br>Observations:<br>1. mock_reverse was never because `mock_calls` returns []. I'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>