9aa3943232585b8b09bf5cf5fbe070a86968da61
[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 from pokedex.db.tables import 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.table_classes:
28 assert getattr(tables, table.__name__) is table
29
30 def test_i18n_table_creation():
31 """Creates and manipulates a magical i18n table, completely independent of
32 the existing schema and data. Makes sure that the expected behavior of the
33 various proxies and columns works.
34 """
35 Base = declarative_base()
36 engine = create_engine("sqlite:///:memory:", echo=True)
37
38 Base.metadata.bind = engine
39
40 # Need this for the foreign keys to work!
41 class Language(Base):
42 __tablename__ = 'languages'
43 id = Column(Integer, primary_key=True, nullable=False)
44 identifier = Column(String(2), nullable=False, unique=True)
45
46 class Foo(Base):
47 __tablename__ = 'foos'
48 __singlename__ = 'foo'
49 id = Column(Integer, primary_key=True, nullable=False)
50
51 FooText = create_translation_table('foo_text', Foo,
52 _language_class=Language,
53 name = Column(String(100)),
54 )
55
56 # TODO move this to the real code
57 class DurpSession(Session):
58 def execute(self, clause, params=None, *args, **kwargs):
59 if not params:
60 params = {}
61 params.setdefault('_default_language', 'en')
62 return super(DurpSession, self).execute(clause, params, *args, **kwargs)
63
64 # OK, create all the tables and gimme a session
65 Base.metadata.create_all()
66 sess = sessionmaker(engine, class_=DurpSession)()
67
68 # Create some languages and foos to bind together
69 lang_en = Language(identifier='en')
70 sess.add(lang_en)
71 lang_jp = Language(identifier='jp')
72 sess.add(lang_jp)
73 lang_ru = Language(identifier='ru')
74 sess.add(lang_ru)
75
76 foo = Foo()
77 sess.add(foo)
78
79 # Commit so the above get primary keys filled in
80 sess.commit()
81
82 # Give our foo some names, as directly as possible
83 foo_text = FooText()
84 foo_text.object_id = foo.id
85 foo_text.language_id = lang_en.id
86 foo_text.name = 'english'
87 sess.add(foo_text)
88
89 foo_text = FooText()
90 foo_text.object_id = foo.id
91 foo_text.language_id = lang_jp.id
92 foo_text.name = 'nihongo'
93 sess.add(foo_text)
94
95 # Commit! This will expire all of the above.
96 sess.commit()
97
98 ### Test 1: re-fetch foo and check its attributes
99 foo = sess.query(Foo).params(_default_language='en').one()
100
101 # Dictionary of language identifiers => names
102 assert foo.name_map[lang_en] == 'english'
103 assert foo.name_map[lang_jp] == 'nihongo'
104
105 # Default language, currently English
106 assert foo.name == 'english'
107
108 sess.expire_all()
109
110 ### Test 2: querying by default language name should work
111 foo = sess.query(Foo).filter_by(name='english').one()
112
113 assert foo.name == 'english'
114
115 sess.expire_all()
116
117 ### Test 3: joinedload on the default name should appear to work
118 # THIS SHOULD WORK SOMEDAY
119 # .options(joinedload(Foo.name)) \
120 foo = sess.query(Foo) \
121 .options(joinedload(Foo.foo_text_local)) \
122 .one()
123
124 assert foo.name == 'english'
125
126 sess.expire_all()
127
128 ### Test 4: joinedload on all the names should appear to work
129 # THIS SHOULD ALSO WORK SOMEDAY
130 # .options(joinedload(Foo.name_map)) \
131 foo = sess.query(Foo) \
132 .options(joinedload(Foo.foo_text)) \
133 .one()
134
135 assert foo.name_map[lang_en] == 'english'
136 assert foo.name_map[lang_jp] == 'nihongo'
137
138 sess.expire_all()
139
140 ### Test 5: Mutating the dict collection should work
141 foo = sess.query(Foo).one()
142
143 foo.name_map[lang_en] = 'different english'
144 foo.name_map[lang_ru] = 'new russian'
145
146 sess.commit()
147
148 assert foo.name_map[lang_en] == 'different english'
149 assert foo.name_map[lang_ru] == 'new russian'
150
151 def test_texts():
152 """Check DB schema for integrity of text columns & translations.
153
154 Mostly protects against copy/paste oversights and rebase hiccups.
155 If there's a reason to relax the tests, do it
156 """
157 for table in sorted(tables.table_classes, key=lambda t: t.__name__):
158 if issubclass(table, tables.LanguageSpecific):
159 good_formats = 'markdown plaintext gametext'.split()
160 assert_text = '%s is language-specific'
161 else:
162 good_formats = 'identifier latex'.split()
163 assert_text = '%s is not language-specific'
164 mapper = class_mapper(table)
165 for column in sorted(mapper.c, key=lambda c: c.name):
166 format = column.info.get('format', None)
167 if format is not None:
168 if format not in good_formats:
169 raise AssertionError(assert_text % column)
170 is_markdown = isinstance(column.type, markdown.MarkdownColumn)
171 if is_markdown != (format == 'markdown'):
172 raise AssertionError('%s: markdown format/column type mismatch' % column)
173 if (format != 'identifier') and (column.name == 'identifier'):
174 raise AssertionError('%s: identifier column name/type mismatch' % column)
175 if column.info.get('official', None) and format not in 'gametext plaintext':
176 raise AssertionError('%s: official text with bad format' % column)
177 else:
178 if isinstance(column.type, (markdown.MarkdownColumn, tables.Unicode)):
179 raise AssertionError('%s: text column without format' % column)
180 if column.name == 'name' and format != 'plaintext':
181 raise AssertionError('%s: non-plaintext name' % column)
182 # No mention of English in the description
183 assert 'English' not in column.info['description'], column
184
185 def test_identifiers_with_names():
186 """Test that named tables have identifiers, and non-named tables don't
187
188 ...have either names or identifiers.
189 """
190 for table in sorted(tables.table_classes, key=lambda t: t.__name__):
191 if issubclass(table, tables.Named):
192 assert issubclass(table, tables.OfficiallyNamed) or issubclass(table, tables.UnofficiallyNamed), table
193 assert hasattr(table, 'identifier'), table
194 else:
195 assert not hasattr(table, 'identifier'), table
196 if not issubclass(table, tables.LanguageSpecific):
197 assert not hasattr(table, 'name'), table