Contact: fumanchu@aminus.org

Log in as guest/dejavu to create tickets

I think I've seen this ORM somewhere before...

root/branches/crazycache/dejavu/test/test_dejavu.py

Revision 552 (checked in by fumanchu, 4 years ago)

Buglets.

  • Property svn:eol-style set to native
Line 
1 import datetime
2 import unittest
3 import warnings
4
5 import dejavu
6 from dejavu import errors, storage
7 from dejavu.test.zoo_fixture import *
8
9
10 store = storage.resolve("ram")
11
12 for cls in (Animal, Lecture, Vet, Visit, Zoo, Exhibit):
13     store.register(cls)
14     store.create_storage(cls)
15
16
17 class UnitTests(unittest.TestCase):
18    
19     def setUp(self):
20         # CleanUP The Database!
21         box = store.new_sandbox()
22         for animal in box.recall(Animal):
23             animal.forget()
24         for zoo_thing in box.recall(Zoo):
25             zoo_thing.forget()
26    
27     def test_Properties(self):
28         # Instance creation and population
29         f = datetime.date(1916, 10, 2)
30         z = Zoo(Name='San Diego Zoo', Founded=f)
31         self.assertEqual(z.dirty(), True)
32         self.assertEqual(Zoo.ID.type, int)
33         self.assertEqual(z.ID, None)
34         self.assertEqual(z.Name, 'San Diego Zoo')
35         self.assertEqual(type(z.Name), unicode)
36         self.assertEqual(z.Founded, f)
37         self.assertEqual(z.__class__.ID.index, True)
38        
39         a = Animal(Species='Giraffe')
40         self.assertEqual(a.dirty(), True)
41         self.assertEqual(a.ID, None)
42         self.assertEqual(a.Species, 'Giraffe')
43         # 4 should be supplied by default
44         self.assertEqual(a.Legs, 4)
45         self.assertEqual(a.__class__.ZooID.index, True)
46        
47         # Sandboxing
48         s = store.new_sandbox()
49         s.memorize(z)
50         self.assertEqual(z.ID, 1)
51         s.memorize(a)
52         self.assertEqual(a.ID, 1)
53         z.add(a)
54         self.assertEqual(a.ZooID, 1)
55        
56         # Triggers
57         z.cleanse()
58         self.assertEqual(z.dirty(), False)
59         a.LastEscape = d = datetime.datetime(2004, 10, 20)
60         self.assertEqual(a.LastEscape, d)
61         self.assertEqual(z.LastEscape, d)
62         self.assertEqual(z.dirty(), True)
63    
64     def test_associations(self):
65         # Test for ticket #35.
66         box = store.new_sandbox()
67         box.memorize(Animal(Species='Liger'))
68         box.memorize(Zoo(Name='Wallingford'))
69         box.flush_all()
70         box = store.new_sandbox()
71         liger = box.unit(Animal, Species='Liger')
72         wall = box.unit(Zoo, Name='Wallingford')
73         liger.ZooID = wall.ID
74         self.assertEqual(len([a for a in wall.Animal()]), 1)
75         box.flush_all()
76    
77     def test_xrecall(self):
78         # Make sure multiple, simultaneous xrecalls recall all units.
79        
80         # Create some animals in a sandbox
81         box = store.new_sandbox()
82         box.memorize(Animal(Species='Wombat'))
83         box.memorize(Animal(Species='Lizard'))
84        
85         animals = []
86         animals2 = []
87        
88         # Start a new sandbox with no cache
89         box = store.new_sandbox()
90        
91         # get animals alternating from two different xrecalls
92         animals_is_stopped = False
93         animals2_is_stopped = False
94         animals_iter = box.xrecall(Animal)
95         animals2_iter = box.xrecall(Animal)
96         while not (animals_is_stopped and animals2_is_stopped):
97             try:
98                 animals.append(animals_iter.next())
99             except StopIteration:
100                 animals_is_stopped = True
101            
102             try:
103                 animals2.append(animals2_iter.next())
104             except StopIteration:
105                 animals2_is_stopped = True
106        
107         for animal in animals:
108             self.failUnless(
109                 animal in animals2,
110                 "An instance in the first xrecall wasn't in the second" )
111        
112         for animal in animals2:
113             self.failUnless(
114                 animal in animals,
115                 "An instance was in the second xrecall but not the first" )
116    
117     def test_sandbox_cache(self):
118         # Make sure the _sandbox_ cache is being used, not the ObjectCache's.
119        
120         # Create an animal in a sandbox, but retain a reference to it
121         box = store.new_sandbox()
122         bat = Animal(Species='Bat')
123         box.memorize(bat)
124        
125         # Modify the unit which is in the sandbox cache.
126         bat.Legs = 2
127        
128         # Retrieve the Unit from the same sandbox again.
129         self.assert_(box.unit(Animal) is bat)
130        
131         # Retrieve the Unit from a new sandbox.
132         # Units should be different, and their
133         # UnitProperties should be different.
134         bat3 = store.new_sandbox().unit(Animal)
135         self.assert_(bat3 is not bat)
136         self.assertEqual(bat3.Legs, 4)
137    
138     def test_UnitJoin(self):
139         box = store.new_sandbox()
140         tree = Animal & Zoo
141         self.assertEqual(str(tree), "(Animal & Zoo)")
142         tree = Animal << Zoo
143         self.assertEqual(str(tree), "(Animal << Zoo)")
144         tree = Animal >> Zoo
145         self.assertEqual(str(tree), "(Animal >> Zoo)")
146        
147         trees = []
148         def make_tree():
149             trees.append( (Animal & Zoo) >> Exhibit )
150        
151         warnings.filterwarnings("error", category=errors.StorageWarning)
152         try:
153             self.assertRaises(errors.StorageWarning, make_tree)
154         finally:
155             warnings.filters.pop(0)
156        
157         # Since we raised the warning, our first make_tree failed.
158         warnings.filterwarnings("ignore", category=errors.StorageWarning)
159         try:
160             make_tree()
161         finally:
162             warnings.filters.pop(0)
163        
164         self.assertEqual(str(trees[0]), "((Animal & Zoo) >> Exhibit)")
165         tree = trees[0] & (Visit << Vet) & Exhibit
166         self.assertEqual(str(tree), "((((Animal & Zoo) >> Exhibit) & "
167                                     "(Visit << Vet)) & Exhibit)")
168         self.assertEqual(list(tree), [Animal, Zoo, Exhibit, Visit, Vet, Exhibit])
169    
170     def test_json(self):
171         try:
172             from dejavu.json import Converter, Encoder, Decoder, unit_to_dict, dict_to_unit
173         except ImportError:
174             print "JSON funtionality requires the simplejson package."
175             return
176        
177         json = Converter()
178         box = store.new_sandbox()
179        
180         dt = datetime.datetime(2006, 9, 11, 21, 17, 34)
181         dt_as_json = json.dumps(dt)
182         dt_from_json = json.loads(dt_as_json)
183         self.assert_(dt is not dt_from_json)
184         self.assertEqual(dt, dt_from_json)
185        
186         f = datetime.date(1916, 10, 2)
187         z = Zoo(Name='San Diego Zoo', Founded=f)
188        
189         box.memorize(z)
190         box.flush_all()
191        
192         zoo = box.unit(Zoo, Name="San Diego Zoo")
193         zoo_json = json.dumps(unit_to_dict(zoo))
194        
195         self.assert_("1916-10-02" in zoo_json)
196         self.assert_("__dejavu.class__" in zoo_json)
197        
198         zoo_json = zoo_json.replace("San Diego Zoo", "The San Diego Zoo")
199         zoo2 = dict_to_unit(json.loads(zoo_json))
200        
201         self.assertEqual(zoo2.Name, "The San Diego Zoo")
202         for name in zoo.properties:
203             setattr(zoo, name, getattr(zoo2, name))
204         box.flush_all()
205        
206         zoo = box.unit(Zoo, Name="San Diego Zoo")
207         self.assertEqual(zoo, None)
208        
209         zoo = box.unit(Zoo, Name="The San Diego Zoo")
210         self.assertEqual(zoo.Founded, datetime.date(1916, 10, 2))
211        
212         # Test subclasses that support dates in MM/DD/YYYY format
213         class TestEncoder(Encoder):
214             DATE_FMT = "%m/%d/%Y"
215             TIME_FMT = "%H:%M:%S"
216             DATETIME_FMT = "%s %s" % (DATE_FMT, TIME_FMT)
217        
218         class TestDecoder(Decoder):
219             DATE_FMT = "%m/%d/%Y"
220             TIME_FMT = "%H:%M:%S"
221             DATETIME_FMT = "%s %s" % (DATE_FMT, TIME_FMT)
222        
223         class TestConverter(Converter):
224             encoder = TestEncoder
225             decoder = TestDecoder
226
227         json = TestConverter(store)
228         zoo_json = json.dumps(zoo)
229         self.assert_("10/02/1916" in zoo_json)
230         zoo3 = json.loads(zoo_json)
231         self.assertEqual(zoo3.Founded, datetime.date(1916, 10, 2))
232        
233         zoo = Zoo()
234         zoo_json = json.dumps(zoo)
235         zoo_json = zoo_json.replace('"Name": null',
236                                     '"Name": "Carnival Freak Show"')
237         today = datetime.date.today()
238         f = today.strftime("%m/%d/%Y")
239         zoo_json = zoo_json.replace('"Founded": {"__date__": true, "value": null}',
240                                     '"Founded": {"__date__": true, "value": "%s"}' % f)
241         zoo = json.loads(zoo_json)
242         box.memorize(zoo)
243         box.flush_all()
244         zoo = box.unit(Zoo, Name="Carnival Freak Show")
245         self.assert_(zoo)
246         self.assertEqual(zoo.Founded, today)
247
248         try:
249             import decimal
250             exhibit = Exhibit(Acreage="3.4")
251             exhibit_json = json.dumps(exhibit)
252             self.assert_('"value": "3.4"' in exhibit_json)
253             self.assert_('"__decimal__": true' in exhibit_json)
254             exhibit_copy = json.loads(exhibit_json)
255             self.assertEqual(exhibit_copy.Acreage, decimal.Decimal("3.4"))
256             exhibit.Acreage = None
257             exhibit_json = json.dumps(exhibit)
258             self.assert_('"Acreage": {"__decimal__": true, "value": null}' in exhibit_json)
259             ej = exhibit_json.replace('"Acreage": {"__decimal__": true, "value": null}',
260                                       '"Acreage": {"__decimal__": true, "value": "1.1"}')
261             exhibit_copy = json.loads(ej)
262             self.assertEqual(exhibit_copy.Acreage, decimal.Decimal("1.1"))
263            
264         except ImportError:
265             print "Skipping decimal test."
266        
267 if __name__ == "__main__":
268     unittest.main(__name__)
269
Note: See TracBrowser for help on using the browser.