test.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  1. from __future__ import absolute_import
  2. import sys
  3. import doctest
  4. import unittest
  5. import decimal
  6. import inspect
  7. import functools
  8. import collections
  9. from collections import defaultdict
  10. try:
  11. c = collections.abc
  12. except AttributeError:
  13. c = collections
  14. from decorator import dispatch_on, contextmanager, decorator
  15. try:
  16. from . import documentation as doc
  17. except (ImportError, ValueError, SystemError): # depending on the py-version
  18. import documentation as doc
  19. @contextmanager
  20. def assertRaises(etype):
  21. """This works in Python 2.6 too"""
  22. try:
  23. yield
  24. except etype:
  25. pass
  26. else:
  27. raise Exception('Expected %s' % etype.__name__)
  28. if sys.version_info >= (3, 5):
  29. exec('''from asyncio import get_event_loop
  30. @decorator
  31. async def before_after(coro, *args, **kwargs):
  32. return "<before>" + (await coro(*args, **kwargs)) + "<after>"
  33. @decorator
  34. def coro_to_func(coro, *args, **kw):
  35. return get_event_loop().run_until_complete(coro(*args, **kw))
  36. class CoroutineTestCase(unittest.TestCase):
  37. def test_before_after(self):
  38. @before_after
  39. async def coro(x):
  40. return x
  41. self.assertTrue(inspect.iscoroutinefunction(coro))
  42. out = get_event_loop().run_until_complete(coro('x'))
  43. self.assertEqual(out, '<before>x<after>')
  44. def test_coro_to_func(self):
  45. @coro_to_func
  46. async def coro(x):
  47. return x
  48. self.assertFalse(inspect.iscoroutinefunction(coro))
  49. self.assertEqual(coro('x'), 'x')
  50. ''')
  51. def gen123():
  52. yield 1
  53. yield 2
  54. yield 3
  55. class GeneratorCallerTestCase(unittest.TestCase):
  56. def test_gen123(self):
  57. @decorator
  58. def square(func, *args, **kw):
  59. for x in gen123():
  60. yield x * x
  61. new = square(gen123)
  62. self.assertTrue(inspect.isgeneratorfunction(new))
  63. self.assertEqual(list(new()), [1, 4, 9])
  64. class DocumentationTestCase(unittest.TestCase):
  65. def test(self):
  66. err = doctest.testmod(doc)[0]
  67. self.assertEqual(err, 0)
  68. def test_singledispatch1(self):
  69. if hasattr(functools, 'singledispatch'):
  70. with assertRaises(RuntimeError):
  71. doc.singledispatch_example1()
  72. def test_singledispatch2(self):
  73. if hasattr(functools, 'singledispatch'):
  74. doc.singledispatch_example2()
  75. class ExtraTestCase(unittest.TestCase):
  76. def test_qualname(self):
  77. if sys.version_info >= (3, 3):
  78. self.assertEqual(doc.hello.__qualname__, 'hello')
  79. else:
  80. with assertRaises(AttributeError):
  81. doc.hello.__qualname__
  82. def test_signature(self):
  83. if hasattr(inspect, 'signature'):
  84. sig = inspect.signature(doc.f1)
  85. self.assertEqual(str(sig), '(x)')
  86. def test_unique_filenames(self):
  87. @decorator
  88. def d1(f, *args, **kwargs):
  89. return f(*args, **kwargs)
  90. @decorator
  91. def d2(f, *args, **kwargs):
  92. return f(*args, **kwargs)
  93. @d1
  94. def f1(x, y, z):
  95. pass
  96. @d2
  97. def f2(x, y, z):
  98. pass
  99. f1_orig = f1
  100. @d1
  101. def f1(x, y, z):
  102. pass
  103. self.assertNotEqual(d1.__code__.co_filename, d2.__code__.co_filename)
  104. self.assertNotEqual(f1.__code__.co_filename, f2.__code__.co_filename)
  105. self.assertNotEqual(f1_orig.__code__.co_filename,
  106. f1.__code__.co_filename)
  107. def test_no_first_arg(self):
  108. @decorator
  109. def example(*args, **kw):
  110. return args[0](*args[1:], **kw)
  111. @example
  112. def func(**kw):
  113. return kw
  114. # there is no confusion when passing args as a keyword argument
  115. self.assertEqual(func(args='a'), {'args': 'a'})
  116. def test_decorator_factory(self):
  117. # similar to what IPython is doing in traitlets.config.application
  118. @decorator
  119. def catch_config_error(method, app, *args, **kwargs):
  120. return method(app)
  121. catch_config_error(lambda app: None)
  122. def test_add1(self):
  123. # similar to what IPython is doing in traitlets.config.application
  124. @decorator
  125. def add(func, const=1, *args, **kwargs):
  126. return const + func(*args, **kwargs)
  127. def f(x):
  128. return x
  129. self.assertEqual(add(f, 2)(0), 2)
  130. # ################### test dispatch_on ############################# #
  131. # adapted from test_functools in Python 3.5
  132. singledispatch = dispatch_on('obj')
  133. class TestSingleDispatch(unittest.TestCase):
  134. def test_simple_overloads(self):
  135. @singledispatch
  136. def g(obj):
  137. return "base"
  138. @g.register(int)
  139. def g_int(i):
  140. return "integer"
  141. self.assertEqual(g("str"), "base")
  142. self.assertEqual(g(1), "integer")
  143. self.assertEqual(g([1, 2, 3]), "base")
  144. def test_mro(self):
  145. @singledispatch
  146. def g(obj):
  147. return "base"
  148. class A(object):
  149. pass
  150. class C(A):
  151. pass
  152. class B(A):
  153. pass
  154. class D(C, B):
  155. pass
  156. @g.register(A)
  157. def g_A(a):
  158. return "A"
  159. @g.register(B)
  160. def g_B(b):
  161. return "B"
  162. self.assertEqual(g(A()), "A")
  163. self.assertEqual(g(B()), "B")
  164. self.assertEqual(g(C()), "A")
  165. self.assertEqual(g(D()), "B")
  166. def test_register_decorator(self):
  167. @singledispatch
  168. def g(obj):
  169. return "base"
  170. @g.register(int)
  171. def g_int(i):
  172. return "int %s" % (i,)
  173. self.assertEqual(g(""), "base")
  174. self.assertEqual(g(12), "int 12")
  175. def test_register_error(self):
  176. @singledispatch
  177. def g(obj):
  178. return "base"
  179. with assertRaises(TypeError):
  180. # wrong number of arguments
  181. @g.register(int)
  182. def g_int():
  183. return "int"
  184. def test_wrapping_attributes(self):
  185. @singledispatch
  186. def g(obj):
  187. "Simple test"
  188. return "Test"
  189. self.assertEqual(g.__name__, "g")
  190. if sys.flags.optimize < 2:
  191. self.assertEqual(g.__doc__, "Simple test")
  192. def test_c_classes(self):
  193. @singledispatch
  194. def g(obj):
  195. return "base"
  196. @g.register(decimal.DecimalException)
  197. def _(obj):
  198. return obj.args
  199. subn = decimal.Subnormal("Exponent < Emin")
  200. rnd = decimal.Rounded("Number got rounded")
  201. self.assertEqual(g(subn), ("Exponent < Emin",))
  202. self.assertEqual(g(rnd), ("Number got rounded",))
  203. @g.register(decimal.Subnormal)
  204. def _g(obj):
  205. return "Too small to care."
  206. self.assertEqual(g(subn), "Too small to care.")
  207. self.assertEqual(g(rnd), ("Number got rounded",))
  208. def test_register_abc(self):
  209. d = {"a": "b"}
  210. l = [1, 2, 3]
  211. s = set([object(), None])
  212. f = frozenset(s)
  213. t = (1, 2, 3)
  214. @singledispatch
  215. def g(obj):
  216. return "base"
  217. self.assertEqual(g(d), "base")
  218. self.assertEqual(g(l), "base")
  219. self.assertEqual(g(s), "base")
  220. self.assertEqual(g(f), "base")
  221. self.assertEqual(g(t), "base")
  222. g.register(c.Sized)(lambda obj: "sized")
  223. self.assertEqual(g(d), "sized")
  224. self.assertEqual(g(l), "sized")
  225. self.assertEqual(g(s), "sized")
  226. self.assertEqual(g(f), "sized")
  227. self.assertEqual(g(t), "sized")
  228. g.register(c.MutableMapping)(lambda obj: "mutablemapping")
  229. self.assertEqual(g(d), "mutablemapping")
  230. self.assertEqual(g(l), "sized")
  231. self.assertEqual(g(s), "sized")
  232. self.assertEqual(g(f), "sized")
  233. self.assertEqual(g(t), "sized")
  234. if hasattr(c, 'ChainMap'):
  235. g.register(c.ChainMap)(lambda obj: "chainmap")
  236. # irrelevant ABCs registered
  237. self.assertEqual(g(d), "mutablemapping")
  238. self.assertEqual(g(l), "sized")
  239. self.assertEqual(g(s), "sized")
  240. self.assertEqual(g(f), "sized")
  241. self.assertEqual(g(t), "sized")
  242. g.register(c.MutableSequence)(lambda obj: "mutablesequence")
  243. self.assertEqual(g(d), "mutablemapping")
  244. self.assertEqual(g(l), "mutablesequence")
  245. self.assertEqual(g(s), "sized")
  246. self.assertEqual(g(f), "sized")
  247. self.assertEqual(g(t), "sized")
  248. g.register(c.MutableSet)(lambda obj: "mutableset")
  249. self.assertEqual(g(d), "mutablemapping")
  250. self.assertEqual(g(l), "mutablesequence")
  251. self.assertEqual(g(s), "mutableset")
  252. self.assertEqual(g(f), "sized")
  253. self.assertEqual(g(t), "sized")
  254. g.register(c.Mapping)(lambda obj: "mapping")
  255. self.assertEqual(g(d), "mutablemapping") # not specific enough
  256. self.assertEqual(g(l), "mutablesequence")
  257. self.assertEqual(g(s), "mutableset")
  258. self.assertEqual(g(f), "sized")
  259. self.assertEqual(g(t), "sized")
  260. g.register(c.Sequence)(lambda obj: "sequence")
  261. self.assertEqual(g(d), "mutablemapping")
  262. self.assertEqual(g(l), "mutablesequence")
  263. self.assertEqual(g(s), "mutableset")
  264. self.assertEqual(g(f), "sized")
  265. self.assertEqual(g(t), "sequence")
  266. g.register(c.Set)(lambda obj: "set")
  267. self.assertEqual(g(d), "mutablemapping")
  268. self.assertEqual(g(l), "mutablesequence")
  269. self.assertEqual(g(s), "mutableset")
  270. self.assertEqual(g(f), "set")
  271. self.assertEqual(g(t), "sequence")
  272. g.register(dict)(lambda obj: "dict")
  273. self.assertEqual(g(d), "dict")
  274. self.assertEqual(g(l), "mutablesequence")
  275. self.assertEqual(g(s), "mutableset")
  276. self.assertEqual(g(f), "set")
  277. self.assertEqual(g(t), "sequence")
  278. g.register(list)(lambda obj: "list")
  279. self.assertEqual(g(d), "dict")
  280. self.assertEqual(g(l), "list")
  281. self.assertEqual(g(s), "mutableset")
  282. self.assertEqual(g(f), "set")
  283. self.assertEqual(g(t), "sequence")
  284. g.register(set)(lambda obj: "concrete-set")
  285. self.assertEqual(g(d), "dict")
  286. self.assertEqual(g(l), "list")
  287. self.assertEqual(g(s), "concrete-set")
  288. self.assertEqual(g(f), "set")
  289. self.assertEqual(g(t), "sequence")
  290. g.register(frozenset)(lambda obj: "frozen-set")
  291. self.assertEqual(g(d), "dict")
  292. self.assertEqual(g(l), "list")
  293. self.assertEqual(g(s), "concrete-set")
  294. self.assertEqual(g(f), "frozen-set")
  295. self.assertEqual(g(t), "sequence")
  296. g.register(tuple)(lambda obj: "tuple")
  297. self.assertEqual(g(d), "dict")
  298. self.assertEqual(g(l), "list")
  299. self.assertEqual(g(s), "concrete-set")
  300. self.assertEqual(g(f), "frozen-set")
  301. self.assertEqual(g(t), "tuple")
  302. def test_mro_conflicts(self):
  303. @singledispatch
  304. def g(obj):
  305. return "base"
  306. class O(c.Sized):
  307. def __len__(self):
  308. return 0
  309. o = O()
  310. self.assertEqual(g(o), "base")
  311. g.register(c.Iterable)(lambda arg: "iterable")
  312. g.register(c.Container)(lambda arg: "container")
  313. g.register(c.Sized)(lambda arg: "sized")
  314. g.register(c.Set)(lambda arg: "set")
  315. self.assertEqual(g(o), "sized")
  316. c.Iterable.register(O)
  317. self.assertEqual(g(o), "sized")
  318. c.Container.register(O)
  319. with assertRaises(RuntimeError): # was "sized" because in mro
  320. self.assertEqual(g(o), "sized")
  321. c.Set.register(O)
  322. self.assertEqual(g(o), "set")
  323. class P(object):
  324. pass
  325. p = P()
  326. self.assertEqual(g(p), "base")
  327. c.Iterable.register(P)
  328. self.assertEqual(g(p), "iterable")
  329. c.Container.register(P)
  330. with assertRaises(RuntimeError):
  331. self.assertEqual(g(p), "iterable")
  332. class Q(c.Sized):
  333. def __len__(self):
  334. return 0
  335. q = Q()
  336. self.assertEqual(g(q), "sized")
  337. c.Iterable.register(Q)
  338. self.assertEqual(g(q), "sized")
  339. c.Set.register(Q)
  340. self.assertEqual(g(q), "set")
  341. # because c.Set is a subclass of c.Sized and c.Iterable
  342. @singledispatch
  343. def h(obj):
  344. return "base"
  345. @h.register(c.Sized)
  346. def h_sized(arg):
  347. return "sized"
  348. @h.register(c.Container)
  349. def h_container(arg):
  350. return "container"
  351. # Even though Sized and Container are explicit bases of MutableMapping,
  352. # this ABC is implicitly registered on defaultdict which makes all of
  353. # MutableMapping's bases implicit as well from defaultdict's
  354. # perspective.
  355. with assertRaises(RuntimeError):
  356. self.assertEqual(h(defaultdict(lambda: 0)), "sized")
  357. class R(defaultdict):
  358. pass
  359. c.MutableSequence.register(R)
  360. @singledispatch
  361. def i(obj):
  362. return "base"
  363. @i.register(c.MutableMapping)
  364. def i_mapping(arg):
  365. return "mapping"
  366. @i.register(c.MutableSequence)
  367. def i_sequence(arg):
  368. return "sequence"
  369. r = R()
  370. with assertRaises(RuntimeError): # was no error
  371. self.assertEqual(i(r), "sequence")
  372. class S(object):
  373. pass
  374. class T(S, c.Sized):
  375. def __len__(self):
  376. return 0
  377. t = T()
  378. self.assertEqual(h(t), "sized")
  379. c.Container.register(T)
  380. self.assertEqual(h(t), "sized") # because it's explicitly in the MRO
  381. class U(object):
  382. def __len__(self):
  383. return 0
  384. u = U()
  385. self.assertEqual(h(u), "sized")
  386. # implicit Sized subclass inferred
  387. # from the existence of __len__()
  388. c.Container.register(U)
  389. # There is no preference for registered versus inferred ABCs.
  390. with assertRaises(RuntimeError):
  391. h(u)
  392. if __name__ == '__main__':
  393. unittest.main()