PageRenderTime 62ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/IPython/deathrow/tests/test_prefilter.py

https://github.com/cboos/ipython
Python | 440 lines | 436 code | 2 blank | 2 comment | 4 complexity | b6aa45c69a6b2e4a5d1b0f31d73dbd5f MD5 | raw file
  1. """
  2. Test which prefilter transformations get called for various input lines.
  3. Note that this does *not* test the transformations themselves -- it's just
  4. verifying that a particular combination of, e.g. config options and escape
  5. chars trigger the proper handle_X transform of the input line.
  6. Usage: run from the command line with *normal* python, not ipython:
  7. > python test_prefilter.py
  8. Fairly quiet output by default. Pass in -v to get everyone's favorite dots.
  9. """
  10. # The prefilter always ends in a call to some self.handle_X method. We swap
  11. # all of those out so that we can capture which one was called.
  12. import sys
  13. sys.path.append('..')
  14. import IPython
  15. import IPython.ipapi
  16. verbose = False
  17. if len(sys.argv) > 1:
  18. if sys.argv[1] == '-v':
  19. sys.argv = sys.argv[:-1] # IPython is confused by -v, apparently
  20. verbose = True
  21. IPython.Shell.start()
  22. ip = IPython.ipapi.get()
  23. # Collect failed tests + stats and print them at the end
  24. failures = []
  25. num_tests = 0
  26. # Store the results in module vars as we go
  27. last_line = None
  28. handler_called = None
  29. def install_mock_handler(name):
  30. """Swap out one of the IP.handle_x methods with a function which can
  31. record which handler was called and what line was produced. The mock
  32. handler func always returns '', which causes ipython to cease handling
  33. the string immediately. That way, that it doesn't echo output, raise
  34. exceptions, etc. But do note that testing multiline strings thus gets
  35. a bit hard."""
  36. def mock_handler(self, line, continue_prompt=None,
  37. pre=None,iFun=None,theRest=None,
  38. obj=None):
  39. #print "Inside %s with '%s'" % (name, line)
  40. global last_line, handler_called
  41. last_line = line
  42. handler_called = name
  43. return ''
  44. mock_handler.name = name
  45. setattr(IPython.iplib.InteractiveShell, name, mock_handler)
  46. install_mock_handler('handle_normal')
  47. install_mock_handler('handle_auto')
  48. install_mock_handler('handle_magic')
  49. install_mock_handler('handle_help')
  50. install_mock_handler('handle_shell_escape')
  51. install_mock_handler('handle_alias')
  52. install_mock_handler('handle_emacs')
  53. def reset_esc_handlers():
  54. """The escape handlers are stored in a hash (as an attribute of the
  55. InteractiveShell *instance*), so we have to rebuild that hash to get our
  56. new handlers in there."""
  57. s = ip.IP
  58. s.esc_handlers = {s.ESC_PAREN : s.handle_auto,
  59. s.ESC_QUOTE : s.handle_auto,
  60. s.ESC_QUOTE2 : s.handle_auto,
  61. s.ESC_MAGIC : s.handle_magic,
  62. s.ESC_HELP : s.handle_help,
  63. s.ESC_SHELL : s.handle_shell_escape,
  64. s.ESC_SH_CAP : s.handle_shell_escape,
  65. }
  66. reset_esc_handlers()
  67. # This is so I don't have to quote over and over. Gotta be a better way.
  68. handle_normal = 'handle_normal'
  69. handle_auto = 'handle_auto'
  70. handle_magic = 'handle_magic'
  71. handle_help = 'handle_help'
  72. handle_shell_escape = 'handle_shell_escape'
  73. handle_alias = 'handle_alias'
  74. handle_emacs = 'handle_emacs'
  75. def check(assertion, failure_msg):
  76. """Check a boolean assertion and fail with a message if necessary. Store
  77. an error essage in module-level failures list in case of failure. Print
  78. '.' or 'F' if module var Verbose is true.
  79. """
  80. global num_tests
  81. num_tests += 1
  82. if assertion:
  83. if verbose:
  84. sys.stdout.write('.')
  85. sys.stdout.flush()
  86. else:
  87. if verbose:
  88. sys.stdout.write('F')
  89. sys.stdout.flush()
  90. failures.append(failure_msg)
  91. def check_handler(expected_handler, line):
  92. """Verify that the expected hander was called (for the given line,
  93. passed in for failure reporting).
  94. Pulled out to its own function so that tests which don't use
  95. run_handler_tests can still take advantage of it."""
  96. check(handler_called == expected_handler,
  97. "Expected %s to be called for %s, "
  98. "instead %s called" % (expected_handler,
  99. repr(line),
  100. handler_called))
  101. def run_handler_tests(h_tests):
  102. """Loop through a series of (input_line, handler_name) pairs, verifying
  103. that, for each ip calls the given handler for the given line.
  104. The verbose complaint includes the line passed in, so if that line can
  105. include enough info to find the error, the tests are modestly
  106. self-documenting.
  107. """
  108. for ln, expected_handler in h_tests:
  109. global handler_called
  110. handler_called = None
  111. ip.runlines(ln)
  112. check_handler(expected_handler, ln)
  113. def run_one_test(ln, expected_handler):
  114. run_handler_tests([(ln, expected_handler)])
  115. # =========================================
  116. # Tests
  117. # =========================================
  118. # Fundamental escape characters + whitespace & misc
  119. # =================================================
  120. esc_handler_tests = [
  121. ( '?thing', handle_help, ),
  122. ( 'thing?', handle_help ), # '?' can trail...
  123. ( 'thing!', handle_normal), # but only '?' can trail
  124. ( ' ?thing', handle_normal), # leading whitespace turns off esc chars
  125. ( '!ls', handle_shell_escape),
  126. ( '! true', handle_shell_escape),
  127. ( '!! true', handle_shell_escape),
  128. ( '%magic', handle_magic),
  129. # XXX Possibly, add test for /,; once those are unhooked from %autocall
  130. ( 'emacs_mode # PYTHON-MODE', handle_emacs ),
  131. ( ' ', handle_normal),
  132. # Trailing qmark combos. Odd special cases abound
  133. # ! always takes priority!
  134. ( '!thing?', handle_shell_escape),
  135. ( '!thing arg?', handle_shell_escape),
  136. ( '!!thing?', handle_shell_escape),
  137. ( '!!thing arg?', handle_shell_escape),
  138. ( ' !!thing arg?', handle_shell_escape),
  139. # For all other leading esc chars, we always trigger help
  140. ( '%cmd?', handle_help),
  141. ( '%cmd ?', handle_help),
  142. ( '/cmd?', handle_help),
  143. ( '/cmd ?', handle_help),
  144. ( ';cmd?', handle_help),
  145. ( ',cmd?', handle_help),
  146. ]
  147. run_handler_tests(esc_handler_tests)
  148. # Shell Escapes in Multi-line statements
  149. # ======================================
  150. #
  151. # We can't test this via runlines, since the hacked-over-for-testing
  152. # handlers all return None, so continue_prompt never becomes true. Instead
  153. # we drop into prefilter directly and pass in continue_prompt.
  154. old_mls = ip.options.multi_line_specials
  155. for ln in [ ' !ls $f multi_line_specials %s',
  156. ' !!ls $f multi_line_specials %s', # !! escapes work on mls
  157. # Trailing ? doesn't trigger help:
  158. ' !ls $f multi_line_specials %s ?',
  159. ' !!ls $f multi_line_specials %s ?',
  160. ]:
  161. ip.options.multi_line_specials = 1
  162. on_ln = ln % 'on'
  163. ignore = ip.IP.prefilter(on_ln, continue_prompt=True)
  164. check_handler(handle_shell_escape, on_ln)
  165. ip.options.multi_line_specials = 0
  166. off_ln = ln % 'off'
  167. ignore = ip.IP.prefilter(off_ln, continue_prompt=True)
  168. check_handler(handle_normal, off_ln)
  169. ip.options.multi_line_specials = old_mls
  170. # Automagic
  171. # =========
  172. # Pick one magic fun and one non_magic fun, make sure both exist
  173. assert hasattr(ip.IP, "magic_cpaste")
  174. assert not hasattr(ip.IP, "magic_does_not_exist")
  175. ip.options.autocall = 0 # gotta have this off to get handle_normal
  176. ip.options.automagic = 0
  177. run_handler_tests([
  178. # Without automagic, only shows up with explicit escape
  179. ( 'cpaste', handle_normal),
  180. ( '%cpaste', handle_magic),
  181. ( '%does_not_exist', handle_magic),
  182. ])
  183. ip.options.automagic = 1
  184. run_handler_tests([
  185. ( 'cpaste', handle_magic),
  186. ( '%cpaste', handle_magic),
  187. ( 'does_not_exist', handle_normal),
  188. ( '%does_not_exist', handle_magic),
  189. ( 'cd /', handle_magic),
  190. ( 'cd = 2', handle_normal),
  191. ( 'r', handle_magic),
  192. ( 'r thing', handle_magic),
  193. ( 'r"str"', handle_normal),
  194. ])
  195. # If next elt starts with anything that could be an assignment, func call,
  196. # etc, we don't call the magic func, unless explicitly escaped to do so.
  197. #magic_killing_tests = []
  198. #for c in list('!=()<>,'):
  199. # magic_killing_tests.append(('cpaste %s killed_automagic' % c, handle_normal))
  200. # magic_killing_tests.append(('%%cpaste %s escaped_magic' % c, handle_magic))
  201. #run_handler_tests(magic_killing_tests)
  202. # magic on indented continuation lines -- on iff multi_line_specials == 1
  203. ip.options.multi_line_specials = 0
  204. ln = ' cpaste multi_line off kills magic'
  205. ignore = ip.IP.prefilter(ln, continue_prompt=True)
  206. check_handler(handle_normal, ln)
  207. ip.options.multi_line_specials = 1
  208. ln = ' cpaste multi_line on enables magic'
  209. ignore = ip.IP.prefilter(ln, continue_prompt=True)
  210. check_handler(handle_magic, ln)
  211. # user namespace shadows the magic one unless shell escaped
  212. ip.user_ns['cpaste'] = 'user_ns'
  213. run_handler_tests([
  214. ( 'cpaste', handle_normal),
  215. ( '%cpaste', handle_magic)])
  216. del ip.user_ns['cpaste']
  217. # Check for !=() turning off .ofind
  218. # =================================
  219. class AttributeMutator(object):
  220. """A class which will be modified on attribute access, to test ofind"""
  221. def __init__(self):
  222. self.called = False
  223. def getFoo(self): self.called = True
  224. foo = property(getFoo)
  225. attr_mutator = AttributeMutator()
  226. ip.to_user_ns('attr_mutator')
  227. ip.options.autocall = 1
  228. run_one_test('attr_mutator.foo should mutate', handle_normal)
  229. check(attr_mutator.called, 'ofind should be called in absence of assign characters')
  230. for c in list('!=()<>+*/%^&|'):
  231. attr_mutator.called = False
  232. run_one_test('attr_mutator.foo %s should *not* mutate' % c, handle_normal)
  233. run_one_test('attr_mutator.foo%s should *not* mutate' % c, handle_normal)
  234. check(not attr_mutator.called,
  235. 'ofind should not be called near character %s' % c)
  236. # Alias expansion
  237. # ===============
  238. # With autocall on or off, aliases should be shadowed by user, internal and
  239. # __builtin__ namespaces
  240. #
  241. # XXX Can aliases have '.' in their name? With autocall off, that works,
  242. # with autocall on, it doesn't. Hmmm.
  243. import __builtin__
  244. for ac_state in [0,1]:
  245. ip.options.autocall = ac_state
  246. ip.IP.alias_table['alias_cmd'] = 'alias_result'
  247. ip.IP.alias_table['alias_head.with_dot'] = 'alias_result'
  248. run_handler_tests([
  249. ("alias_cmd", handle_alias),
  250. # XXX See note above
  251. #("alias_head.with_dot unshadowed, autocall=%s" % ac_state, handle_alias),
  252. ("alias_cmd.something aliases must match whole expr", handle_normal),
  253. ("alias_cmd /", handle_alias),
  254. ])
  255. for ns in [ip.user_ns, ip.IP.internal_ns, __builtin__.__dict__ ]:
  256. ns['alias_cmd'] = 'a user value'
  257. ns['alias_head'] = 'a user value'
  258. run_handler_tests([
  259. ("alias_cmd", handle_normal),
  260. ("alias_head.with_dot", handle_normal)])
  261. del ns['alias_cmd']
  262. del ns['alias_head']
  263. ip.options.autocall = 1
  264. # Autocall
  265. # ========
  266. # For all the tests below, 'len' is callable / 'thing' is not
  267. # Objects which are instances of IPyAutocall are *always* autocalled
  268. import IPython.ipapi
  269. class Autocallable(IPython.ipapi.IPyAutocall):
  270. def __call__(self):
  271. return "called"
  272. autocallable = Autocallable()
  273. ip.to_user_ns('autocallable')
  274. # First, with autocalling fully off
  275. ip.options.autocall = 0
  276. run_handler_tests( [
  277. # With no escapes, no autocalling expansions happen, callable or not,
  278. # unless the obj extends IPyAutocall
  279. ( 'len autocall_0', handle_normal),
  280. ( 'thing autocall_0', handle_normal),
  281. ( 'autocallable', handle_auto),
  282. # With explicit escapes, callable and non-callables both get expanded,
  283. # regardless of the %autocall setting:
  284. ( '/len autocall_0', handle_auto),
  285. ( ',len autocall_0 b0', handle_auto),
  286. ( ';len autocall_0 b0', handle_auto),
  287. ( '/thing autocall_0', handle_auto),
  288. ( ',thing autocall_0 b0', handle_auto),
  289. ( ';thing autocall_0 b0', handle_auto),
  290. # Explicit autocall should not trigger if there is leading whitespace
  291. ( ' /len autocall_0', handle_normal),
  292. ( ' ;len autocall_0', handle_normal),
  293. ( ' ,len autocall_0', handle_normal),
  294. ( ' / len autocall_0', handle_normal),
  295. # But should work if the whitespace comes after the esc char
  296. ( '/ len autocall_0', handle_auto),
  297. ( '; len autocall_0', handle_auto),
  298. ( ', len autocall_0', handle_auto),
  299. ( '/ len autocall_0', handle_auto),
  300. ])
  301. # Now, with autocall in default, 'smart' mode
  302. ip.options.autocall = 1
  303. run_handler_tests( [
  304. # Autocalls without escapes -- only expand if it's callable
  305. ( 'len a1', handle_auto),
  306. ( 'thing a1', handle_normal),
  307. ( 'autocallable', handle_auto),
  308. # As above, all explicit escapes generate auto-calls, callable or not
  309. ( '/len a1', handle_auto),
  310. ( ',len a1 b1', handle_auto),
  311. ( ';len a1 b1', handle_auto),
  312. ( '/thing a1', handle_auto),
  313. ( ',thing a1 b1', handle_auto),
  314. ( ';thing a1 b1', handle_auto),
  315. # Autocalls only happen on things which look like funcs, even if
  316. # explicitly requested. Which, in this case means they look like a
  317. # sequence of identifiers and . attribute references. Possibly the
  318. # second of these two should trigger handle_auto. But not for now.
  319. ( '"abc".join range(4)', handle_normal),
  320. ( '/"abc".join range(4)', handle_normal),
  321. ])
  322. # No tests for autocall = 2, since the extra magic there happens inside the
  323. # handle_auto function, which our test doesn't examine.
  324. # Note that we leave autocall in default, 1, 'smart' mode
  325. # Autocall / Binary operators
  326. # ==========================
  327. # Even with autocall on, 'len in thing' won't transform.
  328. # But ';len in thing' will
  329. # Note, the tests below don't check for multi-char ops. It could.
  330. # XXX % is a binary op and should be in the list, too, but fails
  331. bin_ops = list(r'<>,&^|*/+-') + 'is not in and or'.split()
  332. bin_tests = []
  333. for b in bin_ops:
  334. bin_tests.append(('len %s binop_autocall' % b, handle_normal))
  335. bin_tests.append((';len %s binop_autocall' % b, handle_auto))
  336. bin_tests.append((',len %s binop_autocall' % b, handle_auto))
  337. bin_tests.append(('/len %s binop_autocall' % b, handle_auto))
  338. # Who loves auto-generating tests?
  339. run_handler_tests(bin_tests)
  340. # Possibly add tests for namespace shadowing (really ofind's business?).
  341. #
  342. # user > ipython internal > python builtin > alias > magic
  343. # ============
  344. # Test Summary
  345. # ============
  346. num_f = len(failures)
  347. if verbose:
  348. print
  349. print "%s tests run, %s failure%s" % (num_tests,
  350. num_f,
  351. num_f != 1 and "s" or "")
  352. for f in failures:
  353. print f