Search code examples
pythondjangodjango-testing

Resolved url function not equal to class based view `as_view()` method?


I have the following test:

def test_root_url_resolves_to_home_page_view(self):
    found = resolve('/')
    self.assertEqual(
        found.func,
        views.HomePageView.as_view()
    )

gives this error:

AssertionError: <function HomePageView at 0x107d65620> != <function HomePageView at 0x107d97400>

Solution

  • As per the django 2 documentation on testing the response resolver

    # class-based views need to be compared by name, as the functions
    # generated by as_view() won't be equal
    self.assertEqual(response.resolver_match.func.__name__, MyView.as_view().__name__)
    

    In your case:

    self.assertEqual(
            found.func.__name__,
            views.HomePageView.as_view().__name__
        )