Testing 'class Meta' in Django models

╄→гoц情女王★ 提交于 2019-12-24 09:49:05

问题


How can you test ordering, unique and unique_together in Django models?


回答1:


Ordering - create a couple of instances, then just check if the order is right. Example:

self.assertEqual(list[0], a)
self.assertEqual(list[1], b)
etc

Unique - create an instance, try to create another one with the same unique field. Assert that there is an exception:

with self.assertRaises(IntegrityError):
    MyModel.objects.create(unique_field=the_same_value)

Unique Together is the same as unique.

Hope it helps!




回答2:


As stated in the MDN Django Tutorial Part 10, “You should test all aspects of your own code, but NOT any libraries or functionality provided as part of Python or Django.” See MDN's what you should test. To test what was written by you, you should access the meta attribute of the model class and the model's fields. For example, having defined the book model as follows:

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey('Author', on_delete=models.SETNULL, null=True)
    isbn = models.CharField('ISBN', max_length=13, unique=True)

    class Meta:
        unique_together(('title', 'author'),)
        ordering = ['author']

The Book model would be unit tested for unique, unique_together, and ordering as follows:

class BookModelTests(TestCase):
    @classmethod
    def setUpTestdata(cls):
        #create an author instance and a book instance

    def test_isbn_is_unique(self):
        book = Book.objects.get(id=1)
        unique = book._meta.get_field('isbn').unique
        self.assertEquals(unique, True)

    def test_book_is_unique(self):
        book = Book.objects.get(id=1)
        unique_together = book._meta.unique_together
        self.assertEquals(unique_together[0], ('title', 'author'))

    def test_book_ordering(self):
        book = Book.objects.get(id=1)
        ordering = book._meta.ordering
        self.assertEquals(ordering[0], 'author')


来源:https://stackoverflow.com/questions/46004217/testing-class-meta-in-django-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!