Opened 6 months ago
Closed 6 months ago
#35481 closed Bug (invalid)
assertTemplateUsed false positive
Reported by: | Shiva Kumar | Owned by: | nobody |
---|---|---|---|
Component: | Testing framework | Version: | dev |
Severity: | Normal | Keywords: | |
Cc: | Triage Stage: | Unreviewed | |
Has patch: | no | Needs documentation: | no |
Needs tests: | no | Patch needs improvement: | no |
Easy pickings: | no | UI/UX: | no |
Description
assertTemplateUsed can be used both as a function and as a context manager.
When used as a function, both request
and template_name
should be passed. When used as a context manager, only template_name
needs to be passed.
Consider a test case,
def test_template_used(self): resp = self.client.get("/home/") self.assertEqual(resp.status_code, 200) self.assertTemplateUsed("home.html")
In this case, the last statement returns a context manager object, resulting in no assertion checks, and the test case passes. The test case passed even if the wrong template_name
is provided.
This scenario arises solely because assertTemplateUsed
assumes that when only `template_name` is provided, it must have been used as a context manager.
Had there been a keyword-only argument restriction, this scenario wouldn't have arisen.
This bug is applicable to assertTemplateNotUsed
as well.
If the bug is deemed valid, please assign the ticket to me.
Hello Shiva Kumar,
Thank you for your report, and helping make Django better.
Django's testing framework, like many parts of the framework, relies heavily on the dynamic nature of Python. This dynamic nature means that functions can often be used in multiple ways, as you pointed out. While Django provides a lot of built-in validations and utilities, it cannot cover every possible misuse case. Enforcing stricter checks or keyword-only arguments could reduce some flexibility and introduce backward compatibility issues.
In my opinion, the docs are clear about the correct usage of
assertTemplateUsed
. It says:Given the above, I'll close the ticket accordingly, but if you disagree, you can consider starting a new conversation on the Django Forum, where you'll reach a wider audience.