I have a web app that I am unit testing. I'm trying to test the drf serializers, but the serializers change the format of datetimes, so identical dates formatted differently are failing the test because they're not identical.
I've tried formatting the serializer timeDateField, but all of the strftime formats they use are zero-padded, and my test Users last-login attribute gives the date without zero-padding. I think the solution could be solved the way that the selected answer describes here but that seems a bit sketchy, and ideally, I, as someone who will have to maintain this code, want a cleaner or more pythonic solution.
Here is the test:
class UserTest(TestCase):
def setup(self):
last_login = datetime.datetime(2000, 1, 1, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
date_joined = datetime.datetime(2019, 2, 2, hour=2, minute=2, second=2, microsecond=2, tzinfo=None)
birthdate = timezone.now().date()
renewal = timezone.now().date()
return User.objects.create(username='test_user', first_name='test_first', last_name='test_last',
email='test_mail', last_login=last_login, date_joined=date_joined,
birthdate=birthdate, gender='U', renewal=renewal)
def test_user_serializer(self):
self.u = self.setup()
serializer = UserSerializer(self.u, many=False)
data = serializer.data
.....
# tests for serialized attributes
self.assertEquals((data['last_login']), self.u.last_login) # FAILING THE TEST
Here is the UserSerializer:
class UserSerializer(serializers.ModelSerializer):
last_login = serializers.DateTimeField
date_joined = serializers.DateTimeField
birthdate = serializers.DateField
renewal = serializers.DateField
class Meta:
model = User
fields = ('__all__')
Here is the error I am getting:
self.assertEquals(data['last_login'], self.u.last_login)
AssertionError: '2000-01-01T00:00:00Z' != datetime.datetime(2000, 1, 1, 0, 0)
In the model, the last_login attribute is a dateTimeField.
Should I be trying to change the formats of one of the elements being tested or is there a way to write a test that compares the dates irrespective of format?
Please advise. Thank you.