466   Django Python

Django 框架强大之处在于功能丰富,下面要说说关于测试方法的使用

 

1,创建一个有bug的方法

$ vim polls/models.py
import datetime

from django.db import models
from django.utils import timezone

class Question(models.Model):
    # 如果文章是未来发布的,明显不符合 published_recently,但却能获取到,有bug
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
		

 

2,创建测试方法来检验下

$ vim polls/tests.py

import datetime

from django.utils import timezone
from django.test import TestCase

from .models import Question


class QuestionMethodTests(TestCase):

    def test_was_published_recently_with_future_question(self):
        """
        was_published_recently() should return False for questions whose
        pub_date is in the future.
        """
        time = timezone.now() + datetime.timedelta(days=30)
        future_question = Question(pub_date=time)
        self.assertIs(future_question.was_published_recently(), False)

 

 

3,执行测试方法

$ python manage.py test polls

Creating test database for alias 'default'...
======================================================================
FAIL: test_was_published_recently_with_future_question (polls.tests.QuestionMethodTests)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/path/to/mysite/polls/tests.py", line 16, in test_was_published_recently_with_future_question
    self.assertIs(future_question.was_published_recently(), False)
AssertionError: True is not False

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)
Destroying test database for alias 'default'...

 

提示测试不通过 FAILED

 

4,修复bug

$ vim polls/models.py
def was_published_recently(self):
    now = timezone.now()
    return now - datetime.timedelta(days=1) <= self.pub_date <= now

 

 

5,再来执行测试

$ python manage.py test polls
Creating test database for alias 'default'...
----------------------------------------------------------------------
Ran 1 test in 0.001s

OK
Destroying test database for alias 'default'...

 

这回测试通过拉!

 

Django的测试流程如上所述,通过polls/tests.py编写前缀为test的方法执行来测试

更多测试样例请参考官网




Leave a Reply

Your email address will not be published. Required fields are marked *