问题
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