django测试断言不相等
尝试测试选择器层IM我的应用程序,但是Django不要通过Simle测试。 Queryset看起来很相似,也许我丢了一些东西。
test.py
from django.test import TestCase
from books.models import Author, Book
from books.selectors import get_books
class SelectorTest(TestCase):
def setUp(self):
self.author = Author.objects.create(
name='test_author'
)
self.book = Book.objects.create(
name='test_book',
category='Drama',
release_date='2001-01-01',
author=self.author,
is_read=True
)
def test_get_books(self):
self.assertEqual(get_books(), Book.objects.all())
selectors.py
from django.db.models.query import QuerySet
from books.models import Book
def get_books() -> QuerySet[Book]:
"""
Return all objects of Book model.
"""
books = Book.objects.all()
return books
断言误差
AssertionError: <QuerySet [<Book: test_book>]> != <QuerySet [<Book: test_book>]>
Trying to test selector layer im my app, but django dont pass simle test. Querysets looks quite similar, maybe i lost something.
test.py
from django.test import TestCase
from books.models import Author, Book
from books.selectors import get_books
class SelectorTest(TestCase):
def setUp(self):
self.author = Author.objects.create(
name='test_author'
)
self.book = Book.objects.create(
name='test_book',
category='Drama',
release_date='2001-01-01',
author=self.author,
is_read=True
)
def test_get_books(self):
self.assertEqual(get_books(), Book.objects.all())
selectors.py
from django.db.models.query import QuerySet
from books.models import Book
def get_books() -> QuerySet[Book]:
"""
Return all objects of Book model.
"""
books = Book.objects.all()
return books
assertion error
AssertionError: <QuerySet [<Book: test_book>]> != <QuerySet [<Book: test_book>]>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用Django的
testcase
类中使用transactionTestcase.AsserTactionTestcase.AsserTactionTestcase.AsserTactionTestCase.sertcerysetequal
。 在此处查看文档。在您的情况下:
You can use the
TransactionTestCase.assertQuerysetEqual
assertion from Django'sTestCase
class. Check the documentation here.In your case:
要测试两个QuerySets返回相同的对象,但不一定按相同的顺序返回(当然,假设同一基础模型都在查询相同的基础模型):
这是测试失败时的一条相当有用的消息。您可以获得一个且未确定的PK,而不仅仅是一个不相等的“消息”。
我认为,如果您使用
list()
而不是set> set> set()
您请检查两个都以相同的顺序返回相同的对象。To test that two querysets return the same objects but not necessarily in the same order (assuming both query the same underlying Model, of course):
This makes a reasonably useful message when the test fails. You get the pks which are in one and not the other identified, not just a not equal" message.
I think if you use
list()
instead ofset()
you get to check that both return the same objects in the same order.