In my selenium test below I'm trying to test my Analytics model. I'm using a mock of an Analytics model instance from class AnalyticsFactory.
When I run this test everything works fine except I get an error for the timestamp field in the Analytics model. Note: I'm using timezone.now() for this.
It seems like the time from when I run the test and when the time is assigned to the Analytics factory is slightly different. For example this is the error I'm getting:
AssertionError: datetime.datetime(2022, 4, 8, 13, 3, 28, 153988, tzinfo=<UTC>) != datetime.datetime(2022, 4, 8, 13, 3, 28, 48016, tzinfo=<UTC>)
in the error above 153988 and 48016 are different
Is there a way I could set a 'fake' timezone object instead of using timezone.now()? Since it seems like 'now' is so precise that I can't get this to work.
test_models.py:
from django.utils import timezone
from django.test import TestCase
from myapp.tests.factories import UserFactory, AnalyticsFactory
from myapp.models import Analytics
class MyTestCase(TestCase):
def setUp(self):
self.admin = UserFactory(
username='first.last@gmail.com',
email='first.last@gmail.com',
password=12345
)
self.a1 = AnalyticsFactory(
user=self.admin,
timestamp=timezone.now(),
views=10
)
def test_analytics(self):
a = Analytics.objects.get(id=6)
self.assertEqual(a.views, 10)
self.assertEqual(a.user, self.admin)
self.assertEqual(a.timestamp, self.a1.timestamp) <--- not working
self.assertEqual(response.status_code, 200)
factories.py:
import factory
from myapp.models import Analytics
from user_profile.models import User
import mock
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
django_get_or_create = (
'username',
'email',
'password'
)
class AnalyticsFactory(factory.django.DjangoModelFactory):
class Meta:
model = Analytics
django_get_or_create = (
'timestamp',
'views',
)
user = factory.SubFactory(UserFactory)
models.py:
from django.db import models
from django.utils import timezone
from user_profile.models import User
class Analytics(models.Model):
user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
timestamp = models.DateTimeField(default=timezone.now, blank=True)
views = models.IntegerField(default=1)