PageRenderTime 28ms CodeModel.GetById 22ms app.highlight 3ms RepoModel.GetById 2ms app.codeStats 0ms

/tests/modeltests/get_or_create/tests.py

https://code.google.com/p/mango-py/
Python | 52 lines | 38 code | 9 blank | 5 comment | 0 complexity | eed8338c518fedf48be594c7255641ba MD5 | raw file
 1from datetime import date
 2
 3from django.db import IntegrityError
 4from django.test import TestCase
 5
 6from models import Person, ManualPrimaryKeyTest
 7
 8
 9class GetOrCreateTests(TestCase):
10    def test_get_or_create(self):
11        p = Person.objects.create(
12            first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)
13        )
14
15        p, created = Person.objects.get_or_create(
16            first_name="John", last_name="Lennon", defaults={
17                "birthday": date(1940, 10, 9)
18            }
19        )
20        self.assertFalse(created)
21        self.assertEqual(Person.objects.count(), 1)
22
23        p, created = Person.objects.get_or_create(
24            first_name='George', last_name='Harrison', defaults={
25                'birthday': date(1943, 2, 25)
26            }
27        )
28        self.assertTrue(created)
29        self.assertEqual(Person.objects.count(), 2)
30
31        # If we execute the exact same statement, it won't create a Person.
32        p, created = Person.objects.get_or_create(
33            first_name='George', last_name='Harrison', defaults={
34                'birthday': date(1943, 2, 25)
35            }
36        )
37        self.assertFalse(created)
38        self.assertEqual(Person.objects.count(), 2)
39
40        # If you don't specify a value or default value for all required
41        # fields, you will get an error.
42        self.assertRaises(IntegrityError,
43            Person.objects.get_or_create, first_name="Tom", last_name="Smith"
44        )
45
46        # If you specify an existing primary key, but different other fields,
47        # then you will get an error and data will not be updated.
48        m = ManualPrimaryKeyTest.objects.create(id=1, data="Original")
49        self.assertRaises(IntegrityError,
50            ManualPrimaryKeyTest.objects.get_or_create, id=1, data="Different"
51        )
52        self.assertEqual(ManualPrimaryKeyTest.objects.get(id=1).data, "Original")