PageRenderTime 84ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/regressiontests/get_or_create_regress/tests.py

https://code.google.com/p/mango-py/
Python | 64 lines | 32 code | 15 blank | 17 comment | 0 complexity | 7b8164889538176d4bdedbc40cd9a683 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from django.test import TestCase
  2. from models import Author, Publisher
  3. class GetOrCreateTests(TestCase):
  4. def test_related(self):
  5. p = Publisher.objects.create(name="Acme Publishing")
  6. # Create a book through the publisher.
  7. book, created = p.books.get_or_create(name="The Book of Ed & Fred")
  8. self.assertTrue(created)
  9. # The publisher should have one book.
  10. self.assertEqual(p.books.count(), 1)
  11. # Try get_or_create again, this time nothing should be created.
  12. book, created = p.books.get_or_create(name="The Book of Ed & Fred")
  13. self.assertFalse(created)
  14. # And the publisher should still have one book.
  15. self.assertEqual(p.books.count(), 1)
  16. # Add an author to the book.
  17. ed, created = book.authors.get_or_create(name="Ed")
  18. self.assertTrue(created)
  19. # The book should have one author.
  20. self.assertEqual(book.authors.count(), 1)
  21. # Try get_or_create again, this time nothing should be created.
  22. ed, created = book.authors.get_or_create(name="Ed")
  23. self.assertFalse(created)
  24. # And the book should still have one author.
  25. self.assertEqual(book.authors.count(), 1)
  26. # Add a second author to the book.
  27. fred, created = book.authors.get_or_create(name="Fred")
  28. self.assertTrue(created)
  29. # The book should have two authors now.
  30. self.assertEqual(book.authors.count(), 2)
  31. # Create an Author not tied to any books.
  32. Author.objects.create(name="Ted")
  33. # There should be three Authors in total. The book object should have two.
  34. self.assertEqual(Author.objects.count(), 3)
  35. self.assertEqual(book.authors.count(), 2)
  36. # Try creating a book through an author.
  37. _, created = ed.books.get_or_create(name="Ed's Recipes", publisher=p)
  38. self.assertTrue(created)
  39. # Now Ed has two Books, Fred just one.
  40. self.assertEqual(ed.books.count(), 2)
  41. self.assertEqual(fred.books.count(), 1)
  42. # Use the publisher's primary key value instead of a model instance.
  43. _, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id)
  44. self.assertTrue(created)
  45. # Try get_or_create again, this time nothing should be created.
  46. _, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id)
  47. self.assertFalse(created)
  48. # The publisher should have three books.
  49. self.assertEqual(p.books.count(), 3)