• Django学习系列8:django测试客户端


    """向浏览器返回真正的HTML响应,添加一个新的测试方法"""
    
    
    from django.test import TestCase
    from django.urls import resolve
    from django.http import HttpRequest
    from django.template.loader import render_to_string
    
    from lists.views import home_page
    
    class HomePageTest(TestCase):
    
        def test_root_url_to_home_page(self):
            found = resolve('/')  # resolve是Django内部函数,用于解析URL,并将其映射到相应的视图函数上
            self.assertEqual(found.func, home_page)  # 检查解析网站根路径/时,是否能找到home_page
    
        def test_home_page_returns_correct_html(self):
            response = self.client.get('/')   # 1
    
            html = response.content.decode('utf8')   # 2
            self.assertTrue(html.startswith('<html>'))
            self.assertIn('<title>To-Do lists</title>', html)
            self.assertTrue(html.strip().endswith('</html>'))
    
            self.assertTemplateUsed(response, 'home.html')   # 3
    
    
    """
    代码解析:
        1、不是手动创建httprequest对象并调用view函数,直接调用self.client.get,将要测试的url传递给它。
        2、我们暂时把旧的测试留在那里,以确保一切正常。就像我们想象的那样。
        3、asserttemplateUsed是django测试用例类pro-提供给我们它允许我们检查用于呈现响应的模板(仅适用于测试客户端检索到的响应)
    """

    运行单元测试

    python manage.py test
    Creating test database for alias 'default'...
    System check identified no issues (0 silenced).
    ..
    ----------------------------------------------------------------------
    Ran 2 tests in 0.006s
    
    OK
    Destroying test database for alias 'default'...

    提交版本

    $ git status  # 会看见lists/tests.py,views.py,settings.py以及新建的templates文件夹
    $ git add .
    $ git diff --staged
    $ git commit -m "Refactor home page view to use a template——使用模板重构主页视图"
  • 相关阅读:
    Java里的堆(heap)栈(stack)和方法区(method)
    SpringMVC 的 Controller 返回各种视图的处理方式
    Nginx Open File Cache
    HandlerInterceptor与MethodInterceptor
    Mysql的with rollup分组统计功能(5.1以上版本)
    idea中@data不生效
    java中? extends T 和? super T解析
    java8排序
    spring boot gateway自定义限流
    spring boot添加logging不能启动且不报错
  • 原文地址:https://www.cnblogs.com/ranxf/p/11662525.html
Copyright © 2020-2023  润新知