assertions.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. # testing/assertions.py
  2. # Copyright (C) 2005-2017 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. from __future__ import absolute_import
  8. from . import util as testutil
  9. from sqlalchemy import pool, orm, util
  10. from sqlalchemy.engine import default, url
  11. from sqlalchemy.util import decorator, compat
  12. from sqlalchemy import types as sqltypes, schema, exc as sa_exc
  13. import warnings
  14. import re
  15. from .exclusions import db_spec
  16. from . import assertsql
  17. from . import config
  18. from .util import fail
  19. import contextlib
  20. from . import mock
  21. def expect_warnings(*messages, **kw):
  22. """Context manager which expects one or more warnings.
  23. With no arguments, squelches all SAWarnings emitted via
  24. sqlalchemy.util.warn and sqlalchemy.util.warn_limited. Otherwise
  25. pass string expressions that will match selected warnings via regex;
  26. all non-matching warnings are sent through.
  27. The expect version **asserts** that the warnings were in fact seen.
  28. Note that the test suite sets SAWarning warnings to raise exceptions.
  29. """
  30. return _expect_warnings(sa_exc.SAWarning, messages, **kw)
  31. @contextlib.contextmanager
  32. def expect_warnings_on(db, *messages, **kw):
  33. """Context manager which expects one or more warnings on specific
  34. dialects.
  35. The expect version **asserts** that the warnings were in fact seen.
  36. """
  37. spec = db_spec(db)
  38. if isinstance(db, util.string_types) and not spec(config._current):
  39. yield
  40. else:
  41. with expect_warnings(*messages, **kw):
  42. yield
  43. def emits_warning(*messages):
  44. """Decorator form of expect_warnings().
  45. Note that emits_warning does **not** assert that the warnings
  46. were in fact seen.
  47. """
  48. @decorator
  49. def decorate(fn, *args, **kw):
  50. with expect_warnings(assert_=False, *messages):
  51. return fn(*args, **kw)
  52. return decorate
  53. def expect_deprecated(*messages, **kw):
  54. return _expect_warnings(sa_exc.SADeprecationWarning, messages, **kw)
  55. def emits_warning_on(db, *messages):
  56. """Mark a test as emitting a warning on a specific dialect.
  57. With no arguments, squelches all SAWarning failures. Or pass one or more
  58. strings; these will be matched to the root of the warning description by
  59. warnings.filterwarnings().
  60. Note that emits_warning_on does **not** assert that the warnings
  61. were in fact seen.
  62. """
  63. @decorator
  64. def decorate(fn, *args, **kw):
  65. with expect_warnings_on(db, assert_=False, *messages):
  66. return fn(*args, **kw)
  67. return decorate
  68. def uses_deprecated(*messages):
  69. """Mark a test as immune from fatal deprecation warnings.
  70. With no arguments, squelches all SADeprecationWarning failures.
  71. Or pass one or more strings; these will be matched to the root
  72. of the warning description by warnings.filterwarnings().
  73. As a special case, you may pass a function name prefixed with //
  74. and it will be re-written as needed to match the standard warning
  75. verbiage emitted by the sqlalchemy.util.deprecated decorator.
  76. Note that uses_deprecated does **not** assert that the warnings
  77. were in fact seen.
  78. """
  79. @decorator
  80. def decorate(fn, *args, **kw):
  81. with expect_deprecated(*messages, assert_=False):
  82. return fn(*args, **kw)
  83. return decorate
  84. @contextlib.contextmanager
  85. def _expect_warnings(exc_cls, messages, regex=True, assert_=True,
  86. py2konly=False):
  87. if regex:
  88. filters = [re.compile(msg, re.I | re.S) for msg in messages]
  89. else:
  90. filters = messages
  91. seen = set(filters)
  92. real_warn = warnings.warn
  93. def our_warn(msg, exception, *arg, **kw):
  94. if not issubclass(exception, exc_cls):
  95. return real_warn(msg, exception, *arg, **kw)
  96. if not filters:
  97. return
  98. for filter_ in filters:
  99. if (regex and filter_.match(msg)) or \
  100. (not regex and filter_ == msg):
  101. seen.discard(filter_)
  102. break
  103. else:
  104. real_warn(msg, exception, *arg, **kw)
  105. with mock.patch("warnings.warn", our_warn):
  106. yield
  107. if assert_ and (not py2konly or not compat.py3k):
  108. assert not seen, "Warnings were not seen: %s" % \
  109. ", ".join("%r" % (s.pattern if regex else s) for s in seen)
  110. def global_cleanup_assertions():
  111. """Check things that have to be finalized at the end of a test suite.
  112. Hardcoded at the moment, a modular system can be built here
  113. to support things like PG prepared transactions, tables all
  114. dropped, etc.
  115. """
  116. _assert_no_stray_pool_connections()
  117. _STRAY_CONNECTION_FAILURES = 0
  118. def _assert_no_stray_pool_connections():
  119. global _STRAY_CONNECTION_FAILURES
  120. # lazy gc on cPython means "do nothing." pool connections
  121. # shouldn't be in cycles, should go away.
  122. testutil.lazy_gc()
  123. # however, once in awhile, on an EC2 machine usually,
  124. # there's a ref in there. usually just one.
  125. if pool._refs:
  126. # OK, let's be somewhat forgiving.
  127. _STRAY_CONNECTION_FAILURES += 1
  128. print("Encountered a stray connection in test cleanup: %s"
  129. % str(pool._refs))
  130. # then do a real GC sweep. We shouldn't even be here
  131. # so a single sweep should really be doing it, otherwise
  132. # there's probably a real unreachable cycle somewhere.
  133. testutil.gc_collect()
  134. # if we've already had two of these occurrences, or
  135. # after a hard gc sweep we still have pool._refs?!
  136. # now we have to raise.
  137. if pool._refs:
  138. err = str(pool._refs)
  139. # but clean out the pool refs collection directly,
  140. # reset the counter,
  141. # so the error doesn't at least keep happening.
  142. pool._refs.clear()
  143. _STRAY_CONNECTION_FAILURES = 0
  144. warnings.warn(
  145. "Stray connection refused to leave "
  146. "after gc.collect(): %s" % err)
  147. elif _STRAY_CONNECTION_FAILURES > 10:
  148. assert False, "Encountered more than 10 stray connections"
  149. _STRAY_CONNECTION_FAILURES = 0
  150. def eq_regex(a, b, msg=None):
  151. assert re.match(b, a), msg or "%r !~ %r" % (a, b)
  152. def eq_(a, b, msg=None):
  153. """Assert a == b, with repr messaging on failure."""
  154. assert a == b, msg or "%r != %r" % (a, b)
  155. def ne_(a, b, msg=None):
  156. """Assert a != b, with repr messaging on failure."""
  157. assert a != b, msg or "%r == %r" % (a, b)
  158. def le_(a, b, msg=None):
  159. """Assert a <= b, with repr messaging on failure."""
  160. assert a <= b, msg or "%r != %r" % (a, b)
  161. def is_true(a, msg=None):
  162. is_(a, True, msg=msg)
  163. def is_false(a, msg=None):
  164. is_(a, False, msg=msg)
  165. def is_(a, b, msg=None):
  166. """Assert a is b, with repr messaging on failure."""
  167. assert a is b, msg or "%r is not %r" % (a, b)
  168. def is_not_(a, b, msg=None):
  169. """Assert a is not b, with repr messaging on failure."""
  170. assert a is not b, msg or "%r is %r" % (a, b)
  171. def in_(a, b, msg=None):
  172. """Assert a in b, with repr messaging on failure."""
  173. assert a in b, msg or "%r not in %r" % (a, b)
  174. def not_in_(a, b, msg=None):
  175. """Assert a in not b, with repr messaging on failure."""
  176. assert a not in b, msg or "%r is in %r" % (a, b)
  177. def startswith_(a, fragment, msg=None):
  178. """Assert a.startswith(fragment), with repr messaging on failure."""
  179. assert a.startswith(fragment), msg or "%r does not start with %r" % (
  180. a, fragment)
  181. def eq_ignore_whitespace(a, b, msg=None):
  182. a = re.sub(r'^\s+?|\n', "", a)
  183. a = re.sub(r' {2,}', " ", a)
  184. b = re.sub(r'^\s+?|\n', "", b)
  185. b = re.sub(r' {2,}', " ", b)
  186. assert a == b, msg or "%r != %r" % (a, b)
  187. def assert_raises(except_cls, callable_, *args, **kw):
  188. try:
  189. callable_(*args, **kw)
  190. success = False
  191. except except_cls:
  192. success = True
  193. # assert outside the block so it works for AssertionError too !
  194. assert success, "Callable did not raise an exception"
  195. def assert_raises_message(except_cls, msg, callable_, *args, **kwargs):
  196. try:
  197. callable_(*args, **kwargs)
  198. assert False, "Callable did not raise an exception"
  199. except except_cls as e:
  200. assert re.search(
  201. msg, util.text_type(e), re.UNICODE), "%r !~ %s" % (msg, e)
  202. print(util.text_type(e).encode('utf-8'))
  203. class AssertsCompiledSQL(object):
  204. def assert_compile(self, clause, result, params=None,
  205. checkparams=None, dialect=None,
  206. checkpositional=None,
  207. check_prefetch=None,
  208. use_default_dialect=False,
  209. allow_dialect_select=False,
  210. literal_binds=False,
  211. schema_translate_map=None):
  212. if use_default_dialect:
  213. dialect = default.DefaultDialect()
  214. elif allow_dialect_select:
  215. dialect = None
  216. else:
  217. if dialect is None:
  218. dialect = getattr(self, '__dialect__', None)
  219. if dialect is None:
  220. dialect = config.db.dialect
  221. elif dialect == 'default':
  222. dialect = default.DefaultDialect()
  223. elif dialect == 'default_enhanced':
  224. dialect = default.StrCompileDialect()
  225. elif isinstance(dialect, util.string_types):
  226. dialect = url.URL(dialect).get_dialect()()
  227. kw = {}
  228. compile_kwargs = {}
  229. if schema_translate_map:
  230. kw['schema_translate_map'] = schema_translate_map
  231. if params is not None:
  232. kw['column_keys'] = list(params)
  233. if literal_binds:
  234. compile_kwargs['literal_binds'] = True
  235. if isinstance(clause, orm.Query):
  236. context = clause._compile_context()
  237. context.statement.use_labels = True
  238. clause = context.statement
  239. if compile_kwargs:
  240. kw['compile_kwargs'] = compile_kwargs
  241. c = clause.compile(dialect=dialect, **kw)
  242. param_str = repr(getattr(c, 'params', {}))
  243. if util.py3k:
  244. param_str = param_str.encode('utf-8').decode('ascii', 'ignore')
  245. print(
  246. ("\nSQL String:\n" +
  247. util.text_type(c) +
  248. param_str).encode('utf-8'))
  249. else:
  250. print(
  251. "\nSQL String:\n" +
  252. util.text_type(c).encode('utf-8') +
  253. param_str)
  254. cc = re.sub(r'[\n\t]', '', util.text_type(c))
  255. eq_(cc, result, "%r != %r on dialect %r" % (cc, result, dialect))
  256. if checkparams is not None:
  257. eq_(c.construct_params(params), checkparams)
  258. if checkpositional is not None:
  259. p = c.construct_params(params)
  260. eq_(tuple([p[x] for x in c.positiontup]), checkpositional)
  261. if check_prefetch is not None:
  262. eq_(c.prefetch, check_prefetch)
  263. class ComparesTables(object):
  264. def assert_tables_equal(self, table, reflected_table, strict_types=False):
  265. assert len(table.c) == len(reflected_table.c)
  266. for c, reflected_c in zip(table.c, reflected_table.c):
  267. eq_(c.name, reflected_c.name)
  268. assert reflected_c is reflected_table.c[c.name]
  269. eq_(c.primary_key, reflected_c.primary_key)
  270. eq_(c.nullable, reflected_c.nullable)
  271. if strict_types:
  272. msg = "Type '%s' doesn't correspond to type '%s'"
  273. assert isinstance(reflected_c.type, type(c.type)), \
  274. msg % (reflected_c.type, c.type)
  275. else:
  276. self.assert_types_base(reflected_c, c)
  277. if isinstance(c.type, sqltypes.String):
  278. eq_(c.type.length, reflected_c.type.length)
  279. eq_(
  280. set([f.column.name for f in c.foreign_keys]),
  281. set([f.column.name for f in reflected_c.foreign_keys])
  282. )
  283. if c.server_default:
  284. assert isinstance(reflected_c.server_default,
  285. schema.FetchedValue)
  286. assert len(table.primary_key) == len(reflected_table.primary_key)
  287. for c in table.primary_key:
  288. assert reflected_table.primary_key.columns[c.name] is not None
  289. def assert_types_base(self, c1, c2):
  290. assert c1.type._compare_type_affinity(c2.type),\
  291. "On column %r, type '%s' doesn't correspond to type '%s'" % \
  292. (c1.name, c1.type, c2.type)
  293. class AssertsExecutionResults(object):
  294. def assert_result(self, result, class_, *objects):
  295. result = list(result)
  296. print(repr(result))
  297. self.assert_list(result, class_, objects)
  298. def assert_list(self, result, class_, list):
  299. self.assert_(len(result) == len(list),
  300. "result list is not the same size as test list, " +
  301. "for class " + class_.__name__)
  302. for i in range(0, len(list)):
  303. self.assert_row(class_, result[i], list[i])
  304. def assert_row(self, class_, rowobj, desc):
  305. self.assert_(rowobj.__class__ is class_,
  306. "item class is not " + repr(class_))
  307. for key, value in desc.items():
  308. if isinstance(value, tuple):
  309. if isinstance(value[1], list):
  310. self.assert_list(getattr(rowobj, key), value[0], value[1])
  311. else:
  312. self.assert_row(value[0], getattr(rowobj, key), value[1])
  313. else:
  314. self.assert_(getattr(rowobj, key) == value,
  315. "attribute %s value %s does not match %s" % (
  316. key, getattr(rowobj, key), value))
  317. def assert_unordered_result(self, result, cls, *expected):
  318. """As assert_result, but the order of objects is not considered.
  319. The algorithm is very expensive but not a big deal for the small
  320. numbers of rows that the test suite manipulates.
  321. """
  322. class immutabledict(dict):
  323. def __hash__(self):
  324. return id(self)
  325. found = util.IdentitySet(result)
  326. expected = set([immutabledict(e) for e in expected])
  327. for wrong in util.itertools_filterfalse(lambda o:
  328. isinstance(o, cls), found):
  329. fail('Unexpected type "%s", expected "%s"' % (
  330. type(wrong).__name__, cls.__name__))
  331. if len(found) != len(expected):
  332. fail('Unexpected object count "%s", expected "%s"' % (
  333. len(found), len(expected)))
  334. NOVALUE = object()
  335. def _compare_item(obj, spec):
  336. for key, value in spec.items():
  337. if isinstance(value, tuple):
  338. try:
  339. self.assert_unordered_result(
  340. getattr(obj, key), value[0], *value[1])
  341. except AssertionError:
  342. return False
  343. else:
  344. if getattr(obj, key, NOVALUE) != value:
  345. return False
  346. return True
  347. for expected_item in expected:
  348. for found_item in found:
  349. if _compare_item(found_item, expected_item):
  350. found.remove(found_item)
  351. break
  352. else:
  353. fail(
  354. "Expected %s instance with attributes %s not found." % (
  355. cls.__name__, repr(expected_item)))
  356. return True
  357. def sql_execution_asserter(self, db=None):
  358. if db is None:
  359. from . import db as db
  360. return assertsql.assert_engine(db)
  361. def assert_sql_execution(self, db, callable_, *rules):
  362. with self.sql_execution_asserter(db) as asserter:
  363. callable_()
  364. asserter.assert_(*rules)
  365. def assert_sql(self, db, callable_, rules):
  366. newrules = []
  367. for rule in rules:
  368. if isinstance(rule, dict):
  369. newrule = assertsql.AllOf(*[
  370. assertsql.CompiledSQL(k, v) for k, v in rule.items()
  371. ])
  372. else:
  373. newrule = assertsql.CompiledSQL(*rule)
  374. newrules.append(newrule)
  375. self.assert_sql_execution(db, callable_, *newrules)
  376. def assert_sql_count(self, db, callable_, count):
  377. self.assert_sql_execution(
  378. db, callable_, assertsql.CountStatements(count))
  379. @contextlib.contextmanager
  380. def assert_execution(self, *rules):
  381. assertsql.asserter.add_rules(rules)
  382. try:
  383. yield
  384. assertsql.asserter.statement_complete()
  385. finally:
  386. assertsql.asserter.clear_rules()
  387. def assert_statement_count(self, count):
  388. return self.assert_execution(assertsql.CountStatements(count))