Search code examples
djangodjango-tests

Django url unit test comparison of expected view function fails


class TestsUrls(SimpleTestCase):

def test_index_url_is_resolved(self):
    url = reverse('index')
    self.assertEquals(resolve(url).func, index)

I am trying to unit test url to see if it returns the expected view. This assertion fails even though it looks like the functions are the same. I am using function based views, not class based views. Does that have something to do with it?

AssertionError: <function index at 0x11db7cb70> != <function index at 0x11d860ae8>

Solution

  • It's not clear how you get index, but resolve(url).func returns an instance of the python object that is the function. Everything in python are objects, also functions, so you get an instance in memory. When you compare the two objects, you are comparing different instances of the same function. As you can see their addresses in memory are different.

    So instead of directly comparing them, compare their name and module:

    f = resolve(url).func
    self.assertEqual(f.__name__, index.__name__)
    self.assertEqual(f.__module__, index.__module__)