简体   繁体   English

Django 测试集 created_at 字段

[英]Django test set created_at field

I have following model in Django ( models.py )我在 Django 中有以下模型( models.py

from django.db import models

# Create your models here.

class Session(models.Model):
  session_token = models.TextField(default="")
  code = models.CharField(max_length= 5, default="")
  active = models.BooleanField(default=False)
  created_at = models.DateTimeField(auto_now_add=True)
  updated_at = models.DateTimeField(auto_now=True)

Now, I have following function to be tested.现在,我有以下功能需要测试。

def get_active_session_older_than_hours(older_than_hours):
  older_date_time = datetime.datetime.now() - datetime.timedelta(hours=older_than_hours)
  data = Session.objects\
    .filter(active=True, updated_at__lte=older_date_time)\
    .values_list('code')
  return data

I want to test it.我想测试一下。

from django.test import TestCase


#Working fine
class ActiveSessionsNotPreset(TestCase):
  def test(self):
    data = get_active_session_older_than_hours(3)
    self.assertEqual(len(data), 0)


#This is not working.
#It is not getting the result.
class ActiveSessionPresent(TestCase):
  def setUp(self):
    older_date_time = datetime.datetime.now() - datetime.timedelta(hours=4)
    Session.objects.create(session_token='',
                                     code='US', active=True,
                                     created_at=older_date_time,
                                     updated_at=older_date_time)
  def test(self):
    data = get_active_session_older_than_hours(3)
    print("DEVENDER data " + str(data))
    self.assertEqual(len(data), 1)

In the second test case, I am not getting any result.在第二个测试用例中,我没有得到任何结果。 What is the correct way to force created_at and updated_at ?强制created_atupdated_at的正确方法是什么?

Simplest way would be to use .update() as it would do UPDATE SQL statement that will not call any of Django methods最简单的方法是使用 .update() ,因为它会执行不会调用任何 Django 方法的 UPDATE SQL 语句

session = Session.objects.create(session_token='', ...).
session.filter(pk=session.pk).update(updated_at=older_date_time,..)

Other ideas are fixtures or mocking其他想法是固定装置或嘲笑

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM