2016-10-03 79 views
1

Django中你可以測試天氣視圖渲染正確的模板這樣Django的:被測試,如果模板繼承了正確的模板

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

,但如果你想測試是否使用模板擴展什麼/繼承從正確的模板。

+1

它仍然assertTemplateUsed – e4c5

回答

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個測試通過