When visiting a page that does not exist, the site displays the 404 page, as expected.
However, when running unit tests to check that the 404 page is displayed, the test fails because the HTTP status code is 200 rather than 404.
def test_client_detail_view_with_invalid_customer(self):
self.client.login(username="test_user", password="password123")
response = self.client.get("/customer/123456/")
self.assertEqual(response.status_code, 404)
AssertionError: 200 != 404
handler404 = SystemView.as_view(template_name="pages/system/not-found.html", status=404)
Hi Alan,
Your ClientListView function still returns a 200 status code.
Maybe you could put some conditions to check the user's existence.
If not found, then return this in the view function. By right, the 404 status code will trigger.
return HttpResponseNotFound("<h1>User not found</h1>")
FYI 'Customers' has now been renamed to 'Clients' in order to fit with the company's Domain Language (although the problem still persists)...
When running in the browser, the 404 is returned correctly for invalid routes, but it does not work in unit tests. In unit tests the status code 200 is returned, even for invalid routes.
View:
class ClientListView(LoginRequiredMixin, PermissionRequiredMixin, ListView):
permission_required = "sop.view_client"
permission_denied_message = "You do not have permission to view client information."
template_name = "pages/sop/client_list.html"
context_object_name = "clients"
model = Client
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context = KTLayout.init(context)
return context
path("clients", ClientListView.as_view(), name="client-list"),
def test_client_detail_view_with_invalid_commercial_client(self):
self.client.login(username="sop_user", password="P@55w0Rd")
response = self.client.get("/sop/client/com/123456/")
self.assertEqual(response.status_code, 404)
handler404 = SystemView.as_view(template_name="pages/system/not-found.html", status=404)
handler500 = SystemView.as_view(template_name="pages/system/error.html", status=500)
Hi Alan,
Thank you for contacting us. We need to see your function that generates results for page "/customer/123456/". Even though the user with this id is not found, the page URL to "customer" is still valid.
If the customer is not found, you should return the 404 status.
The handler404 will work for undefined routes. Eg. "customerxyz/123"
Thanks