804e3c8afc3d3fb77c961d18c6b9af6de16e0bda
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 create_translation_table
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():
17 table
= getattr(tables
, varname
)
19 if not issubclass(table
, tables
.TableBase
) or table
is tables
.TableBase
:
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
29 def test_class_order():
30 """The declarative classes should be defined in alphabetical order.
31 Except for Language which should be first.
33 class_names
= [table
.__name__
for table
in tables
.mapped_classes
]
35 return name
!= 'Language', name
36 print [(a
,b
) for (a
,b
) in zip(class_names
, sorted(class_names
, key
=key
)) if a
!=b
]
37 assert class_names
== sorted(class_names
, key
=key
)
39 def test_i18n_table_creation():
40 """Creates and manipulates a magical i18n table, completely independent of
41 the existing schema and data. Makes sure that the expected behavior of the
42 various proxies and columns works.
44 Base
= declarative_base()
45 engine
= create_engine("sqlite:///:memory:", echo
=True)
47 Base
.metadata
.bind
= engine
49 # Need this for the foreign keys to work!
51 __tablename__
= 'languages'
52 id = Column(Integer
, primary_key
=True, nullable
=False)
53 identifier
= Column(String(2), nullable
=False, unique
=True)
56 __tablename__
= 'foos'
57 __singlename__
= 'foo'
58 id = Column(Integer
, primary_key
=True, nullable
=False)
59 translation_classes
= []
61 FooText
= create_translation_table('foo_text', Foo
, 'texts',
62 language_class
=Language
,
63 name
= Column(String(100)),
66 class FauxSession(Session
):
67 def execute(self
, clause
, params
=None, *args
, **kwargs
):
70 params
.setdefault('_default_language', 'en')
71 return super(FauxSession
, self
).execute(clause
, params
, *args
, **kwargs
)
73 # OK, create all the tables and gimme a session
74 Base
.metadata
.create_all()
75 sess
= sessionmaker(engine
, class_
=FauxSession
)()
77 # Create some languages and foos to bind together
78 lang_en
= Language(identifier
='en')
80 lang_jp
= Language(identifier
='jp')
82 lang_ru
= Language(identifier
='ru')
88 # Commit so the above get primary keys filled in
91 # Give our foo some names, as directly as possible
93 foo_text
.foreign_id
= foo
.id
94 foo_text
.local_language_id
= lang_en
.id
95 foo_text
.name
= 'english'
99 foo_text
.foo_id
= foo
.id
100 foo_text
.local_language_id
= lang_jp
.id
101 foo_text
.name
= 'nihongo'
104 # Commit! This will expire all of the above.
107 ### Test 1: re-fetch foo and check its attributes
108 foo
= sess
.query(Foo
).params(_default_language
='en').one()
110 # Dictionary of language identifiers => names
111 assert foo
.name_map
[lang_en
] == 'english'
112 assert foo
.name_map
[lang_jp
] == 'nihongo'
114 # Default language, currently English
115 assert foo
.name
== 'english'
119 ### Test 2: querying by default language name should work
120 foo
= sess
.query(Foo
).filter_by(name
='english').one()
122 assert foo
.name
== 'english'
126 ### Test 3: joinedload on the default name should appear to work
127 # THIS SHOULD WORK SOMEDAY
128 # .options(joinedload(Foo.name)) \
129 foo
= sess
.query(Foo
) \
130 .options(joinedload(Foo
.texts_local
)) \
133 assert foo
.name
== 'english'
137 ### Test 4: joinedload on all the names should appear to work
138 # THIS SHOULD ALSO WORK SOMEDAY
139 # .options(joinedload(Foo.name_map)) \
140 foo
= sess
.query(Foo
) \
141 .options(joinedload(Foo
.texts
)) \
144 assert foo
.name_map
[lang_en
] == 'english'
145 assert foo
.name_map
[lang_jp
] == 'nihongo'
149 ### Test 5: Mutating the dict collection should work
150 foo
= sess
.query(Foo
).one()
152 foo
.name_map
[lang_en
] = 'different english'
153 foo
.name_map
[lang_ru
] = 'new russian'
157 assert foo
.name_map
[lang_en
] == 'different english'
158 assert foo
.name_map
[lang_ru
] == 'new russian'
161 """Check DB schema for integrity of text columns & translations.
163 Mostly protects against copy/paste oversights and rebase hiccups.
164 If there's a reason to relax the tests, do it
167 for cls
in tables
.mapped_classes
:
169 classes
+= cls
.translation_classes
171 if hasattr(cls
, 'local_language') or hasattr(cls
, 'language'):
172 good_formats
= 'markdown plaintext gametext'.split()
173 assert_text
= '%s is language-specific'
175 good_formats
= 'identifier latex'.split()
176 assert_text
= '%s is not language-specific'
177 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
)
191 if isinstance(column
.type, (markdown
.MarkdownColumn
, tables
.Unicode
)):
192 raise AssertionError('%s: text column without format' % column
)
193 if column
.name
== 'name' and format
!= 'plaintext':
194 raise AssertionError('%s: non-plaintext name' % column
)
195 # No mention of English in the description
196 assert 'English' not in column
.info
['description'], column
198 def test_identifiers_with_names():
199 """Test that named tables have identifiers, and non-named tables don't
201 ...have either names or identifiers.
203 for table
in sorted(tables
.mapped_classes
, key
=lambda t
: t
.__name__
):
204 if hasattr(table
, 'name'):
205 assert hasattr(table
, 'identifier'), table
207 assert not hasattr(table
, 'identifier'), table