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
|
"""Test suite for our zeromq-based messaging specification.
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING.txt, distributed as part of this software.
#-----------------------------------------------------------------------------
import re
import sys
import time
from subprocess import PIPE
from Queue import Empty
import nose.tools as nt
from ..blockingkernelmanager import BlockingKernelManager
from IPython.testing import decorators as dec
from IPython.utils import io
from IPython.utils.traitlets import (
HasTraits, TraitError, Bool, Unicode, Dict, Integer, List, Enum,
)
#-----------------------------------------------------------------------------
# Global setup and utilities
#-----------------------------------------------------------------------------
def setup():
global KM
KM = BlockingKernelManager()
KM.start_kernel(stdout=PIPE, stderr=PIPE)
KM.start_channels()
# wait for kernel to be ready
KM.shell_channel.execute("pass")
KM.shell_channel.get_msg(block=True, timeout=5)
flush_channels()
def teardown():
KM.stop_channels()
KM.shutdown_kernel()
def flush_channels():
"""flush any messages waiting on the queue"""
for channel in (KM.shell_channel, KM.sub_channel):
while True:
try:
msg = channel.get_msg(block=True, timeout=0.1)
except Empty:
break
else:
list(validate_message(msg))
def execute(code='', **kwargs):
"""wrapper for doing common steps for validating an execution request"""
shell = KM.shell_channel
sub = KM.sub_channel
msg_id = shell.execute(code=code, **kwargs)
reply = shell.get_msg(timeout=2)
list(validate_message(reply, 'execute_reply', msg_id))
busy = sub.get_msg(timeout=2)
list(validate_message(busy, 'status', msg_id))
nt.assert_equals(busy['content']['execution_state'], 'busy')
if not kwargs.get('silent'):
pyin = sub.get_msg(timeout=2)
list(validate_message(pyin, 'pyin', msg_id))
nt.assert_equals(pyin['content']['code'], code)
return msg_id, reply['content']
#-----------------------------------------------------------------------------
# MSG Spec References
#-----------------------------------------------------------------------------
class Reference(HasTraits):
def check(self, d):
"""validate a dict against our traits"""
for key in self.trait_names():
yield nt.assert_true(key in d, "Missing key: %r, should be found in %s" % (key, d))
# FIXME: always allow None, probably not a good idea
if d[key] is None:
continue
try:
setattr(self, key, d[key])
except TraitError as e:
yield nt.assert_true(False, str(e))
class RMessage(Reference):
msg_id = Unicode()
msg_type = Unicode()
header = Dict()
parent_header = Dict()
content = Dict()
class RHeader(Reference):
msg_id = Unicode()
msg_type = Unicode()
session = Unicode()
username = Unicode()
class RContent(Reference):
status = Enum((u'ok', u'error'))
class ExecuteReply(Reference):
execution_count = Integer()
status = Enum((u'ok', u'error'))
def check(self, d):
for tst in Reference.check(self, d):
yield tst
if d['status'] == 'ok':
for tst in ExecuteReplyOkay().check(d):
yield tst
elif d['status'] == 'error':
for tst in ExecuteReplyError().check(d):
yield tst
class ExecuteReplyOkay(Reference):
payload = List(Dict)
user_variables = Dict()
user_expressions = Dict()
class ExecuteReplyError(Reference):
ename = Unicode()
evalue = Unicode()
traceback = List(Unicode)
class OInfoReply(Reference):
name = Unicode()
found = Bool()
ismagic = Bool()
isalias = Bool()
namespace = Enum((u'builtin', u'magics', u'alias', u'Interactive'))
type_name = Unicode()
string_form = Unicode()
base_class = Unicode()
length = Integer()
file = Unicode()
definition = Unicode()
argspec = Dict()
init_definition = Unicode()
docstring = Unicode()
init_docstring = Unicode()
class_docstring = Unicode()
call_def = Unicode()
call_docstring = Unicode()
source = Unicode()
def check(self, d):
for tst in Reference.check(self, d):
yield tst
if d['argspec'] is not None:
for tst in ArgSpec().check(d['argspec']):
yield tst
class ArgSpec(Reference):
args = List(Unicode)
varargs = Unicode()
varkw = Unicode()
defaults = List()
class Status(Reference):
execution_state = Enum((u'busy', u'idle'))
class CompleteReply(Reference):
matches = List(Unicode)
# IOPub messages
class PyIn(Reference):
code = Unicode()
execution_count = Integer()
PyErr = ExecuteReplyError
class Stream(Reference):
name = Enum((u'stdout', u'stderr'))
data = Unicode()
mime_pat = re.compile(r'\w+/\w+')
class DisplayData(Reference):
source = Unicode()
metadata = Dict()
data = Dict()
def _data_changed(self, name, old, new):
for k,v in new.iteritems():
nt.assert_true(mime_pat.match(k))
nt.assert_true(isinstance(v, basestring), "expected string data, got %r" % v)
class PyOut(Reference):
execution_count = Integer()
data = Dict()
def _data_changed(self, name, old, new):
for k,v in new.iteritems():
nt.assert_true(mime_pat.match(k))
nt.assert_true(isinstance(v, basestring), "expected string data, got %r" % v)
references = {
'execute_reply' : ExecuteReply(),
'object_info_reply' : OInfoReply(),
'status' : Status(),
'complete_reply' : CompleteReply(),
'pyin' : PyIn(),
'pyout' : PyOut(),
'pyerr' : PyErr(),
'stream' : Stream(),
'display_data' : DisplayData(),
}
def validate_message(msg, msg_type=None, parent=None):
"""validate a message
This is a generator, and must be iterated through to actually
trigger each test.
If msg_type and/or parent are given, the msg_type and/or parent msg_id
are compared with the given values.
"""
RMessage().check(msg)
if msg_type:
yield nt.assert_equals(msg['msg_type'], msg_type)
if parent:
yield nt.assert_equal(msg['parent_header']['msg_id'], parent)
content = msg['content']
ref = references[msg['msg_type']]
for tst in ref.check(content):
yield tst
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
# Shell channel
@dec.parametric
def test_execute():
flush_channels()
shell = KM.shell_channel
msg_id = shell.execute(code='x=1')
reply = shell.get_msg(timeout=2)
for tst in validate_message(reply, 'execute_reply', msg_id):
yield tst
@dec.parametric
def test_execute_silent():
flush_channels()
msg_id, reply = execute(code='x=1', silent=True)
# flush status=idle
status = KM.sub_channel.get_msg(timeout=2)
for tst in validate_message(status, 'status', msg_id):
yield tst
nt.assert_equals(status['content']['execution_state'], 'idle')
yield nt.assert_raises(Empty, KM.sub_channel.get_msg, timeout=0.1)
count = reply['execution_count']
msg_id, reply = execute(code='x=2', silent=True)
# flush status=idle
status = KM.sub_channel.get_msg(timeout=2)
for tst in validate_message(status, 'status', msg_id):
yield tst
yield nt.assert_equals(status['content']['execution_state'], 'idle')
yield nt.assert_raises(Empty, KM.sub_channel.get_msg, timeout=0.1)
count_2 = reply['execution_count']
yield nt.assert_equals(count_2, count)
@dec.parametric
def test_execute_error():
flush_channels()
msg_id, reply = execute(code='1/0')
yield nt.assert_equals(reply['status'], 'error')
yield nt.assert_equals(reply['ename'], 'ZeroDivisionError')
pyerr = KM.sub_channel.get_msg(timeout=2)
for tst in validate_message(pyerr, 'pyerr', msg_id):
yield tst
def test_execute_inc():
"""execute request should increment execution_count"""
flush_channels()
msg_id, reply = execute(code='x=1')
count = reply['execution_count']
flush_channels()
msg_id, reply = execute(code='x=2')
count_2 = reply['execution_count']
nt.assert_equals(count_2, count+1)
def test_user_variables():
flush_channels()
msg_id, reply = execute(code='x=1', user_variables=['x'])
user_variables = reply['user_variables']
nt.assert_equals(user_variables, {u'x' : u'1'})
def test_user_expressions():
flush_channels()
msg_id, reply = execute(code='x=1', user_expressions=dict(foo='x+1'))
user_expressions = reply['user_expressions']
nt.assert_equals(user_expressions, {u'foo' : u'2'})
@dec.parametric
def test_oinfo():
flush_channels()
shell = KM.shell_channel
msg_id = shell.object_info('a')
reply = shell.get_msg(timeout=2)
for tst in validate_message(reply, 'object_info_reply', msg_id):
yield tst
@dec.parametric
def test_oinfo_found():
flush_channels()
shell = KM.shell_channel
msg_id, reply = execute(code='a=5')
msg_id = shell.object_info('a')
reply = shell.get_msg(timeout=2)
for tst in validate_message(reply, 'object_info_reply', msg_id):
yield tst
content = reply['content']
yield nt.assert_true(content['found'])
argspec = content['argspec']
yield nt.assert_true(argspec is None, "didn't expect argspec dict, got %r" % argspec)
@dec.parametric
def test_oinfo_detail():
flush_channels()
shell = KM.shell_channel
msg_id, reply = execute(code='ip=get_ipython()')
msg_id = shell.object_info('ip.object_inspect', detail_level=2)
reply = shell.get_msg(timeout=2)
for tst in validate_message(reply, 'object_info_reply', msg_id):
yield tst
content = reply['content']
yield nt.assert_true(content['found'])
argspec = content['argspec']
yield nt.assert_true(isinstance(argspec, dict), "expected non-empty argspec dict, got %r" % argspec)
yield nt.assert_equals(argspec['defaults'], [0])
@dec.parametric
def test_oinfo_not_found():
flush_channels()
shell = KM.shell_channel
msg_id = shell.object_info('dne')
reply = shell.get_msg(timeout=2)
for tst in validate_message(reply, 'object_info_reply', msg_id):
yield tst
content = reply['content']
yield nt.assert_false(content['found'])
@dec.parametric
def test_complete():
flush_channels()
shell = KM.shell_channel
msg_id, reply = execute(code="alpha = albert = 5")
msg_id = shell.complete('al', 'al', 2)
reply = shell.get_msg(timeout=2)
for tst in validate_message(reply, 'complete_reply', msg_id):
yield tst
matches = reply['content']['matches']
for name in ('alpha', 'albert'):
yield nt.assert_true(name in matches, "Missing match: %r" % name)
# IOPub channel
@dec.parametric
def test_stream():
flush_channels()
msg_id, reply = execute("print('hi')")
stdout = KM.sub_channel.get_msg(timeout=2)
for tst in validate_message(stdout, 'stream', msg_id):
yield tst
content = stdout['content']
yield nt.assert_equals(content['name'], u'stdout')
yield nt.assert_equals(content['data'], u'hi\n')
@dec.parametric
def test_display_data():
flush_channels()
msg_id, reply = execute("from IPython.core.display import display; display(1)")
display = KM.sub_channel.get_msg(timeout=2)
for tst in validate_message(display, 'display_data', parent=msg_id):
yield tst
data = display['content']['data']
yield nt.assert_equals(data['text/plain'], u'1')
|