python unit test: assertEqual on same objects throwing AssertionError

daydreamer picture daydreamer · Jul 18, 2012 · Viewed 7.3k times · Source

I have a class as

class PlaylistManager(models.Manager):
    def add_playlist(self, name):
        playlist = Playlist(name=name)
        playlist.save()
        return playlist

    def get_playlist_with_id(self, id):
        return super(PlaylistManager, self).get_query_set().filter(pk=id)

class Playlist(models.Model):
    name = models.CharField(max_length=30)
    date_created = models.DateTimeField(auto_now_add=True)
    date_modified = models.DateTimeField(auto_now=True)
    deleted = models.BooleanField(default=False)
    objects = PlaylistManager() # is a customer manager

    def __repr__(self):
        return '<Playlist name:%s, date_created:%s, date_modified:%s, deleted:%s>' % \
                (self.name, self.date_created, self.date_modified, self.deleted)

    class Meta:
        db_table = 'playlists'

and i test as

def test_get_playlist(self):
    playlist = Utility.add_playlist()
    self.assertEqual(Playlist.objects.get_playlist_with_id(playlist.id), playlist)

class Utility():
    @staticmethod
    def add_playlist(playlist_name=PLAYLIST):
        return Playlist.objects.add_playlist(playlist_name)

When I run the test, I see error as

AssertionError: [<Playlist name:playlist, date_created:2012-07-18 19:54:12.265909+00:00, date_modified:2012-07-18 19:54:12.265955+00:00, deleted:False>] != <Playlist name:playlist, date_created:2012-07-18 19:54:12.265909+00:00, date_modified:2012-07-18 19:54:12.265955+00:00, deleted:False>

even when the two objects are same.

Is there anything I am missing here?

Answer

Sven Marnach picture Sven Marnach · Jul 18, 2012

assertEqual() uses the == operator to compare the classes. The default == operator of user-defined classes compares instances by object identity. This means two instances are only considered equal when they are the same instance.