关于django:python单元测试:对抛出AssertionError的相同对象的assertEqual

python unit test: assertEqual on same objects throwing AssertionError

我有一个班

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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'

我把1〔0〕作为

1
2
3
4
5
6
7
8
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)

当我运行测试时,我将错误视为

1
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>

即使两个对象相同。

我这里有什么东西不见了吗?


assertEqual()使用==运算符比较类。用户定义类的默认==运算符按对象标识比较实例。这意味着只有当两个实例是同一个实例时,才认为它们是相等的。


比较型号ID或PK,就可以了。


AssertionError是正确的。您的get_playlist_with_id返回的是Queryset而不是Playlist实例。如果希望get_playlist_with_id返回单个实例,那么应该使用get而不是filter