test_message_spec.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. """Test suite for our zeromq-based message specification."""
  2. # Copyright (c) IPython Development Team.
  3. # Distributed under the terms of the Modified BSD License.
  4. import re
  5. import sys
  6. from distutils.version import LooseVersion as V
  7. try:
  8. from queue import Empty # Py 3
  9. except ImportError:
  10. from Queue import Empty # Py 2
  11. import nose.tools as nt
  12. from nose.plugins.skip import SkipTest
  13. from traitlets import (
  14. HasTraits, TraitError, Bool, Unicode, Dict, Integer, List, Enum
  15. )
  16. from ipython_genutils.py3compat import string_types, iteritems
  17. from .utils import TIMEOUT, start_global_kernel, flush_channels, execute
  18. #-----------------------------------------------------------------------------
  19. # Globals
  20. #-----------------------------------------------------------------------------
  21. KC = None
  22. def setup():
  23. global KC
  24. KC = start_global_kernel()
  25. #-----------------------------------------------------------------------------
  26. # Message Spec References
  27. #-----------------------------------------------------------------------------
  28. class Reference(HasTraits):
  29. """
  30. Base class for message spec specification testing.
  31. This class is the core of the message specification test. The
  32. idea is that child classes implement trait attributes for each
  33. message keys, so that message keys can be tested against these
  34. traits using :meth:`check` method.
  35. """
  36. def check(self, d):
  37. """validate a dict against our traits"""
  38. for key in self.trait_names():
  39. assert key in d
  40. # FIXME: always allow None, probably not a good idea
  41. if d[key] is None:
  42. continue
  43. try:
  44. setattr(self, key, d[key])
  45. except TraitError as e:
  46. assert False, str(e)
  47. class Version(Unicode):
  48. def __init__(self, *args, **kwargs):
  49. self.min = kwargs.pop('min', None)
  50. self.max = kwargs.pop('max', None)
  51. kwargs['default_value'] = self.min
  52. super(Version, self).__init__(*args, **kwargs)
  53. def validate(self, obj, value):
  54. if self.min and V(value) < V(self.min):
  55. raise TraitError("bad version: %s < %s" % (value, self.min))
  56. if self.max and (V(value) > V(self.max)):
  57. raise TraitError("bad version: %s > %s" % (value, self.max))
  58. class RMessage(Reference):
  59. msg_id = Unicode()
  60. msg_type = Unicode()
  61. header = Dict()
  62. parent_header = Dict()
  63. content = Dict()
  64. def check(self, d):
  65. super(RMessage, self).check(d)
  66. RHeader().check(self.header)
  67. if self.parent_header:
  68. RHeader().check(self.parent_header)
  69. class RHeader(Reference):
  70. msg_id = Unicode()
  71. msg_type = Unicode()
  72. session = Unicode()
  73. username = Unicode()
  74. version = Version(min='5.0')
  75. mime_pat = re.compile(r'^[\w\-\+\.]+/[\w\-\+\.]+$')
  76. class MimeBundle(Reference):
  77. metadata = Dict()
  78. data = Dict()
  79. def _data_changed(self, name, old, new):
  80. for k,v in iteritems(new):
  81. assert mime_pat.match(k)
  82. assert isinstance(v, string_types)
  83. # shell replies
  84. class Reply(Reference):
  85. status = Enum((u'ok', u'error'), default_value=u'ok')
  86. class ExecuteReply(Reply):
  87. execution_count = Integer()
  88. def check(self, d):
  89. Reference.check(self, d)
  90. if d['status'] == 'ok':
  91. ExecuteReplyOkay().check(d)
  92. elif d['status'] == 'error':
  93. ExecuteReplyError().check(d)
  94. class ExecuteReplyOkay(Reply):
  95. status = Enum(('ok',))
  96. user_expressions = Dict()
  97. class ExecuteReplyError(Reply):
  98. ename = Unicode()
  99. evalue = Unicode()
  100. traceback = List(Unicode())
  101. class InspectReply(Reply, MimeBundle):
  102. found = Bool()
  103. class ArgSpec(Reference):
  104. args = List(Unicode())
  105. varargs = Unicode()
  106. varkw = Unicode()
  107. defaults = List()
  108. class Status(Reference):
  109. execution_state = Enum((u'busy', u'idle', u'starting'), default_value=u'busy')
  110. class CompleteReply(Reply):
  111. matches = List(Unicode())
  112. cursor_start = Integer()
  113. cursor_end = Integer()
  114. status = Unicode()
  115. class LanguageInfo(Reference):
  116. name = Unicode('python')
  117. version = Unicode(sys.version.split()[0])
  118. class KernelInfoReply(Reply):
  119. protocol_version = Version(min='5.0')
  120. implementation = Unicode('ipython')
  121. implementation_version = Version(min='2.1')
  122. language_info = Dict()
  123. banner = Unicode()
  124. def check(self, d):
  125. Reference.check(self, d)
  126. LanguageInfo().check(d['language_info'])
  127. class ConnectReply(Reference):
  128. shell_port = Integer()
  129. control_port = Integer()
  130. stdin_port = Integer()
  131. iopub_port = Integer()
  132. hb_port = Integer()
  133. class CommInfoReply(Reply):
  134. comms = Dict()
  135. class IsCompleteReply(Reference):
  136. status = Enum((u'complete', u'incomplete', u'invalid', u'unknown'), default_value=u'complete')
  137. def check(self, d):
  138. Reference.check(self, d)
  139. if d['status'] == 'incomplete':
  140. IsCompleteReplyIncomplete().check(d)
  141. class IsCompleteReplyIncomplete(Reference):
  142. indent = Unicode()
  143. # IOPub messages
  144. class ExecuteInput(Reference):
  145. code = Unicode()
  146. execution_count = Integer()
  147. class Error(ExecuteReplyError):
  148. """Errors are the same as ExecuteReply, but without status"""
  149. status = None # no status field
  150. class Stream(Reference):
  151. name = Enum((u'stdout', u'stderr'), default_value=u'stdout')
  152. text = Unicode()
  153. class DisplayData(MimeBundle):
  154. pass
  155. class ExecuteResult(MimeBundle):
  156. execution_count = Integer()
  157. class HistoryReply(Reply):
  158. history = List(List())
  159. references = {
  160. 'execute_reply' : ExecuteReply(),
  161. 'inspect_reply' : InspectReply(),
  162. 'status' : Status(),
  163. 'complete_reply' : CompleteReply(),
  164. 'kernel_info_reply': KernelInfoReply(),
  165. 'connect_reply': ConnectReply(),
  166. 'comm_info_reply': CommInfoReply(),
  167. 'is_complete_reply': IsCompleteReply(),
  168. 'execute_input' : ExecuteInput(),
  169. 'execute_result' : ExecuteResult(),
  170. 'history_reply' : HistoryReply(),
  171. 'error' : Error(),
  172. 'stream' : Stream(),
  173. 'display_data' : DisplayData(),
  174. 'header' : RHeader(),
  175. }
  176. """
  177. Specifications of `content` part of the reply messages.
  178. """
  179. def validate_message(msg, msg_type=None, parent=None):
  180. """validate a message
  181. This is a generator, and must be iterated through to actually
  182. trigger each test.
  183. If msg_type and/or parent are given, the msg_type and/or parent msg_id
  184. are compared with the given values.
  185. """
  186. RMessage().check(msg)
  187. if msg_type:
  188. assert msg['msg_type'] == msg_type
  189. if parent:
  190. assert msg['parent_header']['msg_id'] == parent
  191. content = msg['content']
  192. ref = references[msg['msg_type']]
  193. ref.check(content)
  194. #-----------------------------------------------------------------------------
  195. # Tests
  196. #-----------------------------------------------------------------------------
  197. # Shell channel
  198. def test_execute():
  199. flush_channels()
  200. msg_id = KC.execute(code='x=1')
  201. reply = KC.get_shell_msg(timeout=TIMEOUT)
  202. validate_message(reply, 'execute_reply', msg_id)
  203. def test_execute_silent():
  204. flush_channels()
  205. msg_id, reply = execute(code='x=1', silent=True)
  206. # flush status=idle
  207. status = KC.iopub_channel.get_msg(timeout=TIMEOUT)
  208. validate_message(status, 'status', msg_id)
  209. assert status['content']['execution_state'] == 'idle'
  210. nt.assert_raises(Empty, KC.iopub_channel.get_msg, timeout=0.1)
  211. count = reply['execution_count']
  212. msg_id, reply = execute(code='x=2', silent=True)
  213. # flush status=idle
  214. status = KC.iopub_channel.get_msg(timeout=TIMEOUT)
  215. validate_message(status, 'status', msg_id)
  216. assert status['content']['execution_state'] == 'idle'
  217. nt.assert_raises(Empty, KC.iopub_channel.get_msg, timeout=0.1)
  218. count_2 = reply['execution_count']
  219. assert count_2 == count
  220. def test_execute_error():
  221. flush_channels()
  222. msg_id, reply = execute(code='1/0')
  223. assert reply['status'] == 'error'
  224. assert reply['ename'] == 'ZeroDivisionError'
  225. error = KC.iopub_channel.get_msg(timeout=TIMEOUT)
  226. validate_message(error, 'error', msg_id)
  227. def test_execute_inc():
  228. """execute request should increment execution_count"""
  229. flush_channels()
  230. msg_id, reply = execute(code='x=1')
  231. count = reply['execution_count']
  232. flush_channels()
  233. msg_id, reply = execute(code='x=2')
  234. count_2 = reply['execution_count']
  235. assert count_2 == count+1
  236. def test_execute_stop_on_error():
  237. """execute request should not abort execution queue with stop_on_error False"""
  238. flush_channels()
  239. fail = '\n'.join([
  240. # sleep to ensure subsequent message is waiting in the queue to be aborted
  241. 'import time',
  242. 'time.sleep(0.5)',
  243. 'raise ValueError',
  244. ])
  245. KC.execute(code=fail)
  246. msg_id = KC.execute(code='print("Hello")')
  247. KC.get_shell_msg(timeout=TIMEOUT)
  248. reply = KC.get_shell_msg(timeout=TIMEOUT)
  249. assert reply['content']['status'] == 'aborted'
  250. flush_channels()
  251. KC.execute(code=fail, stop_on_error=False)
  252. msg_id = KC.execute(code='print("Hello")')
  253. KC.get_shell_msg(timeout=TIMEOUT)
  254. reply = KC.get_shell_msg(timeout=TIMEOUT)
  255. assert reply['content']['status'] == 'ok'
  256. def test_user_expressions():
  257. flush_channels()
  258. msg_id, reply = execute(code='x=1', user_expressions=dict(foo='x+1'))
  259. user_expressions = reply['user_expressions']
  260. nt.assert_equal(user_expressions, {u'foo': {
  261. u'status': u'ok',
  262. u'data': {u'text/plain': u'2'},
  263. u'metadata': {},
  264. }})
  265. def test_user_expressions_fail():
  266. flush_channels()
  267. msg_id, reply = execute(code='x=0', user_expressions=dict(foo='nosuchname'))
  268. user_expressions = reply['user_expressions']
  269. foo = user_expressions['foo']
  270. assert foo['status'] == 'error'
  271. assert foo['ename'] == 'NameError'
  272. def test_oinfo():
  273. flush_channels()
  274. msg_id = KC.inspect('a')
  275. reply = KC.get_shell_msg(timeout=TIMEOUT)
  276. validate_message(reply, 'inspect_reply', msg_id)
  277. def test_oinfo_found():
  278. flush_channels()
  279. msg_id, reply = execute(code='a=5')
  280. msg_id = KC.inspect('a')
  281. reply = KC.get_shell_msg(timeout=TIMEOUT)
  282. validate_message(reply, 'inspect_reply', msg_id)
  283. content = reply['content']
  284. assert content['found']
  285. text = content['data']['text/plain']
  286. assert 'Type:' in text
  287. assert 'Docstring:' in text
  288. def test_oinfo_detail():
  289. flush_channels()
  290. msg_id, reply = execute(code='ip=get_ipython()')
  291. msg_id = KC.inspect('ip.object_inspect', cursor_pos=10, detail_level=1)
  292. reply = KC.get_shell_msg(timeout=TIMEOUT)
  293. validate_message(reply, 'inspect_reply', msg_id)
  294. content = reply['content']
  295. assert content['found']
  296. text = content['data']['text/plain']
  297. assert 'Signature:' in text
  298. assert 'Source:' in text
  299. def test_oinfo_not_found():
  300. flush_channels()
  301. msg_id = KC.inspect('dne')
  302. reply = KC.get_shell_msg(timeout=TIMEOUT)
  303. validate_message(reply, 'inspect_reply', msg_id)
  304. content = reply['content']
  305. assert not content['found']
  306. def test_complete():
  307. flush_channels()
  308. msg_id, reply = execute(code="alpha = albert = 5")
  309. msg_id = KC.complete('al', 2)
  310. reply = KC.get_shell_msg(timeout=TIMEOUT)
  311. validate_message(reply, 'complete_reply', msg_id)
  312. matches = reply['content']['matches']
  313. for name in ('alpha', 'albert'):
  314. assert name in matches
  315. def test_kernel_info_request():
  316. flush_channels()
  317. msg_id = KC.kernel_info()
  318. reply = KC.get_shell_msg(timeout=TIMEOUT)
  319. validate_message(reply, 'kernel_info_reply', msg_id)
  320. def test_connect_request():
  321. flush_channels()
  322. msg = KC.session.msg('connect_request')
  323. KC.shell_channel.send(msg)
  324. return msg['header']['msg_id']
  325. msg_id = KC.kernel_info()
  326. reply = KC.get_shell_msg(timeout=TIMEOUT)
  327. validate_message(reply, 'connect_reply', msg_id)
  328. def test_comm_info_request():
  329. flush_channels()
  330. if not hasattr(KC, 'comm_info'):
  331. raise SkipTest()
  332. msg_id = KC.comm_info()
  333. reply = KC.get_shell_msg(timeout=TIMEOUT)
  334. validate_message(reply, 'comm_info_reply', msg_id)
  335. def test_single_payload():
  336. flush_channels()
  337. msg_id, reply = execute(code="ip = get_ipython()\n"
  338. "for i in range(3):\n"
  339. " ip.set_next_input('Hello There')\n")
  340. payload = reply['payload']
  341. next_input_pls = [pl for pl in payload if pl["source"] == "set_next_input"]
  342. assert len(next_input_pls) == 1
  343. def test_is_complete():
  344. flush_channels()
  345. msg_id = KC.is_complete("a = 1")
  346. reply = KC.get_shell_msg(timeout=TIMEOUT)
  347. validate_message(reply, 'is_complete_reply', msg_id)
  348. def test_history_range():
  349. flush_channels()
  350. msg_id_exec = KC.execute(code='x=1', store_history = True)
  351. reply_exec = KC.get_shell_msg(timeout=TIMEOUT)
  352. msg_id = KC.history(hist_access_type = 'range', raw = True, output = True, start = 1, stop = 2, session = 0)
  353. reply = KC.get_shell_msg(timeout=TIMEOUT)
  354. validate_message(reply, 'history_reply', msg_id)
  355. content = reply['content']
  356. assert len(content['history']) == 1
  357. def test_history_tail():
  358. flush_channels()
  359. msg_id_exec = KC.execute(code='x=1', store_history = True)
  360. reply_exec = KC.get_shell_msg(timeout=TIMEOUT)
  361. msg_id = KC.history(hist_access_type = 'tail', raw = True, output = True, n = 1, session = 0)
  362. reply = KC.get_shell_msg(timeout=TIMEOUT)
  363. validate_message(reply, 'history_reply', msg_id)
  364. content = reply['content']
  365. assert len(content['history']) == 1
  366. def test_history_search():
  367. flush_channels()
  368. msg_id_exec = KC.execute(code='x=1', store_history = True)
  369. reply_exec = KC.get_shell_msg(timeout=TIMEOUT)
  370. msg_id = KC.history(hist_access_type = 'search', raw = True, output = True, n = 1, pattern = '*', session = 0)
  371. reply = KC.get_shell_msg(timeout=TIMEOUT)
  372. validate_message(reply, 'history_reply', msg_id)
  373. content = reply['content']
  374. assert len(content['history']) == 1
  375. # IOPub channel
  376. def test_stream():
  377. flush_channels()
  378. msg_id, reply = execute("print('hi')")
  379. stdout = KC.iopub_channel.get_msg(timeout=TIMEOUT)
  380. validate_message(stdout, 'stream', msg_id)
  381. content = stdout['content']
  382. assert content['text'] == u'hi\n'
  383. def test_display_data():
  384. flush_channels()
  385. msg_id, reply = execute("from IPython.core.display import display; display(1)")
  386. display = KC.iopub_channel.get_msg(timeout=TIMEOUT)
  387. validate_message(display, 'display_data', parent=msg_id)
  388. data = display['content']['data']
  389. assert data['text/plain'] == u'1'