Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Django Basics Test Time Model Tests

Noah Fields
Noah Fields
13,985 Points

now and course.created_at have equal values

When I run the test_course_creation test, I receive an error because now and course.created_at are exactly equal. Naturally, this means that neither is less than the other, thus the test fails (though exactly why this occurs is something I'm uncertain of). However, if I change it to assertIs, it also fails, even though the values are identical. I know this thanks to the console output that I am given regarding the failure.

My code is here:

def test_course_creation(self):
    Ensure that the course is created at a time before "now"
    course = Course.objects.create(
        title="Dragon Regular Expressions",
        description="Learn to write dragony expressions in Dragish"
   now = timezone.now()
   self.assertLess(course.created_at, now)

Edit: Yes, it also fails when assertLess is replaced with assertIs. assertLess does not fail every time, though, just sometimes.

Hey Noah,

I had this same problem. You could do one of two things; either change the assert statement to assertLessEqual, or import datetime, create a time delta equal to 1 microsecond, and add that to the now variable. That way if the now is created at the same times as the course, it will still have a time of 1 microsecond in the future.

I'm not sure what the more correct solution is to this in terms of writing solid tests, and perhaps someone with more experience could chime in.


1 Answer

Haydar Al-Rikabi
Haydar Al-Rikabi
5,971 Points

'assertIs' does not compare if two values are equal, but rather if the two equal values belong to one object in memory (True) or to two separate objects in memory (False).