Ticket #55: test_assoc.py

File test_assoc.py, 1.6 kB (added by guest, 6 years ago)

test case demonstrating mapped_collection missed association

Line 
1from elixir import *
2metadata.bind='sqlite:///'
3
4from sqlalchemy.orm.collections import attribute_mapped_collection
5
6class Item(Entity):
7        name = Field(String(128))
8        attributes = OneToMany('Attribute', collection_class=attribute_mapped_collection('name'))
9       
10        def __repr__(self):
11                return 'Item(%s)' % (self.name,)
12
13class Attribute(Entity):
14        item = ManyToOne('Item', primary_key=True)
15        name = Field(String(128), primary_key=True)
16
17        def __repr__(self):
18                return 'Attribute(%s, %s)' % (self.name, self.value)
19 
20setup_all(True)
21
22item1 = Item(name='item1')
23# uncomment this to fail at the first assertion
24#print item1.attributes
25attr1 = Attribute(name='attr1key', value='attr1value', item=item1)
26print item1.attributes
27assert not None in item1.attributes
28assert 'attr1key' in item1.attributes
29assert attr1 in session.new
30
31# this works fine, even after accessing item1.attributes
32attr2 = Attribute(name='attr2key', value='attr2value')
33# because we've explicitly deferred setting the .item until
34#  after the attribute is instantiated.
35attr2.item = item1
36print item1.attributes
37assert not None in item1.attributes
38assert 'attr2key' in item1.attributes
39assert attr2 in session.new
40
41# anytime after we've accessed item1.attributes, if we try to initialize
42# an attribute for that item, the attribute will not be correctly
43# associated and will be lost from the session.
44attr3 = Attribute(name='attr3key', value='attr3value', item=item1)
45print item1.attributes
46assert not None in item1.attributes
47assert 'attr3key' in item1.attributes
48assert attr3 in session.new