Added a test for the i18n dynamic table generation.
[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.ext.declarative import declarative_base
7
8 from pokedex.db import tables, markdown
9
10 def test_variable_names():
11 """We want pokedex.db.tables to export tables using the class name"""
12 for varname in dir(tables):
13 if not varname[0].isupper():
14 continue
15 table = getattr(tables, varname)
16 try:
17 if not issubclass(table, tables.TableBase) or table is tables.TableBase:
18 continue
19 except TypeError:
20 continue
21 classname = table.__name__
22 if classname and varname[0].isupper():
23 assert varname == classname, '%s refers to %s' % (varname, classname)
24 for table in tables.table_classes:
25 assert getattr(tables, table.__name__) is table
26
27 def test_i18n_table_creation():
28 """Creates and manipulates a magical i18n table, completely independent of
29 the existing schema and data. Makes sure that the expected behavior of the
30 various proxies and columns works.
31 """
32 Base = declarative_base()
33 engine = create_engine("sqlite:///:memory:")
34
35 Base.metadata.bind = engine
36
37 # Need this for the foreign keys to work!
38 class Language(Base):
39 __tablename__ = 'languages'
40 id = Column(Integer, primary_key=True, nullable=False)
41 identifier = Column(String(2), nullable=False, unique=True)
42
43 class Foo(Base):
44 __tablename__ = 'foos'
45 __singlename__ = 'foo'
46 id = Column(Integer, primary_key=True, nullable=False)
47
48 FooText = tables.makeTextTable(
49 foreign_table_class=Foo,
50 table_suffix_plural='blorp',
51 table_suffix_singular='klink',
52 columns=[
53 ('name', 'names', Column(String(100))),
54 ],
55 lazy='select',
56 Language=Language,
57 )
58
59 # OK, create all the tables and gimme a session
60 Base.metadata.create_all()
61 sess = sessionmaker(engine)()
62
63 # Create some languages and foos to bind together
64 lang_en = Language(identifier='en')
65 sess.add(lang_en)
66 lang_jp = Language(identifier='jp')
67 sess.add(lang_jp)
68
69 foo = Foo()
70 sess.add(foo)
71
72 # Commit so the above get primary keys filled in
73 sess.commit()
74
75 # Give our foo some names, as directly as possible
76 foo_text = FooText()
77 foo_text.object_id = foo.id
78 foo_text.language_id = lang_en.id
79 foo_text.name = 'english'
80 sess.add(foo_text)
81
82 foo_text = FooText()
83 foo_text.object_id = foo.id
84 foo_text.language_id = lang_jp.id
85 foo_text.name = 'nihongo'
86 sess.add(foo_text)
87
88 # Commit! This will expire all of the above.
89 sess.commit()
90
91 ### Test 1: re-fetch foo and check its attributes
92 foo = sess.query(Foo).one()
93
94 # Dictionary of language identifiers => names
95 assert foo.names['en'] == 'english'
96 assert foo.names['jp'] == 'nihongo'
97
98 # Default language, currently English
99 assert foo.name == 'english'
100
101 sess.expire_all()
102
103 ### Test 2: joinedload on the default name should appear to work
104 foo = sess.query(Foo) \
105 .options(joinedload(Foo.name)) \
106 .first
107
108 assert foo.name == 'english'
109
110 sess.expire_all()
111
112 ### Test 3: joinedload on all the names should appear to work
113 foo = sess.query(Foo) \
114 .options(joinedload(Foo.names)) \
115 .first
116
117 assert foo.names['en'] == 'english'
118 assert foo.names['jp'] == 'nihongo'
119
120 sess.expire_all()
121
122 ### Test 4: Mutating the dict collection should work
123 foo = sess.query(Foo).first
124
125 foo.names['en'] = 'different english'
126 del foo.names['jp']
127
128 sess.commit()
129
130 assert foo.names['en'] == 'different english'
131 assert 'jp' not in foo.names
132
133 def test_texts():
134 """Check DB schema for integrity of text columns & translations.
135
136 Mostly protects against copy/paste oversights and rebase hiccups.
137 If there's a reason to relax the tests, do it
138 """
139 for table in sorted(tables.table_classes, key=lambda t: t.__name__):
140 if issubclass(table, tables.LanguageSpecific):
141 good_formats = 'markdown plaintext gametext'.split()
142 assert_text = '%s is language-specific'
143 else:
144 good_formats = 'identifier latex'.split()
145 assert_text = '%s is not language-specific'
146 mapper = class_mapper(table)
147 for column in sorted(mapper.c, key=lambda c: c.name):
148 format = column.info.get('format', None)
149 if format is not None:
150 if format not in good_formats:
151 raise AssertionError(assert_text % column)
152 is_markdown = isinstance(column.type, markdown.MarkdownColumn)
153 if is_markdown != (format == 'markdown'):
154 raise AssertionError('%s: markdown format/column type mismatch' % column)
155 if (format != 'identifier') and (column.name == 'identifier'):
156 raise AssertionError('%s: identifier column name/type mismatch' % column)
157 if column.info.get('official', None) and format not in 'gametext plaintext':
158 raise AssertionError('%s: official text with bad format' % column)
159 else:
160 if isinstance(column.type, (markdown.MarkdownColumn, tables.Unicode)):
161 raise AssertionError('%s: text column without format' % column)
162 if column.name == 'name' and format != 'plaintext':
163 raise AssertionError('%s: non-plaintext name' % column)
164 # No mention of English in the description
165 assert 'English' not in column.info['description'], column
166
167 def test_identifiers_with_names():
168 """Test that named tables have identifiers, and non-named tables don't
169
170 ...have either names or identifiers.
171 """
172 for table in sorted(tables.table_classes, key=lambda t: t.__name__):
173 if issubclass(table, tables.Named):
174 assert issubclass(table, tables.OfficiallyNamed) or issubclass(table, tables.UnofficiallyNamed), table
175 assert hasattr(table, 'identifier'), table
176 else:
177 assert not hasattr(table, 'identifier'), table
178 if not issubclass(table, tables.LanguageSpecific):
179 assert not hasattr(table, 'name'), table