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