簡體   English   中英

在Django模型中測試日期的錯誤

[英]Error testing dates in Django models

我正在努力測試一些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'...

我在外殼上進行了一些手動測試,並應用了相同的過濾條件,它返回了我兩分鍾前剛剛創建的記錄。 我肯定還有另一件事想念。

注意:我進行這項測試的日期是2013/06/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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM