Ticket #2227: tests.py

File tests.py, 2.0 KB (added by weaver@…, 16 years ago)
Line 
1import unittest
2from django.db import transaction, connection, models
3
4class Item(models.Model):
5 content = models.TextField()
6
7 def __unicode__(self):
8 return self.content
9
10class ItemTests(object):
11 def setUp(self):
12 Item.objects.create(id=1, content="a")
13 Item.objects.create(id=2, content="b")
14
15 def tearDown(self):
16 Item.objects.all().delete()
17
18 def items_are(self, where, *values):
19 ids = [id for (id, value) in values]
20 expect = [value for (id, value) in values]
21 self.assertEqual([Item.objects.get(id=id).content for id in ids], list(expect))
22
23class NestedOnSuccess(ItemTests, unittest.TestCase):
24
25 def testSuccess(self):
26 """
27 This test asserts that an explicit commit done for an inner
28 transaction should not actually be committed until the outer
29 transaction is finished.
30 """
31 @transaction.commit_on_success
32 def outer():
33 item = Item.objects.get(id=1)
34 inner()
35 transaction.rollback()
36 item.content = "changed a"
37 item.save()
38 self.items_are('outer end', (1, "changed a"), (2, "b"))
39
40 @transaction.commit_on_success
41 def inner():
42 item = Item.objects.get(id=2)
43 item.content = "changed b"
44 item.save()
45
46 self.items_are('initially', (1, "a"), (2, "b"))
47 outer()
48 self.items_are('finally', (1, "changed a"), (2, "b"))
49
50class NestedAutocommit(ItemTests, unittest.TestCase):
51
52 def testFail(self):
53 """
54 This test asserts that an inner `autocommit' transaction
55 should not commit itself until the outer transaction is
56 finished. This implies that transaction.managed(False) should
57 not override transaction.managed(True).
58 """
59 @transaction.commit_on_success
60 def outer():
61 item = Item.objects.get(id=1)
62 item.content = inner()
63 item.save()
64 raise RuntimeError
65
66 @transaction.autocommit
67 def inner():
68 item = Item.objects.get(id=2)
69 item.content = "changed b"
70 item.save()
71 return "changed a"
72
73 self.items_are('initially', (1, "a"), (2, "b"))
74 try:
75 outer()
76 except RuntimeError:
77 pass
78 self.items_are('finally', (1, "a"), (2, "b"))
Back to Top