New i18n schema thing impl, and fixed the new tests to match.
[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
11 def test_variable_names():
12 """We want pokedex.db.tables to export tables using the class name"""
13 for varname in dir(tables):
14 if not varname[0].isupper():
15 continue
16 table = getattr(tables, varname)
17 try:
18 if not issubclass(table, tables.TableBase) or table is tables.TableBase:
19 continue
20 except TypeError:
21 continue
22 classname = table.__name__
23 if classname and varname[0].isupper():
24 assert varname == classname, '%s refers to %s' % (varname, classname)
25 for table in tables.table_classes:
26 assert getattr(tables, table.__name__) is table
27
28 def test_i18n_table_creation():
29 """Creates and manipulates a magical i18n table, completely independent of
30 the existing schema and data. Makes sure that the expected behavior of the
31 various proxies and columns works.
32 """
33 Base = declarative_base()
34 engine = create_engine("sqlite:///:memory:", echo=True)
35
36 Base.metadata.bind = engine
37
38 # Need this for the foreign keys to work!
39 class Language(Base):
40 __tablename__ = 'languages'
41 id = Column(Integer, primary_key=True, nullable=False)
42 identifier = Column(String(2), nullable=False, unique=True)
43
44 class Foo(Base):
45 __tablename__ = 'foos'
46 __singlename__ = 'foo'
47 id = Column(Integer, primary_key=True, nullable=False)
48
49 FooText = tables.create_translation_table('foo_text', Foo,
50 _language_class=Language,
51 name = Column(String(100)),
52 )
53
54 # TODO move this to the real code
55 class DurpSession(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(DurpSession, 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_=DurpSession)()
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['en'] == 'english'
101 assert foo.name_map['jp'] == 'nihongo'
102
103 # Default language, currently English
104 assert foo.name == 'english'
105
106 sess.expire_all()
107
108 ### Test 2: joinedload on the default name should appear to work
109 # THIS SHOULD WORK SOMEDAY
110 # .options(joinedload(Foo.name)) \
111 foo = sess.query(Foo) \
112 .options(joinedload(Foo.foo_text_local)) \
113 .one()
114
115 assert foo.name == 'english'
116
117 sess.expire_all()
118
119 ### Test 3: joinedload on all the names should appear to work
120 # THIS SHOULD ALSO WORK SOMEDAY
121 # .options(joinedload(Foo.name_map)) \
122 foo = sess.query(Foo) \
123 .options(joinedload(Foo.foo_text)) \
124 .one()
125
126 assert foo.name_map['en'] == 'english'
127 assert foo.name_map['jp'] == 'nihongo'
128
129 sess.expire_all()
130
131 ### Test 4: Mutating the dict collection should work
132 foo = sess.query(Foo).one()
133
134 foo.name_map['en'] = 'different english'
135 foo.name_map['ru'] = 'new russian'
136
137 sess.commit()
138
139 assert foo.name_map['en'] == 'different english'
140 assert foo.name_map['ru'] == 'new russian'
141
142 def test_texts():
143 """Check DB schema for integrity of text columns & translations.
144
145 Mostly protects against copy/paste oversights and rebase hiccups.
146 If there's a reason to relax the tests, do it
147 """
148 for table in sorted(tables.table_classes, key=lambda t: t.__name__):
149 if issubclass(table, tables.LanguageSpecific):
150 good_formats = 'markdown plaintext gametext'.split()
151 assert_text = '%s is language-specific'
152 else:
153 good_formats = 'identifier latex'.split()
154 assert_text = '%s is not language-specific'
155 mapper = class_mapper(table)
156 for column in sorted(mapper.c, key=lambda c: c.name):
157 format = column.info.get('format', None)
158 if format is not None:
159 if format not in good_formats:
160 raise AssertionError(assert_text % column)
161 is_markdown = isinstance(column.type, markdown.MarkdownColumn)
162 if is_markdown != (format == 'markdown'):
163 raise AssertionError('%s: markdown format/column type mismatch' % column)
164 if (format != 'identifier') and (column.name == 'identifier'):
165 raise AssertionError('%s: identifier column name/type mismatch' % column)
166 if column.info.get('official', None) and format not in 'gametext plaintext':
167 raise AssertionError('%s: official text with bad format' % column)
168 else:
169 if isinstance(column.type, (markdown.MarkdownColumn, tables.Unicode)):
170 raise AssertionError('%s: text column without format' % column)
171 if column.name == 'name' and format != 'plaintext':
172 raise AssertionError('%s: non-plaintext name' % column)
173 # No mention of English in the description
174 assert 'English' not in column.info['description'], column
175
176 def test_identifiers_with_names():
177 """Test that named tables have identifiers, and non-named tables don't
178
179 ...have either names or identifiers.
180 """
181 for table in sorted(tables.table_classes, key=lambda t: t.__name__):
182 if issubclass(table, tables.Named):
183 assert issubclass(table, tables.OfficiallyNamed) or issubclass(table, tables.UnofficiallyNamed), table
184 assert hasattr(table, 'identifier'), table
185 else:
186 assert not hasattr(table, 'identifier'), table
187 if not issubclass(table, tables.LanguageSpecific):
188 assert not hasattr(table, 'name'), table