• Django1.10文档学习笔记四


    16 应用测试

    编写第一个测试程序

    先在admin后台创建一个发布日期在未来的question,shell中验证这个bug

    >>> import datetime

    >>> from django.utils import timezone

    >>> from polls.models import Question

    >>> q.was_published_recently()

    True

    通过自动化测试来完成这个操作

    Models.py

    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date <= now

    test.py

    from django.test import TestCase
    import datetime
    from django.utils import timezone
    from .models import Question

    # Create your tests here.

    '''
    问卷测试
    '''
    def
    test_was_published_recently_with_old_question(self):
        """
            日期超过1天的将返回False。这里创建了一个30天前发布的实例。
        """
        
    time = timezone.now() - datetime.timedelta(days=30)
        old_question = Question(pub_date=time)

        self.assertIs(old_question.was_published_recently(), False)


    def test_was_published_recently_with_recent_question(self):
        """
          最近一天内的将返回True。这里创建了一个1小时内发布的实例。
        """
        
    time = timezone.now() - datetime.timedelta(hours=1)
        recent_question = Question(pub_date=time)
        self.assertIs(recent_question.was_published_recently(), True)

    17 测试一个视图

    测试用客户端

    >>> from django.test.utils import setup_test_environment

    >>> setup_test_environment

    <function setup_test_environment at 0x0310DC00>

    >>>

    >>> from django.test import Client #导入客户端

    >>> client=Client()#创建一个实例

    >>> response=client.get('/')#/获取响应

    Not Found: /

    >>> response.status_code#从这个地址返回的是404

    404

    >>> from django.urls import reverse

    >>> response=client.get(reverse('polls:index'))#通过polls获取内容

    >>> response.status_code

    200

    >>> response.content#取得response的正文内容

    b'    <ul>                    <li>                                <a href="/polls/3/">                    test case                </a>                                <a href="/polls/3/">

                       test case                </a>            </li>                    <li>                                <a href="/polls/2/">                    what is your name ?

            </a>                                <a href="/polls/2/">                    what is your name ?                </a>            </li>                    <li>                

             <a href="/polls/1/">                    what is up?                </a>                                <a href="/polls/1/">                    what is up?                </a>

      </li>            </ul> '

    >>>

    修改views.py

    # 最近的5个调查问卷
    def get_queryset(self):
        # return Question.objects.order_by('-pub_date')[:5]

    #查询的结果在当前时间之前,不包含将来的时间

       return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5]

    编写自动作测试

     from django.test import TestCase
    import datetime
    from django.utils import timezone
    from .models import Question
    from django.urls import reverse

    # Create your tests here.

    '''
    问卷测试
    '''


    def
    test_was_published_recently_with_old_question(self):
        """
            日期超过1天的将返回False。这里创建了一个30天前发布的实例。
        """
        
    time = timezone.now() - datetime.timedelta(days=30)
        old_question = Question(pub_date=time)

        self.assertIs(old_question.was_published_recently(), False)


    def test_was_published_recently_with_recent_question(self):
        """
          最近一天内的将返回True。这里创建了一个1小时内发布的实例。
        """
        
    time = timezone.now() - datetime.timedelta(hours=1)
        recent_question = Question(pub_date=time)
        self.assertIs(recent_question.was_published_recently(), True)


    '''
    创建question,
    question_text   问卷的文本内容
    days 当前时间的偏移天数,负值表过去,正值表将来
    '''


    def
    create_question(question_text, days):
        time = timezone.now() + datetime.timedelta(days=days)
        return Question.objects.create(question_text=question_text, pub_date=time)


    class QuestionViewTests(TestCase):
        #
        
    def test_index_viewwith_no_questions(self):
            response = self.client.get(reverse('polls:index'))
            # 返回状态码正常
            
    self.assertEquals(response.status_code, 200)
            self.assertContains(response, 'no polls are available.')
            self.assertQuerysetEqual(response.context['latest_question_list'], [])


    def test_index_view_with_a_past_question(self):
        """        发布日期在过去的问卷将在index页面显示。        """
        
    create_question(question_text="Past question.", days=-30)
        response = self.client.get(reverse('polls:index'))

        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            ['<Question: Past question.>']
        )


    def test_index_view_with_a_future_question(self):
        """        发布日期在将来的问卷不会在index页面显示        """
        
    create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse('polls:index'))

        self.assertContains(response, "No polls are available.")
        self.assertQuerysetEqual(response.context['latest_question_list'], [])


    def test_index_view_with_future_question_and_past_question(self):
        """        即使同时存在过去和将来的问卷,也只有过去的问卷会被显示。        """
        
    create_question(question_text="Past question.", days=-30)
        create_question(question_text="Future question.", days=30)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            ['<Question: Past question.>']
        )


    def test_index_view_with_two_past_questions(self):
        """        index页面可以同时显示多个问卷。        """
        
    create_question(question_text="Past question 1.", days=-30)
        create_question(question_text="Past question 2.", days=-5)
        response = self.client.get(reverse('polls:index'))
        self.assertQuerysetEqual(
            response.context['latest_question_list'],
            ['<Question: Past question 2.>', '<Question: Past question 1.>']
        )

  • 相关阅读:
    java爬虫(jsoup)
    python之模块分类(六)
    Python之模块分类(五)
    python之模块分类(四)
    python之模块分类(三)
    Linux系统引导过程
    python之模块分类(二)
    linux 进程管理
    python之模块分类(一)
    python基础之模块导入
  • 原文地址:https://www.cnblogs.com/retacn-yue/p/6194185.html
Copyright © 2020-2023  润新知