django - 如何在 Django 中测试 "render to template"函数? (测试驱动)

标签 django testing tdd django-views

我应该如何测试这些功能?他们所做的只是渲染 html 页面并将一些对象传递给 html 页面。

def index(request):
    companies = Company.objects.filter(approved = True);
    return direct_to_template(request, 'home.html', {'companies': companies} );

最佳答案

可以测试以下内容:

  1. 响应码
  2. 使用的模板
  3. 模板包含一些特定的文本

代码看起来像这样:

    from django.test import Client, TestCase
    from django.urls import reverse
    
    class TestPage(TestCase):
    
       def setUp(self):
           self.client = Client()
    
       def test_index_page(self):
           url = reverse('index')
           response = self.client.get(url)
           self.assertEqual(response.status_code, 200)
           self.assertTemplateUsed(response, 'index.html')
           self.assertContains(response, 'Company Name XYZ')

关于django - 如何在 Django 中测试 "render to template"函数? (测试驱动),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10608681/

相关文章:

javascript - 如何在javascript中模拟文件?

testing - 鼓励管理层放弃手动测试并以正确的方式做事

python - Heroku : "Please supply the ENGINE value" 中的 Django 错误

Django-oscar 产品图片错误

python - 如何在 virtualenv 中强制使用新版本的 Django?

linux - 如何监视 linux 二进制文件以测试 shell 脚本

python - Openid报错: Received "invalidate_handle" from server是什么原因

testing - 无法从 teamcity 运行 nunit 测试

testing - 如何在 Go 中测试 os.exit 场景

unit-testing - Laravel 5.1 中的模拟请求用于(实际)单元测试