0518ed8a3c0ed96e7e1e04e48b33a836df421d3f
2 from nose
.tools
import *
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
9 from pokedex
.db
import tables
, markdown
10 from pokedex
.db
.multilang
import MultilangScopedSession
, MultilangSession
, \
11 create_translation_table
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():
18 table
= getattr(tables
, varname
)
20 if not issubclass(table
, tables
.TableBase
) or table
is tables
.TableBase
:
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
.mapped_classes
:
28 assert getattr(tables
, table
.__name__
) is table
30 def test_class_order():
31 """The declarative classes should be defined in alphabetical order.
32 Except for Language which should be first.
34 class_names
= [table
.__name__
for table
in tables
.mapped_classes
]
36 return name
!= 'Language', name
37 print [(a
,b
) for (a
,b
) in zip(class_names
, sorted(class_names
, key
=key
)) if a
!=b
]
38 assert class_names
== sorted(class_names
, key
=key
)
40 def test_i18n_table_creation():
41 """Creates and manipulates a magical i18n table, completely independent of
42 the existing schema and data. Makes sure that the expected behavior of the
43 various proxies and columns works.
45 Base
= declarative_base()
46 engine
= create_engine("sqlite:///:memory:", echo
=True)
48 Base
.metadata
.bind
= engine
50 # Need this for the foreign keys to work!
52 __tablename__
= 'languages'
53 id = Column(Integer
, primary_key
=True, nullable
=False)
54 identifier
= Column(String(2), nullable
=False, unique
=True)
57 __tablename__
= 'foos'
58 __singlename__
= 'foo'
59 id = Column(Integer
, primary_key
=True, nullable
=False)
60 translation_classes
= []
62 FooText
= create_translation_table('foo_text', Foo
, 'texts',
63 language_class
=Language
,
64 name
= Column(String(100)),
67 # OK, create all the tables and gimme a session
68 Base
.metadata
.create_all()
69 sm
= sessionmaker(class_
=MultilangSession
)
70 sess
= MultilangScopedSession(sm
)
72 # Create some languages and foos to bind together
73 lang_en
= Language(identifier
='en')
75 lang_jp
= Language(identifier
='jp')
77 lang_ru
= Language(identifier
='ru')
83 # Commit so the above get primary keys filled in, then give the
84 # session the language id
86 # Note that this won't apply to sessions created in other threads, but that
87 # ought not be a problem!
88 sess
.default_language_id
= lang_en
.id
90 # Give our foo some names, as directly as possible
92 foo_text
.foreign_id
= foo
.id
93 foo_text
.local_language_id
= lang_en
.id
94 foo_text
.name
= 'english'
98 foo_text
.foo_id
= foo
.id
99 foo_text
.local_language_id
= lang_jp
.id
100 foo_text
.name
= 'nihongo'
103 # Commit! This will expire all of the above.
106 ### Test 1: re-fetch foo and check its attributes
107 foo
= sess
.query(Foo
).params(_default_language
='en').one()
109 # Dictionary of language identifiers => names
110 assert foo
.name_map
[lang_en
] == 'english'
111 assert foo
.name_map
[lang_jp
] == 'nihongo'
113 # Default language, currently English
114 assert foo
.name
== 'english'
118 ### Test 2: querying by default language name should work
119 foo
= sess
.query(Foo
).filter_by(name
='english').one()
121 assert foo
.name
== 'english'
125 ### Test 3: joinedload on the default name should appear to work
126 # THIS SHOULD WORK SOMEDAY
127 # .options(joinedload(Foo.name)) \
128 foo
= sess
.query(Foo
) \
129 .options(joinedload(Foo
.texts_local
)) \
132 assert foo
.name
== 'english'
136 ### Test 4: joinedload on all the names should appear to work
137 # THIS SHOULD ALSO WORK SOMEDAY
138 # .options(joinedload(Foo.name_map)) \
139 foo
= sess
.query(Foo
) \
140 .options(joinedload(Foo
.texts
)) \
143 assert foo
.name_map
[lang_en
] == 'english'
144 assert foo
.name_map
[lang_jp
] == 'nihongo'
148 ### Test 5: Mutating the dict collection should work
149 foo
= sess
.query(Foo
).one()
151 foo
.name_map
[lang_en
] = 'different english'
152 foo
.name_map
[lang_ru
] = 'new russian'
156 assert foo
.name_map
[lang_en
] == 'different english'
157 assert foo
.name_map
[lang_ru
] == 'new russian'
160 """Check DB schema for integrity of text columns & translations.
162 Mostly protects against copy/paste oversights and rebase hiccups.
163 If there's a reason to relax the tests, do it
166 for cls
in tables
.mapped_classes
:
168 classes
+= cls
.translation_classes
170 if hasattr(cls
, 'local_language') or hasattr(cls
, 'language'):
171 good_formats
= 'markdown plaintext gametext'.split()
172 assert_text
= '%s is language-specific'
174 good_formats
= 'identifier latex'.split()
175 assert_text
= '%s is not language-specific'
176 columns
= sorted(cls
.__table__
.c
, key
=lambda c
: c
.name
)
178 for column
in columns
:
179 format
= column
.info
.get('format', None)
180 if format
is not None:
181 if format
not in good_formats
:
182 raise AssertionError(assert_text % column
)
183 is_markdown
= isinstance(column
.type, markdown
.MarkdownColumn
)
184 if is_markdown
!= (format
== 'markdown'):
185 raise AssertionError('%s: markdown format/column type mismatch' % column
)
186 if (format
!= 'identifier') and (column
.name
== 'identifier'):
187 raise AssertionError('%s: identifier column name/type mismatch' % column
)
188 if column
.info
.get('official', None) and format
not in 'gametext plaintext':
189 raise AssertionError('%s: official text with bad format' % column
)
190 text_columns
.append(column
)
192 if isinstance(column
.type, (markdown
.MarkdownColumn
, tables
.Unicode
)):
193 raise AssertionError('%s: text column without format' % column
)
194 if column
.name
== 'name' and format
!= 'plaintext':
195 raise AssertionError('%s: non-plaintext name' % column
)
196 # No mention of English in the description
197 assert 'English' not in column
.info
['description'], column
198 # If there's more than one text column in a translation table,
199 # they have to be nullable, to support missing translations
200 if hasattr(cls
, 'local_language') and len(text_columns
) > 1:
201 for column
in text_columns
:
202 assert column
.nullable
204 def test_identifiers_with_names():
205 """Test that named tables have identifiers, and non-named tables don't
207 ...have either names or identifiers.
209 for table
in sorted(tables
.mapped_classes
, key
=lambda t
: t
.__name__
):
210 if hasattr(table
, 'name'):
211 assert hasattr(table
, 'identifier'), table
213 assert not hasattr(table
, 'identifier'), table