Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert django uses certain template in pytest

In the unittest style, I can test that a page uses a particular template by calling assertTemplateUsed. This is useful, for example, when Django inserts values through a template, so that I can't just test string equality.

How should I write the equivalent statement in pytest?

I've been looking in pytest-django but don't see how to do it.

like image 237
Hatshepsut Avatar asked Aug 28 '17 20:08

Hatshepsut


People also ask

Can I use Pytest with Django?

pytest-django Documentation. pytest-django is a plugin for pytest that provides a set of useful tools for testing Django applications and projects.

What does Pytest Mark Django_db do?

mark. django_db - request database access. This is used to mark a test function as requiring the database.

How do I add a template to Django?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

Does Django use Pytest or Unittest?

Django's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach.


1 Answers

As phd stated in a comment, use the following to assert that a template file is actually used in a view:

response = client.get(article.get_absolute_url())
assert 'article_detail.html' in (t.name for t in response.templates)

Update: Since v3.8.0 (2020-01-14) pytest-django makes all of the assertions in Django's TestCase available in pytest_django.asserts. See Stan Redoute's answer for an example.

like image 188
jnns Avatar answered Oct 26 '22 23:10

jnns