PageRenderTime 7ms CodeModel.GetById 1ms app.highlight 4ms RepoModel.GetById 1ms 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
 1from django.test import TestCase
 2
 3from models import Author, Publisher
 4
 5
 6class GetOrCreateTests(TestCase):
 7    def test_related(self):
 8        p = Publisher.objects.create(name="Acme Publishing")
 9        # Create a book through the publisher.
10        book, created = p.books.get_or_create(name="The Book of Ed & Fred")
11        self.assertTrue(created)
12        # The publisher should have one book.
13        self.assertEqual(p.books.count(), 1)
14
15        # Try get_or_create again, this time nothing should be created.
16        book, created = p.books.get_or_create(name="The Book of Ed & Fred")
17        self.assertFalse(created)
18        # And the publisher should still have one book.
19        self.assertEqual(p.books.count(), 1)
20
21        # Add an author to the book.
22        ed, created = book.authors.get_or_create(name="Ed")
23        self.assertTrue(created)
24        # The book should have one author.
25        self.assertEqual(book.authors.count(), 1)
26
27        # Try get_or_create again, this time nothing should be created.
28        ed, created = book.authors.get_or_create(name="Ed")
29        self.assertFalse(created)
30        # And the book should still have one author.
31        self.assertEqual(book.authors.count(), 1)
32
33        # Add a second author to the book.
34        fred, created = book.authors.get_or_create(name="Fred")
35        self.assertTrue(created)
36
37        # The book should have two authors now.
38        self.assertEqual(book.authors.count(), 2)
39
40        # Create an Author not tied to any books.
41        Author.objects.create(name="Ted")
42
43        # There should be three Authors in total. The book object should have two.
44        self.assertEqual(Author.objects.count(), 3)
45        self.assertEqual(book.authors.count(), 2)
46
47        # Try creating a book through an author.
48        _, created = ed.books.get_or_create(name="Ed's Recipes", publisher=p)
49        self.assertTrue(created)
50
51        # Now Ed has two Books, Fred just one.
52        self.assertEqual(ed.books.count(), 2)
53        self.assertEqual(fred.books.count(), 1)
54
55        # Use the publisher's primary key value instead of a model instance.
56        _, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id)
57        self.assertTrue(created)
58
59        # Try get_or_create again, this time nothing should be created.
60        _, created = ed.books.get_or_create(name='The Great Book of Ed', publisher_id=p.id)
61        self.assertFalse(created)
62
63        # The publisher should have three books.
64        self.assertEqual(p.books.count(), 3)