0

いくつかの Django モデルのテストに苦労しています。関連するコードは次のとおりです。

モデル:

class Check(models.Model):
    date = models.DateTimeField(auto_now_add=True)
    ...

テスト中の機能:

def get_today_records(model):
    today = datetime.today()
    today_records = model.objects.filter(
        date__year=today.year,
        date__month=today.month,
        date__day=today.day)
    return today_records

テストファイル:

def setUp(self):
        self.today_check = models.Check.objects.create(
            ...
            date=datetime.today())

def test_get_today_records(self):
        past_check = self.today_check
        past_check.date = datetime(2012, 1, 1)
        past_check.save()
        today_records = get_today_records(models.Check)
        self.assertTrue(self.today_check in today_records,
                        'get_today_records not returning today records')
        self.assertTrue(past_check not in today_records,
                        'get_today_records returnig older records')

エラー:

======================================================================
Traceback (most recent call last):
  File "C:\..\tests.py", lin
e 32, in test_get_today_records
    'get_today_records not returning today records')
AssertionError: get_today_records not returning today records

----------------------------------------------------------------------
Ran 2 tests in 0.018s

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

シェルでいくつかの手動テストを行い、同じフィルター基準を適用したところ、2 分前に作成したばかりのレコードが返されました。私が見逃しているものが他にあるはずです。

注: このテストを実行した日付は 2013/06/1 です

前もって感謝します

4

1 に答える 1

1

テスト機能でpast_check = self.today_checkは、期待どおりに新しいレコードを作成せず、データベース内の既存のレコードを変更します。

を実行するpast_check.save()と、データベースにある単一のレコードが過去の更新日で更新されます。

テストでは、おそらく次のようなものが必要です。

past_check = models.Check.objects.create(date=datetime(2012, 1, 1))

それ以外の:

past_check = self.today_check
past_check.date = datetime(2012, 1, 1)
past_check.save()
于 2013-06-02T23:21:33.003 に答える