Skip to content Skip to sidebar Skip to footer

How To Write A Test Case For This Django Custom Tag

Django version : v1.10 Python : 3.5 (this is important as it turns out .. look at the answer) I found this answer in order to have a if-else tag to compare the request.path in Dj

Solution 1:

You should be able to cover most, if not all of that using mock. For example, let's say you want to test the render function:

from unittest.mock import Mock

deftest_render_url_match(self):
    mock_request = Mock()
    matching_url_name = 'url_name'
    mock_nodelist_true, mock_nodelist_false = Mock(), Mock()
    mock_view_name = Mock()
    mock_view_name.resolve.return_value = matching_url_name
    mock_request.resolver_match.url_name = matching_url_name
    mock_context = {'request': mock_request}

    custom_node = IfCurrentViewNode(mock_view_name, mock_nodelist_true, mock_nodelist_false)
    custom_node.render(mock_context)

    # You can then test that the correct function was called:# you can change to `assert_called_once` if using Python 3.6
    mock_nodelist_true.render.assert_called_once_with(mock_context)

By setting up the mocks that way, I've ensured that this request.resolver_match.url_name == view_name will be true, and hit this line: return self.nodelist_true.render(context). You can then set up the url name so they don't match and cover the false case.

Then, for the do_ifcurrentview function, you can mock out whatever pieces you need to as well. Maybe you don't want to mess with getting parser.compile_filter to return what you need. Just mock it and change the return value:

with mock.patch('parser.compile_filter') as mock_compile_filter:
    mock_compile_filter.return_value = 'my_expected_view_name'

Post a Comment for "How To Write A Test Case For This Django Custom Tag"