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