Split up MoveEffectProperty; don't detect dict proxies.
[zzz-pokedex.git] / pokedex / tests / test_schema.py
1 # encoding: utf8
2 from nose.tools import *
3 import unittest
4 from sqlalchemy import Column, Integer, String, create_engine
5 from sqlalchemy.orm import class_mapper, joinedload, sessionmaker
6 from sqlalchemy.orm.session import Session
7 from sqlalchemy.ext.declarative import declarative_base
8
9 from pokedex.db import tables, markdown
10 from pokedex.db.multilang import create_translation_table
11
12 def test_variable_names():
13 """We want pokedex.db.tables to export tables using the class name"""
14 for varname in dir(tables):
15 if not varname[0].isupper():
16 continue
17 table = getattr(tables, varname)
18 try:
19 if not issubclass(table, tables.TableBase) or table is tables.TableBase:
20 continue
21 except TypeError:
22 continue
23 classname = table.__name__
24 if classname and varname[0].isupper():
25 assert varname == classname, '%s refers to %s' % (varname, classname)
26 for table in tables.mapped_classes:
27 assert getattr(tables, table.__name__) is table
28
29 def test_class_order():
30 """The declarative classes should be defined in alphabetical order.
31 Except for Language which should be first.
32 """
33 class_names = [table.__name__ for table in tables.mapped_classes]
34 def key(name):
35 return name != 'Language', name
36 print [(a,b) for (a,b) in zip(class_names, sorted(class_names, key=key)) if a!=b]
37 assert class_names == sorted(class_names, key=key)
38
39 def test_i18n_table_creation():
40 """Creates and manipulates a magical i18n table, completely independent of
41 the existing schema and data. Makes sure that the expected behavior of the
42 various proxies and columns works.
43 """
44 Base = declarative_base()
45 engine = create_engine("sqlite:///:memory:", echo=True)
46
47 Base.metadata.bind = engine
48
49 # Need this for the foreign keys to work!
50 class Language(Base):
51 __tablename__ = 'languages'
52 id = Column(Integer, primary_key=True, nullable=False)
53 identifier = Column(String(2), nullable=False, unique=True)
54
55 class Foo(Base):
56 __tablename__ = 'foos'
57 __singlename__ = 'foo'
58 id = Column(Integer, primary_key=True, nullable=False)
59 translation_classes = []
60
61 FooText = create_translation_table('foo_text', Foo, 'texts',
62 language_class=Language,
63 name = Column(String(100)),
64 )
65
66 class FauxSession(Session):
67 def execute(self, clause, params=None, *args, **kwargs):
68 if not params:
69 params = {}
70 params.setdefault('_default_language', 'en')
71 return super(FauxSession, self).execute(clause, params, *args, **kwargs)
72
73 # OK, create all the tables and gimme a session
74 Base.metadata.create_all()
75 sess = sessionmaker(engine, class_=FauxSession)()
76
77 # Create some languages and foos to bind together
78 lang_en = Language(identifier='en')
79 sess.add(lang_en)
80 lang_jp = Language(identifier='jp')
81 sess.add(lang_jp)
82 lang_ru = Language(identifier='ru')
83 sess.add(lang_ru)
84
85 foo = Foo()
86 sess.add(foo)
87
88 # Commit so the above get primary keys filled in
89 sess.commit()
90
91 # Give our foo some names, as directly as possible
92 foo_text = FooText()
93 foo_text.foreign_id = foo.id
94 foo_text.local_language_id = lang_en.id
95 foo_text.name = 'english'
96 sess.add(foo_text)
97
98 foo_text = FooText()
99 foo_text.foo_id = foo.id
100 foo_text.local_language_id = lang_jp.id
101 foo_text.name = 'nihongo'
102 sess.add(foo_text)
103
104 # Commit! This will expire all of the above.
105 sess.commit()
106
107 ### Test 1: re-fetch foo and check its attributes
108 foo = sess.query(Foo).params(_default_language='en').one()
109
110 # Dictionary of language identifiers => names
111 assert foo.name_map[lang_en] == 'english'
112 assert foo.name_map[lang_jp] == 'nihongo'
113
114 # Default language, currently English
115 assert foo.name == 'english'
116
117 sess.expire_all()
118
119 ### Test 2: querying by default language name should work
120 foo = sess.query(Foo).filter_by(name='english').one()
121
122 assert foo.name == 'english'
123
124 sess.expire_all()
125
126 ### Test 3: joinedload on the default name should appear to work
127 # THIS SHOULD WORK SOMEDAY
128 # .options(joinedload(Foo.name)) \
129 foo = sess.query(Foo) \
130 .options(joinedload(Foo.texts_local)) \
131 .one()
132
133 assert foo.name == 'english'
134
135 sess.expire_all()
136
137 ### Test 4: joinedload on all the names should appear to work
138 # THIS SHOULD ALSO WORK SOMEDAY
139 # .options(joinedload(Foo.name_map)) \
140 foo = sess.query(Foo) \
141 .options(joinedload(Foo.texts)) \
142 .one()
143
144 assert foo.name_map[lang_en] == 'english'
145 assert foo.name_map[lang_jp] == 'nihongo'
146
147 sess.expire_all()
148
149 ### Test 5: Mutating the dict collection should work
150 foo = sess.query(Foo).one()
151
152 foo.name_map[lang_en] = 'different english'
153 foo.name_map[lang_ru] = 'new russian'
154
155 sess.commit()
156
157 assert foo.name_map[lang_en] == 'different english'
158 assert foo.name_map[lang_ru] == 'new russian'
159
160 def test_texts():
161 """Check DB schema for integrity of text columns & translations.
162
163 Mostly protects against copy/paste oversights and rebase hiccups.
164 If there's a reason to relax the tests, do it
165 """
166 classes = []
167 for cls in tables.mapped_classes:
168 classes.append(cls)
169 classes += cls.translation_classes
170 for cls in classes:
171 if hasattr(cls, 'local_language') or hasattr(cls, 'language'):
172 good_formats = 'markdown plaintext gametext'.split()
173 assert_text = '%s is language-specific'
174 else:
175 good_formats = 'identifier latex'.split()
176 assert_text = '%s is not language-specific'
177 columns = sorted(cls.__table__.c, key=lambda c: c.name)
178 for column in columns:
179 format = column.info.get('format', None)
180 if format is not None:
181 if format not in good_formats:
182 raise AssertionError(assert_text % column)
183 is_markdown = isinstance(column.type, markdown.MarkdownColumn)
184 if is_markdown != (format == 'markdown'):
185 raise AssertionError('%s: markdown format/column type mismatch' % column)
186 if (format != 'identifier') and (column.name == 'identifier'):
187 raise AssertionError('%s: identifier column name/type mismatch' % column)
188 if column.info.get('official', None) and format not in 'gametext plaintext':
189 raise AssertionError('%s: official text with bad format' % column)
190 else:
191 if isinstance(column.type, (markdown.MarkdownColumn, tables.Unicode)):
192 raise AssertionError('%s: text column without format' % column)
193 if column.name == 'name' and format != 'plaintext':
194 raise AssertionError('%s: non-plaintext name' % column)
195 # No mention of English in the description
196 assert 'English' not in column.info['description'], column
197
198 def test_identifiers_with_names():
199 """Test that named tables have identifiers, and non-named tables don't
200
201 ...have either names or identifiers.
202 """
203 for table in sorted(tables.mapped_classes, key=lambda t: t.__name__):
204 if hasattr(table, 'name'):
205 assert hasattr(table, 'identifier'), table
206 else:
207 assert not hasattr(table, 'identifier'), table