1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
|
"""TestCase and TestSuite artifacts and testing decorators."""
# monkeypatches unittest.TestLoader.suiteClass at import time
import itertools
import operator
import re
import sys
import types
import unittest
import warnings
from cStringIO import StringIO
import testlib.config as config
from testlib.compat import set, _function_named, reversed
# Delayed imports
MetaData = None
Session = None
clear_mappers = None
sa_exc = None
schema = None
sqltypes = None
util = None
_ops = { '<': operator.lt,
'>': operator.gt,
'==': operator.eq,
'!=': operator.ne,
'<=': operator.le,
'>=': operator.ge,
'in': operator.contains,
'between': lambda val, pair: val >= pair[0] and val <= pair[1],
}
# sugar ('testing.db'); set here by config() at runtime
db = None
# more sugar, installed by __init__
requires = None
def fails_if(callable_):
"""Mark a test as expected to fail if callable_ returns True.
If the callable returns false, the test is run and reported as normal.
However if the callable returns true, the test is expected to fail and the
unit test logic is inverted: if the test fails, a success is reported. If
the test succeeds, a failure is reported.
"""
docstring = getattr(callable_, '__doc__', None) or callable_.__name__
description = docstring.split('\n')[0]
def decorate(fn):
fn_name = fn.__name__
def maybe(*args, **kw):
if not callable_():
return fn(*args, **kw)
else:
try:
fn(*args, **kw)
except Exception, ex:
print ("'%s' failed as expected (condition: %s): %s " % (
fn_name, description, str(ex)))
return True
else:
raise AssertionError(
"Unexpected success for '%s' (condition: %s)" %
(fn_name, description))
return _function_named(maybe, fn_name)
return decorate
def future(fn):
"""Mark a test as expected to unconditionally fail.
Takes no arguments, omit parens when using as a decorator.
"""
fn_name = fn.__name__
def decorated(*args, **kw):
try:
fn(*args, **kw)
except Exception, ex:
print ("Future test '%s' failed as expected: %s " % (
fn_name, str(ex)))
return True
else:
raise AssertionError(
"Unexpected success for future test '%s'" % fn_name)
return _function_named(decorated, fn_name)
def fails_on(*dbs):
"""Mark a test as expected to fail on one or more database implementations.
Unlike ``crashes``, tests marked as ``fails_on`` will be run
for the named databases. The test is expected to fail and the unit test
logic is inverted: if the test fails, a success is reported. If the test
succeeds, a failure is reported.
"""
def decorate(fn):
fn_name = fn.__name__
def maybe(*args, **kw):
if config.db.name not in dbs:
return fn(*args, **kw)
else:
try:
fn(*args, **kw)
except Exception, ex:
print ("'%s' failed as expected on DB implementation "
"'%s': %s" % (
fn_name, config.db.name, str(ex)))
return True
else:
raise AssertionError(
"Unexpected success for '%s' on DB implementation '%s'" %
(fn_name, config.db.name))
return _function_named(maybe, fn_name)
return decorate
def fails_on_everything_except(*dbs):
"""Mark a test as expected to fail on most database implementations.
Like ``fails_on``, except failure is the expected outcome on all
databases except those listed.
"""
def decorate(fn):
fn_name = fn.__name__
def maybe(*args, **kw):
if config.db.name in dbs:
return fn(*args, **kw)
else:
try:
fn(*args, **kw)
except Exception, ex:
print ("'%s' failed as expected on DB implementation "
"'%s': %s" % (
fn_name, config.db.name, str(ex)))
return True
else:
raise AssertionError(
"Unexpected success for '%s' on DB implementation '%s'" %
(fn_name, config.db.name))
return _function_named(maybe, fn_name)
return decorate
def crashes(db, reason):
"""Mark a test as unsupported by a database implementation.
``crashes`` tests will be skipped unconditionally. Use for feature tests
that cause deadlocks or other fatal problems.
"""
carp = _should_carp_about_exclusion(reason)
def decorate(fn):
fn_name = fn.__name__
def maybe(*args, **kw):
if config.db.name == db:
msg = "'%s' unsupported on DB implementation '%s': %s" % (
fn_name, config.db.name, reason)
print msg
if carp:
print >> sys.stderr, msg
return True
else:
return fn(*args, **kw)
return _function_named(maybe, fn_name)
return decorate
def _block_unconditionally(db, reason):
"""Mark a test as unsupported by a database implementation.
Will never run the test against any version of the given database, ever,
no matter what. Use when your assumptions are infallible; past, present
and future.
"""
carp = _should_carp_about_exclusion(reason)
def decorate(fn):
fn_name = fn.__name__
def maybe(*args, **kw):
if config.db.name == db:
msg = "'%s' unsupported on DB implementation '%s': %s" % (
fn_name, config.db.name, reason)
print msg
if carp:
print >> sys.stderr, msg
return True
else:
return fn(*args, **kw)
return _function_named(maybe, fn_name)
return decorate
def exclude(db, op, spec, reason):
"""Mark a test as unsupported by specific database server versions.
Stackable, both with other excludes and other decorators. Examples::
# Not supported by mydb versions less than 1, 0
@exclude('mydb', '<', (1,0))
# Other operators work too
@exclude('bigdb', '==', (9,0,9))
@exclude('yikesdb', 'in', ((0, 3, 'alpha2'), (0, 3, 'alpha3')))
"""
carp = _should_carp_about_exclusion(reason)
def decorate(fn):
fn_name = fn.__name__
def maybe(*args, **kw):
if _is_excluded(db, op, spec):
msg = "'%s' unsupported on DB %s version '%s': %s" % (
fn_name, config.db.name, _server_version(), reason)
print msg
if carp:
print >> sys.stderr, msg
return True
else:
return fn(*args, **kw)
return _function_named(maybe, fn_name)
return decorate
def _should_carp_about_exclusion(reason):
"""Guard against forgotten exclusions."""
assert reason
for _ in ('todo', 'fixme', 'xxx'):
if _ in reason.lower():
return True
else:
if len(reason) < 4:
return True
def _is_excluded(db, op, spec):
"""Return True if the configured db matches an exclusion specification.
db:
A dialect name
op:
An operator or stringified operator, such as '=='
spec:
A value that will be compared to the dialect's server_version_info
using the supplied operator.
Examples::
# Not supported by mydb versions less than 1, 0
_is_excluded('mydb', '<', (1,0))
# Other operators work too
_is_excluded('bigdb', '==', (9,0,9))
_is_excluded('yikesdb', 'in', ((0, 3, 'alpha2'), (0, 3, 'alpha3')))
"""
if config.db.name != db:
return False
version = _server_version()
oper = hasattr(op, '__call__') and op or _ops[op]
return oper(version, spec)
def _server_version(bind=None):
"""Return a server_version_info tuple."""
if bind is None:
bind = config.db
return bind.dialect.server_version_info(bind.contextual_connect())
def skip_if(predicate, reason=None):
"""Skip a test if predicate is true."""
reason = reason or predicate.__name__
def decorate(fn):
fn_name = fn.__name__
def maybe(*args, **kw):
if predicate():
msg = "'%s' skipped on DB %s version '%s': %s" % (
fn_name, config.db.name, _server_version(), reason)
print msg
return True
else:
return fn(*args, **kw)
return _function_named(maybe, fn_name)
return decorate
def emits_warning(*messages):
"""Mark a test as emitting a warning.
With no arguments, squelches all SAWarning failures. Or pass one or more
strings; these will be matched to the root of the warning description by
warnings.filterwarnings().
"""
# TODO: it would be nice to assert that a named warning was
# emitted. should work with some monkeypatching of warnings,
# and may work on non-CPython if they keep to the spirit of
# warnings.showwarning's docstring.
# - update: jython looks ok, it uses cpython's module
def decorate(fn):
def safe(*args, **kw):
global sa_exc
if sa_exc is None:
import sqlalchemy.exc as sa_exc
# todo: should probably be strict about this, too
filters = [dict(action='ignore',
category=sa_exc.SAPendingDeprecationWarning)]
if not messages:
filters.append([dict(action='ignore',
category=sa_exc.SAWarning)])
else:
filters.extend([dict(action='ignore',
message=message,
category=sa_exc.SAWarning)
for message in messages])
for f in filters:
warnings.filterwarnings(**f)
try:
return fn(*args, **kw)
finally:
resetwarnings()
return _function_named(safe, fn.__name__)
return decorate
def uses_deprecated(*messages):
"""Mark a test as immune from fatal deprecation warnings.
With no arguments, squelches all SADeprecationWarning failures.
Or pass one or more strings; these will be matched to the root
of the warning description by warnings.filterwarnings().
As a special case, you may pass a function name prefixed with //
and it will be re-written as needed to match the standard warning
verbiage emitted by the sqlalchemy.util.deprecated decorator.
"""
def decorate(fn):
def safe(*args, **kw):
global sa_exc
if sa_exc is None:
import sqlalchemy.exc as sa_exc
# todo: should probably be strict about this, too
filters = [dict(action='ignore',
category=sa_exc.SAPendingDeprecationWarning)]
if not messages:
filters.append(dict(action='ignore',
category=sa_exc.SADeprecationWarning))
else:
filters.extend(
[dict(action='ignore',
message=message,
category=sa_exc.SADeprecationWarning)
for message in
[ (m.startswith('//') and
('Call to deprecated function ' + m[2:]) or m)
for m in messages] ])
for f in filters:
warnings.filterwarnings(**f)
try:
return fn(*args, **kw)
finally:
resetwarnings()
return _function_named(safe, fn.__name__)
return decorate
def resetwarnings():
"""Reset warning behavior to testing defaults."""
global sa_exc
if sa_exc is None:
import sqlalchemy.exc as sa_exc
warnings.filterwarnings('ignore',
category=sa_exc.SAPendingDeprecationWarning)
warnings.filterwarnings('error', category=sa_exc.SADeprecationWarning)
warnings.filterwarnings('error', category=sa_exc.SAWarning)
if sys.version_info < (2, 4):
warnings.filterwarnings('ignore', category=FutureWarning)
def against(*queries):
"""Boolean predicate, compares to testing database configuration.
Given one or more dialect names, returns True if one is the configured
database engine.
Also supports comparison to database version when provided with one or
more 3-tuples of dialect name, operator, and version specification::
testing.against('mysql', 'postgres')
testing.against(('mysql', '>=', (5, 0, 0))
"""
for query in queries:
if isinstance(query, basestring):
if config.db.name == query:
return True
else:
name, op, spec = query
if config.db.name != name:
continue
have = config.db.dialect.server_version_info(
config.db.contextual_connect())
oper = hasattr(op, '__call__') and op or _ops[op]
if oper(have, spec):
return True
return False
def _chain_decorators_on(fn, *decorators):
"""Apply a series of decorators to fn, returning a decorated function."""
for decorator in reversed(decorators):
fn = decorator(fn)
return fn
def rowset(results):
"""Converts the results of sql execution into a plain set of column tuples.
Useful for asserting the results of an unordered query.
"""
return set([tuple(row) for row in results])
def eq_(a, b, msg=None):
"""Assert a == b, with repr messaging on failure."""
assert a == b, msg or "%r != %r" % (a, b)
def ne_(a, b, msg=None):
"""Assert a != b, with repr messaging on failure."""
assert a != b, msg or "%r == %r" % (a, b)
def is_(a, b, msg=None):
"""Assert a is b, with repr messaging on failure."""
assert a is b, msg or "%r is not %r" % (a, b)
def is_not_(a, b, msg=None):
"""Assert a is not b, with repr messaging on failure."""
assert a is not b, msg or "%r is %r" % (a, b)
def startswith_(a, fragment, msg=None):
"""Assert a.startswith(fragment), with repr messaging on failure."""
assert a.startswith(fragment), msg or "%r does not start with %r" % (
a, fragment)
def fixture(table, columns, *rows):
"""Insert data into table after creation."""
def onload(event, schema_item, connection):
insert = table.insert()
column_names = [col.key for col in columns]
connection.execute(insert, [dict(zip(column_names, column_values))
for column_values in rows])
table.append_ddl_listener('after-create', onload)
class TestData(object):
"""Tracks SQL expressions as they are executed via an instrumented ExecutionContext."""
def __init__(self):
self.set_assert_list(None, None)
self.sql_count = 0
self.buffer = None
def set_assert_list(self, unittest, list):
self.unittest = unittest
self.assert_list = list
if list is not None:
self.assert_list.reverse()
testdata = TestData()
class ExecutionContextWrapper(object):
"""instruments the ExecutionContext created by the Engine so that SQL expressions
can be tracked."""
def __init__(self, ctx):
self.__dict__['ctx'] = ctx
def __getattr__(self, key):
return getattr(self.ctx, key)
def __setattr__(self, key, value):
setattr(self.ctx, key, value)
trailing_underscore_pattern = re.compile(r'(\W:[\w_#]+)_\b',re.MULTILINE)
def post_execution(self):
ctx = self.ctx
statement = unicode(ctx.compiled)
statement = re.sub(r'\n', '', ctx.statement)
if config.db.name == 'mssql' and statement.endswith('; select scope_identity()'):
statement = statement[:-25]
if testdata.buffer is not None:
testdata.buffer.write(statement + "\n")
if testdata.assert_list is not None:
assert len(testdata.assert_list), "Received query but no more assertions: %s" % statement
item = testdata.assert_list[-1]
if not isinstance(item, dict):
item = testdata.assert_list.pop()
else:
# asserting a dictionary of statements->parameters
# this is to specify query assertions where the queries can be in
# multiple orderings
if '_converted' not in item:
for key in item.keys():
ckey = self.convert_statement(key)
item[ckey] = item[key]
if ckey != key:
del item[key]
item['_converted'] = True
try:
entry = item.pop(statement)
if len(item) == 1:
testdata.assert_list.pop()
item = (statement, entry)
except KeyError:
assert False, "Testing for one of the following queries: %s, received '%s'" % (repr([k for k in item.keys()]), statement)
(query, params) = item
if callable(params):
params = params(ctx)
if params is not None and not isinstance(params, list):
params = [params]
parameters = ctx.compiled_parameters
query = self.convert_statement(query)
equivalent = ( (statement == query)
or ( (config.db.name == 'oracle') and (self.trailing_underscore_pattern.sub(r'\1', statement) == query) )
) \
and \
( (params is None) or (params == parameters)
or params == [dict([(k.strip('_'), v)
for (k, v) in p.items()])
for p in parameters]
)
testdata.unittest.assert_(equivalent,
"Testing for query '%s' params %s, received '%s' with params %s" % (query, repr(params), statement, repr(parameters)))
testdata.sql_count += 1
self.ctx.post_execution()
def convert_statement(self, query):
paramstyle = self.ctx.dialect.paramstyle
if paramstyle == 'named':
pass
elif paramstyle =='pyformat':
query = re.sub(r':([\w_]+)', r"%(\1)s", query)
else:
# positional params
repl = None
if paramstyle=='qmark':
repl = "?"
elif paramstyle=='format':
repl = r"%s"
elif paramstyle=='numeric':
repl = None
query = re.sub(r':([\w_]+)', repl, query)
return query
def _import_by_name(name):
submodule = name.split('.')[-1]
return __import__(name, globals(), locals(), [submodule])
class CompositeModule(types.ModuleType):
"""Merged attribute access for multiple modules."""
# break the habit
__all__ = ()
def __init__(self, name, *modules, **overrides):
"""Construct a new lazy composite of modules.
Modules may be string names or module-like instances. Individual
attribute overrides may be specified as keyword arguments for
convenience.
The constructed module will resolve attribute access in reverse order:
overrides, then each member of reversed(modules). Modules specified
by name will be loaded lazily when encountered in attribute
resolution.
"""
types.ModuleType.__init__(self, name)
self.__modules = list(reversed(modules))
for key, value in overrides.iteritems():
setattr(self, key, value)
def __getattr__(self, key):
for idx, mod in enumerate(self.__modules):
if isinstance(mod, basestring):
self.__modules[idx] = mod = _import_by_name(mod)
if hasattr(mod, key):
return getattr(mod, key)
raise AttributeError(key)
def resolve_artifact_names(fn):
"""Decorator, augment function globals with tables and classes.
Swaps out the function's globals at execution time. The 'global' statement
will not work as expected inside a decorated function.
"""
# This could be automatically applied to framework and test_ methods in
# the MappedTest-derived test suites but... *some* explicitness for this
# magic is probably good. Especially as 'global' won't work- these
# rebound functions aren't regular Python..
#
# Also: it's lame that CPython accepts a dict-subclass for globals, but
# only calls dict methods. That would allow 'global' to pass through to
# the func_globals.
def resolved(*args, **kwargs):
self = args[0]
context = dict(fn.func_globals)
for source in self._artifact_registries:
context.update(getattr(self, source))
# jython bug #1034
rebound = types.FunctionType(
fn.func_code, context, fn.func_name, fn.func_defaults,
fn.func_closure)
return rebound(*args, **kwargs)
return _function_named(resolved, fn.func_name)
class adict(dict):
"""Dict keys available as attributes. Shadows."""
def __getattribute__(self, key):
try:
return self[key]
except KeyError:
return dict.__getattribute__(self, key)
def get_all(self, *keys):
return tuple([self[key] for key in keys])
class TestBase(unittest.TestCase):
# A sequence of database names to always run, regardless of the
# constraints below.
__whitelist__ = ()
# A sequence of requirement names matching testing.requires decorators
__requires__ = ()
# A sequence of dialect names to exclude from the test class.
__unsupported_on__ = ()
# If present, test class is only runnable for the *single* specified
# dialect. If you need multiple, use __unsupported_on__ and invert.
__only_on__ = None
# A sequence of no-arg callables. If any are True, the entire testcase is
# skipped.
__skip_if__ = None
_artifact_registries = ()
_sa_first_test = False
_sa_last_test = False
def __init__(self, *args, **params):
unittest.TestCase.__init__(self, *args, **params)
def setUpAll(self):
pass
def tearDownAll(self):
pass
def shortDescription(self):
"""overridden to not return docstrings"""
return None
def assertRaisesMessage(self, except_cls, msg, callable_, *args, **kwargs):
try:
callable_(*args, **kwargs)
assert False, "Callable did not raise an exception"
except except_cls, e:
assert re.search(msg, str(e)), "%r !~ %s" % (msg, e)
if not hasattr(unittest.TestCase, 'assertTrue'):
assertTrue = unittest.TestCase.failUnless
if not hasattr(unittest.TestCase, 'assertFalse'):
assertFalse = unittest.TestCase.failIf
class AssertsCompiledSQL(object):
def assert_compile(self, clause, result, params=None, checkparams=None, dialect=None):
if dialect is None:
dialect = getattr(self, '__dialect__', None)
if params is None:
keys = None
else:
keys = params.keys()
c = clause.compile(column_keys=keys, dialect=dialect)
print "\nSQL String:\n" + str(c) + repr(c.params)
cc = re.sub(r'\n', '', str(c))
self.assertEquals(cc, result, "%r != %r on dialect %r" % (cc, result, dialect))
if checkparams is not None:
self.assertEquals(c.construct_params(params), checkparams)
class ComparesTables(object):
def assert_tables_equal(self, table, reflected_table):
global sqltypes, schema
if sqltypes is None:
import sqlalchemy.types as sqltypes
if schema is None:
import sqlalchemy.schema as schema
base_mro = sqltypes.TypeEngine.__mro__
assert len(table.c) == len(reflected_table.c)
for c, reflected_c in zip(table.c, reflected_table.c):
self.assertEquals(c.name, reflected_c.name)
assert reflected_c is reflected_table.c[c.name]
self.assertEquals(c.primary_key, reflected_c.primary_key)
self.assertEquals(c.nullable, reflected_c.nullable)
assert len(
set(type(reflected_c.type).__mro__).difference(base_mro).intersection(
set(type(c.type).__mro__).difference(base_mro)
)
) > 0, "Type '%s' doesn't correspond to type '%s'" % (reflected_c.type, c.type)
if isinstance(c.type, sqltypes.String):
self.assertEquals(c.type.length, reflected_c.type.length)
self.assertEquals(set([f.column.name for f in c.foreign_keys]), set([f.column.name for f in reflected_c.foreign_keys]))
if c.default:
assert isinstance(reflected_c.server_default,
schema.FetchedValue)
elif against(('mysql', '<', (5, 0))):
# ignore reflection of bogus db-generated DefaultClause()
pass
elif not c.primary_key or not against('postgres'):
print repr(c)
assert reflected_c.default is None, reflected_c.default
assert len(table.primary_key) == len(reflected_table.primary_key)
for c in table.primary_key:
assert reflected_table.primary_key.columns[c.name]
class AssertsExecutionResults(object):
def assert_result(self, result, class_, *objects):
result = list(result)
print repr(result)
self.assert_list(result, class_, objects)
def assert_list(self, result, class_, list):
self.assert_(len(result) == len(list),
"result list is not the same size as test list, " +
"for class " + class_.__name__)
for i in range(0, len(list)):
self.assert_row(class_, result[i], list[i])
def assert_row(self, class_, rowobj, desc):
self.assert_(rowobj.__class__ is class_,
"item class is not " + repr(class_))
for key, value in desc.iteritems():
if isinstance(value, tuple):
if isinstance(value[1], list):
self.assert_list(getattr(rowobj, key), value[0], value[1])
else:
self.assert_row(value[0], getattr(rowobj, key), value[1])
else:
self.assert_(getattr(rowobj, key) == value,
"attribute %s value %s does not match %s" % (
key, getattr(rowobj, key), value))
def assert_unordered_result(self, result, cls, *expected):
"""As assert_result, but the order of objects is not considered.
The algorithm is very expensive but not a big deal for the small
numbers of rows that the test suite manipulates.
"""
global util
if util is None:
from sqlalchemy import util
class frozendict(dict):
def __hash__(self):
return id(self)
found = util.IdentitySet(result)
expected = set([frozendict(e) for e in expected])
for wrong in itertools.ifilterfalse(lambda o: type(o) == cls, found):
self.fail('Unexpected type "%s", expected "%s"' % (
type(wrong).__name__, cls.__name__))
if len(found) != len(expected):
self.fail('Unexpected object count "%s", expected "%s"' % (
len(found), len(expected)))
NOVALUE = object()
def _compare_item(obj, spec):
for key, value in spec.iteritems():
if isinstance(value, tuple):
try:
self.assert_unordered_result(
getattr(obj, key), value[0], *value[1])
except AssertionError:
return False
else:
if getattr(obj, key, NOVALUE) != value:
return False
return True
for expected_item in expected:
for found_item in found:
if _compare_item(found_item, expected_item):
found.remove(found_item)
break
else:
self.fail(
"Expected %s instance with attributes %s not found." % (
cls.__name__, repr(expected_item)))
return True
def assert_sql(self, db, callable_, list, with_sequences=None):
global testdata
testdata = TestData()
if with_sequences is not None and config.db.name in ('firebird', 'oracle', 'postgres'):
testdata.set_assert_list(self, with_sequences)
else:
testdata.set_assert_list(self, list)
try:
callable_()
finally:
testdata.set_assert_list(None, None)
def assert_sql_count(self, db, callable_, count):
global testdata
testdata = TestData()
callable_()
self.assert_(testdata.sql_count == count,
"desired statement count %d does not match %d" % (
count, testdata.sql_count))
def capture_sql(self, db, callable_):
global testdata
testdata = TestData()
buffer = StringIO()
testdata.buffer = buffer
try:
callable_()
return buffer.getvalue()
finally:
testdata.buffer = None
_otest_metadata = None
class ORMTest(TestBase, AssertsExecutionResults):
keep_mappers = False
keep_data = False
metadata = None
def setUpAll(self):
global MetaData, _otest_metadata
if MetaData is None:
from sqlalchemy import MetaData
if self.metadata is None:
_otest_metadata = MetaData(config.db)
else:
_otest_metadata = self.metadata
if self.metadata.bind is None:
_otest_metadata.bind = config.db
self.define_tables(_otest_metadata)
_otest_metadata.create_all()
self.setup_mappers()
self.insert_data()
def define_tables(self, _otest_metadata):
raise NotImplementedError()
def setup_mappers(self):
pass
def insert_data(self):
pass
def get_metadata(self):
return _otest_metadata
def tearDownAll(self):
global clear_mappers
if clear_mappers is None:
from sqlalchemy.orm import clear_mappers
clear_mappers()
_otest_metadata.drop_all()
def tearDown(self):
global Session
if Session is None:
from sqlalchemy.orm.session import Session
Session.close_all()
global clear_mappers
if clear_mappers is None:
from sqlalchemy.orm import clear_mappers
if not self.keep_mappers:
clear_mappers()
if not self.keep_data:
for t in _otest_metadata.table_iterator(reverse=True):
try:
t.delete().execute().close()
except Exception, e:
print "EXCEPTION DELETING...", e
class TTestSuite(unittest.TestSuite):
"""A TestSuite with once per TestCase setUpAll() and tearDownAll()"""
def __init__(self, tests=()):
if len(tests) > 0 and isinstance(tests[0], TestBase):
self._initTest = tests[0]
else:
self._initTest = None
for t in tests:
if isinstance(t, TestBase):
t._sa_first_test = True
break
for t in reversed(tests):
if isinstance(t, TestBase):
t._sa_last_test = True
break
unittest.TestSuite.__init__(self, tests)
def do_run(self, result):
# nice job unittest ! you switched __call__ and run() between py2.3
# and 2.4 thereby making straight subclassing impossible !
for test in self._tests:
if result.shouldStop:
break
test(result)
return result
def run(self, result):
return self(result)
def __should_skip_for(self, cls):
if hasattr(cls, '__requires__'):
global requires
if requires is None:
from testing import requires
def test_suite(): return 'ok'
for requirement in cls.__requires__:
check = getattr(requires, requirement)
if check(test_suite)() != 'ok':
# The requirement will perform messaging.
return True
if (hasattr(cls, '__unsupported_on__') and
config.db.name in cls.__unsupported_on__):
print "'%s' unsupported on DB implementation '%s'" % (
cls.__class__.__name__, config.db.name)
return True
if (getattr(cls, '__only_on__', None) not in (None,config.db.name)):
print "'%s' unsupported on DB implementation '%s'" % (
cls.__class__.__name__, config.db.name)
return True
if (getattr(cls, '__skip_if__', False)):
for c in getattr(cls, '__skip_if__'):
if c():
print "'%s' skipped by %s" % (
cls.__class__.__name__, c.__name__)
return True
for rule in getattr(cls, '__excluded_on__', ()):
if _is_excluded(*rule):
print "'%s' unsupported on DB %s version %s" % (
cls.__class__.__name__, config.db.name,
_server_version())
return True
return False
def __call__(self, result):
init = getattr(self, '_initTest', None)
if init is not None:
if (hasattr(init, '__whitelist__') and
config.db.name in init.__whitelist__):
pass
else:
if self.__should_skip_for(init):
return True
try:
resetwarnings()
init.setUpAll()
except:
# skip tests if global setup fails
ex = self.__exc_info()
for test in self._tests:
result.addError(test, ex)
return False
try:
resetwarnings()
return self.do_run(result)
finally:
try:
resetwarnings()
if init is not None:
init.tearDownAll()
except:
result.addError(init, self.__exc_info())
pass
def __exc_info(self):
"""Return a version of sys.exc_info() with the traceback frame
minimised; usually the top level of the traceback frame is not
needed.
ripped off out of unittest module since its double __
"""
exctype, excvalue, tb = sys.exc_info()
if sys.platform[:4] == 'java': ## tracebacks look different in Jython
return (exctype, excvalue, tb)
return (exctype, excvalue, tb)
# monkeypatch
unittest.TestLoader.suiteClass = TTestSuite
class DevNullWriter(object):
def write(self, msg):
pass
def flush(self):
pass
def runTests(suite):
verbose = config.options.verbose
quiet = config.options.quiet
orig_stdout = sys.stdout
try:
if not verbose or quiet:
sys.stdout = DevNullWriter()
runner = unittest.TextTestRunner(verbosity = quiet and 1 or 2)
return runner.run(suite)
finally:
if not verbose or quiet:
sys.stdout = orig_stdout
def main(suite=None):
if not suite:
if sys.argv[1:]:
suite =unittest.TestLoader().loadTestsFromNames(
sys.argv[1:], __import__('__main__'))
else:
suite = unittest.TestLoader().loadTestsFromModule(
__import__('__main__'))
result = runTests(suite)
sys.exit(not result.wasSuccessful())
|