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

时间:2016-10-03 06:38:21

标签: django django-templates django-testing

在django中,您可以测试天气,您的视图正在渲染正确的模板

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

但是如果你想测试使用的模板是否正在从正确的模板扩展/继承,那该怎么办呢?

1 个答案:

答案 0 :(得分:3)

因为@ e4c5指出它是assertTemplateUsed

刚试过它:

应用程序/ 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')

应用程序/ 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')
]

模板/ template.html

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

应用程序/ 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项测试