# Writing your-first Django-app-part 5 -test
11449 ワード
バグの確認
もし未来の時間が伝わったらwas_published_recently()は何を返しますか?
D:\desktop\todoList\Django\mDjango\demoSite>python manage.py shell
Python 2.7.6 (default, Nov 10 2013, 19:24:18) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> import datetime
>>> from django.utils import timezone
>>> from DemoAppPoll.models import Question
>>> future_question = Question(pub_date=timezone.now()+datetime.timedelta(days=30))
>>> future_question.was_published_recently()
True
テストを書いてバグを暴露する
上記の手順をtestとして以下のように書きます.
DemoAppPoll/tests.py
import datetime
from django.test import TestCase
from django.utils import timezone
from DemoAppPoll.models import Question
class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
time = timezone.now()+datetime.timedelta(days=30)
furture_question = Question(pub_date=time)
self.assertEqual(furture_question.was_published_recently(),False)
テストの実行:
python manage.py test DemoAppPoll
1>「python manage.py test DemoAppPoll」DemoAppPoll(APP)からtestsを探す.
2>「django.test.TestCase」、テスト例、DemoAppPollはTestCaseパラメータとして入力されます.
class QuestionMethodTests(TestCase):
3>テスト用の特別なデータベースを作成
4>assertEqual()最後に判断する.
バグの修正
DemoAppPoll/models.py
def was_published_recently(self):
now = timezone.now()
return now-datetime.timedelta(days=1) <=self.pub_date<=now
#return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
従来の片側不等式から、現在の二国間不等式に変更すればよい.
テスト結果:
D:\desktop\todoList\Django\mDjango\demoSite>python manage.py test DemoAppPoll
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.318s
OK
Destroying test database for alias 'default'...
その他のテスト例
以前の問題なら?最近の問題なら?
DemoAppPoll/tests.py
def test_was_published_rencently_with_old_question(self):
time = timezone.now()-datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertEqual(old_question.was_published_recently(),False)
def test_was_published_rencently_with_recent_question(self):
time = timezone.now()-datetime.timedelta(hours=1)
recent_question=Question(pub_date=time)
self.assertEqual(recent_question.was_published_recently(),True)
viewをテスト
The Django test clientはクライアントをテストする。
D:\Documents\mandroid\demoSite>python manage.py shell
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> from django.test import Client
>>> client =Client()
>>> response=client.get('/')
>>> response.status_code
404
>>> from django.core.urlresolvers import reverse
>>> response=client.get(reverse('DemoAppPoll:index'))
>>> response.status_code
200
>>> response.content
'\r
<ul>\r
\r
\r
\t\t<li><a href="/DemoAppPoll/1/">what's up </a></li>\r
\r
\'
>>> from DemoAppPoll.models import Question
>>> from django.utils import timezone
>>> q=Question(question_text="who is your favourite Beatle",pub_date=timezone.now())
>>> q.save()
>>> response=client.get('/DemoAppPoll/')
>>> response.content
'\r
<ul>\r
\r
\r
\t\t<li><a href="/DemoAppPoll/3/">who is your favourite Beatle</a></li>\r
\r
\t\t<li><a href="/DemoAppPoll/2/">what time is it?</a></li>\r
\r
</ul>\r
'
>>> response.context['latest_question_list']
[<Question: who is your favourite Beatle>, <Question: what's up >, <Question: what time is it?>]
>>>
DemoAppPoll/viewsをアップグレードします。py
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.utils import timezone
私たちのviewをテストします。index
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_view_with_a_future_question(self):
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('DemoAppPoll:index'))
self.assertContains(response, "No polls are available.",
status_code=200)
self.assertQuerysetEqual(response.context['latest_question_list'], [])
それともいくつかのステップです
1>必要なパッケージのインポート:
from django.core.urlresolvers import reverse
2>クラスの記述、TestCaseパラメータの入力
3>試験方法の作成:a)インスタンスの作成,b)シミュレーション要求,c)比較結果
DemoAppPoll/viewsをテストします。py/DetailView
まず、DemoAppPoll/viewsを少し修正します.py:
class DetailView(generic.DetailView):
model = Question
template_name = "DemoAppPoll/detail.html"
def get_queryset(self):
#return Question.objects.order_by('-pub_date')[:5]
return Question.objects.filter(pub_date__lte=timezone.now())
DemoAppPoll/xx/に直接アクセスする人がいる場合は、空に戻ります.
次のテストを記述します.
class QuestionIndexDetailTests(TestCase):# , TestCase
#
def test_detail_view_with_a_future_question(self):
#
future_question=create_question(question_text="Future question", days=5)
#
response = self.client.get(reverse('DemoAppPoll:detail',args=(future_question.id,)))
# .
self.assertEqual(response.status_code,404)
# .
def test_detail_view_with_a_past_question(self):
past_question=create_question(question_text="past question", days=-5)
response = self.client.get(reverse('DemoAppPoll:detail',args=(past_question.id,)))
self.assertContains(response,'past question')
テストのテクニック:
最後に、完全なテストファイルを添付します。
demoSite/DemoAppPoll/tests.py
# -*- coding: utf-8 -*-
import datetime
from django.test import TestCase
from django.utils import timezone
from DemoAppPoll.models import Question
from django.core.urlresolvers import reverse
class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
time = timezone.now() + datetime.timedelta(days=30)
furture_question = Question(pub_date=time)
self.assertEqual(furture_question.was_published_recently(), False)
def test_was_published_rencently_with_old_question(self):
time = timezone.now() - datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertEqual(old_question.was_published_recently(), False)
def test_was_published_rencently_with_recent_question(self):
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertEqual(recent_question.was_published_recently(), True)
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_view_with_no_question(self):
response = self.client.get(reverse('DemoAppPoll:index'))
self.assertEqual(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):
create_question(question_text="Past question", days=-30)
response = self.client.get(reverse("DemoAppPoll:index"))
self.assertQuerysetEqual(response.context['latest_question_list'],
['<Question: Past question>']
)
def test_index_view_with_a_future_question(self):
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('DemoAppPoll:index'))
self.assertContains(response, "No polls are available.",
status_code=200)
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('DemoAppPoll:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
)
def test_index_view_with_two_past_questions(self):
create_question(question_text="Past question 1.", days=-30)
create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse('DemoAppPoll:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
class QuestionIndexDetailTests(TestCase):# , TestCase
#
def test_detail_view_with_a_future_question(self):#
future_question=create_question(question_text="Future question", days=5)#
response = self.client.get(reverse('DemoAppPoll:detail',args=(future_question.id,)))# .
self.assertEqual(response.status_code,404)# .
def test_detail_view_with_a_past_question(self):
past_question=create_question(question_text="past question", days=-5)
response = self.client.get(reverse('DemoAppPoll:detail',args=(past_question.id,)))
self.assertContains(response,'past question')