Opened 2 days ago

Last modified 6 hours ago

#35571 new Bug

TypeError in assertTemplateUsed when using pathlib.Path as template_name

Reported by: Erik Z. Owned by: nobody
Component: Testing framework Version: 5.0
Severity: Normal Keywords: assertTemplateUsed
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: yes UI/UX: no

Description

Right now it is perfectly fine to use pathlib.Path as an template_name. This works fine for production as the template render fine. However when unit testing the assertTemplateUsed function throws a TypeError:

File "<stuff>/.local/lib/python3.12/site-packages/django/test/testcases.py", line 681, in _assert_template_used
        % (template_name, ", ".join(template_names)),
                          ^^^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: sequence item 0: expected str instance, PosixPath found

This happens because the template_name is stored as is.

Happened on 5.0.4

Attachments (1)

Screenshot 2024-07-03 143121.2.png (225.6 KB ) - added by Rish 14 hours ago.

Download all attachments as: .zip

Change History (6)

comment:1 by Natalia Bidart, 2 days ago

Component: Template systemTesting framework
Keywords: assertTemplateUsed added; template_name removed
Resolution: needsinfo
Status: newclosed

Hello Erik! Thank you for your report.

The PR you have submitted is not ideal in that the "production" code is coercing to str in multiple places and this could impact performance.
Following your description, and ideally, we should provide a fix within the Testing framework.

To fully understand this issue, I would need a minimal django project (views and tests) so we can reproduce this, triage it and review the fix accordingly.

comment:2 by Erik Z., 25 hours ago

Sure, I can understand that.
I prepared a project which should give an understanding on how the error works.
It can be found here: https://github.com/guserav/django_bug_test_template_name_str/
all important code should be in https://github.com/guserav/django_bug_test_template_name_str/commit/828d56b405c7932fdcf6c6c29a9038ce115628ed

comment:3 by Erik Z., 25 hours ago

Resolution: needsinfo
Status: closednew

comment:4 by Rish, 14 hours ago

I tried to reproduce this bug using the repo provided: https://github.com/guserav/django_bug_test_template_name_str/
Can't seem to reproduce it, all tests run just fine on django version 5.0.4. https://code.djangoproject.com/attachment/ticket/35571/Screenshot%202024-07-03%20143121.2.png
Can you please elaborate more on this?

Last edited 14 hours ago by Rish (previous) (diff)

comment:5 by Erik Z., 6 hours ago

The tests are deliberatly designed to run through. I removed the Exception assertions that made the tests work. Now the tests are failing.

Note: See TracTickets for help on using tickets.
Back to Top