Django:测试模板是否继承了正确的模板

Django: Testing if the template is inheriting the correct template

在 Django 中,您可以像这样测试您的视图是否呈现正确的模板

    def test_view_renders_correct_template(self):
        response = self.client.get("/some/url/")
        self.assertTemplateUsed(response, 'template.html')

但是如果您想测试使用的模板是否来自正确的模板extending/inheriting,该怎么办。

所以正如@e4c5 指出的那样assertTemplateUsed

刚刚测试过:

app/views.py

from django.shortcuts import render_to_response


def base_index(request):
    return render_to_response('base.html')


def template_index(request):
    return render_to_response('template.html')

app/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^base$', views.base_index, name='base'),
    url(r'^template$', views.template_index, name='template')
]

templates/template.html

{% extends 'base.html' %}
{% block content %}
  <div>help</div>
{% endblock %}

app/tests.py

from django.test import TestCase


class TemplateTest(TestCase):
    def test_base_view(self):
        response = self.client.get('/base')
        self.assertTemplateUsed(response, 'base.html')
        self.assertTemplateNotUsed(response, 'template.html')

    def test_template_view(self):
        response = self.client.get('/template')
        self.assertTemplateUsed(response, 'template.html')
        self.assertTemplateUsed(response, 'base.html')

所有 2 个测试都通过了