gpt4 book ai didi

python 单元测试: assertEqual on same objects throwing AssertionError

转载 作者:太空狗 更新时间:2023-10-29 22:02:26 24 4
gpt4 key购买 nike

我有一个类

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'

测试作为

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)

当我运行测试时,我看到的错误是

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() 使用 == 运算符来比较类。用户定义类的默认 == 运算符按对象标识比较实例。这意味着只有当两个实例是相同实例时,它们才被视为相等。

关于 python 单元测试: assertEqual on same objects throwing AssertionError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11549309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com