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