lundi 22 juin 2020

Test timezone in Django model

I am trying to test a model in django but I faced a issue with the DateTimeField(auto_now_add=True) method. I see that since I am asserting equal to the model creation, the message error is telling me that there is a difference of almost one millisecond. I've tried to find the solution but I don't know how to fix this issue. Here is the code:


class Contact(models.Model):
    name = models.CharField(max_length=80, blank=False)
    email = models.EmailField(blank=False)
    subject = models.CharField(max_length=40, blank=False)
    message = models.TextField(blank=False)
    created_on = models.DateTimeField(auto_now_add=True)
    active = models.BooleanField(default=False)

    class Meta:
        ordering = ['created_on']

    def __str__(self):
        return 'Contact {} by {}'.format(self.contact, self.name)

# test_cotact_model

def test_cotact_model(self):
        contact = Contact.objects.create(
            name = 'neil',
            email='neil@email.com',
            subject= 'this is a test.',
            message = 'test',
            created_on = timezone.now(),
            active = False,
        )
        contact.save()
        self.assertEquals(contact.name, 'neil')
        self.assertEquals(contact.email, 'neil@email.com')
        self.assertEquals(contact.subject, 'this is a test.')
        self.assertEquals(contact.message, 'test')
        self.assertEquals(contact.created_on, timezone.now())
        self.assertEquals(contact.active, False)

# Error

self.assertEquals(contact.created_on, timezone.now())
AssertionError: datetime.datetime(2020, 6, 22, 19, 0, 54, 413700, tzinfo=<UTC>) != datetime.datetime(2020, 6, 22, 19, 0, 54, 414675,
 tzinfo=<UTC>)

I have even saved the timezone.now() in a variable also changed the assertEquals() method for the timezone after the contact.save() command to see whether I could match the time but with no success.

Aucun commentaire:

Enregistrer un commentaire