0

I'm struggling testing some Django models, you can see the relevant code here:

models:

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

function being tested:

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

test file:

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')

the error:

======================================================================
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'...

I did some manual tests on the shell and applied the same filter criteria and it returned the record I just created two minutes ago. There must be another thing I'm missing.

Note: the date I ran this test is 2013/06/1

Thanks in advance

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 回答