Djangoのチュートリアルに取り組んでいます。
Djangoで作成したアプリケーションをテストするという場面です。
まずバグの確認をし、テストをするという手順ですが、バグの確認の時点で期待するバグではないエラーが起きます。
timedeltaの計算がうまくいっていないように思ったのですが、自力で解決できず、お力添えいただけると幸いです。
$ python manage.py shell Python 3.7.0 (default, Jun 28 2018, 08:04:48) [MSC v.1912 64 bit (AMD64)] Type 'copyright', 'credits' or 'license' for more information IPython 6.5.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: import datetime In [2]: from django.utils import timezone In [3]: from polls.models import Question In [4]: future_question = Question(pub_date=timezone.now() + datetime.timedelta(days=30)) In [5]: future_question.was_published_recently() --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-5-ac756cd69bcb> in <module>() ----> 1 future_question.was_published_recently() ~\Desktop\git-work\test\Python\Django\mysite\polls\models.py in was_published_recently(self) 10 return self.question_text 11 def was_published_recently(self): ---> 12 return self.pub_date >= timezone.now() - timezone.timedalta(days=1) 13 14 AttributeError: module 'django.utils.timezone' has no attribute 'timedalta'
↑本当はここでエラーではなく"True"が返ってきてほしい
models.pyとtests.pyは以下の通りです。(importの問題?と思ったのでコメントアウトしたりしてますが、上記エラーが発生した状態のファイルが以下の通りです)
$ cat polls/models.py import datetime #from datetime import datetime, date, timedelta from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - timezone.timedalta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200, default='') votes = models.IntegerField(default=0) def __str__(self): return self.choice_text
$ cat polls/tests.py from django.test import TestCase from django.utils import timezone import datetime #from datetime import datetime, timedelta from .models import Question class QuestionModelTests(TestCase): def test_was_published_recently_with_future_question(self): time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) self.assertIs(future_question.was_published_recently(), False)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/06/19 11:44