##// END OF EJS Templates
Reset the interactive namespace __warningregistry__ before executing code...
Reset the interactive namespace __warningregistry__ before executing code Fixes #6611. Idea: Right now, people often don't see important warnings when running code in IPython, because (to a first approximation) any given warning will only issue once per session. Blink and you'll miss it! This is a very common contributor to confused emails to numpy-discussion. E.g.: In [5]: 1 / my_array_with_random_contents /home/njs/.user-python2.7-64bit-3/bin/ipython:1: RuntimeWarning: divide by zero encountered in divide #!/home/njs/.user-python2.7-64bit-3/bin/python Out[5]: array([ 1.77073316, -2.29765021, -2.01800811, ..., 1.13871243, -1.08302964, -8.6185091 ]) Oo, right, guess I gotta be careful of those zeros -- thanks, numpy, for giving me that warning! A few days later: In [592]: 1 / some_other_array Out[592]: array([ 3.07735763, 0.50769289, 0.83984078, ..., -0.67563917, -0.85736257, -1.36511271]) Oops, it turns out that this array had a zero in it too, and that's going to bite me later. But no warning this time! The effect of this commit is to make it so that warnings triggered by the code in cell 5 do *not* suppress warnings triggered by the code in cell 592. Note that this only applies to warnings triggered *directly* by code entered interactively -- if somepkg.foo() calls anotherpkg.bad_func() which issues a warning, then this warning will still only be displayed once, even if multiple cells call somepkg.foo(). But if cell 5 and cell 592 both call anotherpkg.bad_func() directly, then both will get warnings. (Important exception: if foo() is defined *interactively*, and calls anotherpkg.bad_func(), then every cell that calls foo() will display the warning again. This is unavoidable without fixes to CPython upstream.) Explanation: Python's warning system has some weird quirks. By default, it tries to suppress duplicate warnings, where "duplicate" means the same warning message triggered twice by the same line of code. This requires determining which line of code is responsible for triggering a warning, and this is controlled by the stacklevel= argument to warnings.warn. Basically, though, the idea is that if foo() calls bar() which calls baz() which calls some_deprecated_api(), then baz() will get counted as being "responsible", and the warning system will make a note that the usage of some_deprecated_api() inside baz() has already been warned about and doesn't need to be warned about again. So far so good. To accomplish this, obviously, there has to be a record of somewhere which line this was. You might think that this would be done by recording the filename:linenumber pair in a dict inside the warnings module, or something like that. You would be wrong. What actually happens is that the warnings module will use stack introspection to reach into baz()'s execution environment, create a global (module-level) variable there named __warningregistry__, and then, inside this dictionary, record just the line number. Basically, it assumes that any given module contains only one line 1, only one line 2, etc., so storing the filename is irrelevant. Obviously for interactive code this is totally wrong -- all cells share the same execution environment and global namespace, and they all contain a new line 1. Currently the warnings module treats these as if they were all the same line. In fact they are not the same line; once we have executed a given chunk of code, we will never see those particular lines again. As soon as a given chunk of code finishes executing, its line number labels become meaningless, and the corresponding warning registry entries become meaningless as well. Therefore, with this patch we delete the __warningregistry__ each time we execute a new block of code.

File last commit:

r16766:a7d1875e
r18548:61431d7d
Show More
test_session.py
318 lines | 12.4 KiB | text/x-python | PythonLexer
MinRK
zmq kernels now started via newapp
r3970 """test building messages with streamsession"""
#-------------------------------------------------------------------------------
# Copyright (C) 2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Imports
#-------------------------------------------------------------------------------
import os
import uuid
MinRK
test date time treatment in Session...
r13523 from datetime import datetime
MinRK
zmq kernels now started via newapp
r3970 import zmq
from zmq.tests import BaseZMQTestCase
from zmq.eventloop.zmqstream import ZMQStream
MinRK
merge IPython.parallel.streamsession into IPython.zmq.session...
r4006
MinRK
mv IPython.zmq to IPython.kernel.zmq
r9372 from IPython.kernel.zmq import session as ss
MinRK
zmq kernels now started via newapp
r3970
MinRK
test date time treatment in Session...
r13523 from IPython.testing.decorators import skipif, module_not_available
from IPython.utils.py3compat import string_types
from IPython.utils import jsonutil
MinRK
test invalid Session pack and unpack
r12773 def _bad_packer(obj):
raise TypeError("I don't work")
def _bad_unpacker(bytes):
raise TypeError("I don't work either")
MinRK
zmq kernels now started via newapp
r3970 class SessionTestCase(BaseZMQTestCase):
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
zmq kernels now started via newapp
r3970 def setUp(self):
BaseZMQTestCase.setUp(self)
MinRK
merge IPython.parallel.streamsession into IPython.zmq.session...
r4006 self.session = ss.Session()
MinRK
zmq kernels now started via newapp
r3970
Brian E. Granger
More tests for Session.send/recv.
r4234
MinRK
zmq kernels now started via newapp
r3970 class TestSession(SessionTestCase):
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
zmq kernels now started via newapp
r3970 def test_msg(self):
"""message format"""
msg = self.session.msg('execute')
Jason Grout
Make top-level metadata dictionary not optional.
r7955 thekeys = set('header parent_header metadata content msg_type msg_id'.split())
MinRK
zmq kernels now started via newapp
r3970 s = set(msg.keys())
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(s, thekeys)
MinRK
zmq kernels now started via newapp
r3970 self.assertTrue(isinstance(msg['content'],dict))
Jason Grout
Make top-level metadata dictionary not optional.
r7955 self.assertTrue(isinstance(msg['metadata'],dict))
MinRK
zmq kernels now started via newapp
r3970 self.assertTrue(isinstance(msg['header'],dict))
self.assertTrue(isinstance(msg['parent_header'],dict))
MinRK
restore msg_id/msg_type aliases in top level of msg dict...
r4711 self.assertTrue(isinstance(msg['msg_id'],str))
self.assertTrue(isinstance(msg['msg_type'],str))
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(msg['header']['msg_type'], 'execute')
self.assertEqual(msg['msg_type'], 'execute')
Brian E. Granger
Adding tests for zmq.session.
r4233
def test_serialize(self):
MinRK
avoid jsonlib returning Decimal...
r6060 msg = self.session.msg('execute', content=dict(a=10, b=1.1))
Brian E. Granger
Adding tests for zmq.session.
r4233 msg_list = self.session.serialize(msg, ident=b'foo')
ident, msg_list = self.session.feed_identities(msg_list)
new_msg = self.session.unserialize(msg_list)
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(ident[0], b'foo')
self.assertEqual(new_msg['msg_id'],msg['msg_id'])
self.assertEqual(new_msg['msg_type'],msg['msg_type'])
self.assertEqual(new_msg['header'],msg['header'])
self.assertEqual(new_msg['content'],msg['content'])
self.assertEqual(new_msg['parent_header'],msg['parent_header'])
Jason Grout
Make top-level metadata dictionary not optional.
r7955 self.assertEqual(new_msg['metadata'],msg['metadata'])
MinRK
avoid jsonlib returning Decimal...
r6060 # ensure floats don't come out as Decimal:
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(type(new_msg['content']['b']),type(new_msg['content']['b']))
Brian E. Granger
Adding tests for zmq.session.
r4233
Brian E. Granger
More tests for Session.send/recv.
r4234 def test_send(self):
MinRK
remove MockSocket in test_session...
r9340 ctx = zmq.Context.instance()
A = ctx.socket(zmq.PAIR)
B = ctx.socket(zmq.PAIR)
A.bind("inproc://test")
B.connect("inproc://test")
Brian E. Granger
More tests for Session.send/recv.
r4234
msg = self.session.msg('execute', content=dict(a=10))
MinRK
remove MockSocket in test_session...
r9340 self.session.send(A, msg, ident=b'foo', buffers=[b'bar'])
ident, msg_list = self.session.feed_identities(B.recv_multipart())
Brian E. Granger
More tests for Session.send/recv.
r4234 new_msg = self.session.unserialize(msg_list)
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(ident[0], b'foo')
self.assertEqual(new_msg['msg_id'],msg['msg_id'])
self.assertEqual(new_msg['msg_type'],msg['msg_type'])
self.assertEqual(new_msg['header'],msg['header'])
self.assertEqual(new_msg['content'],msg['content'])
self.assertEqual(new_msg['parent_header'],msg['parent_header'])
Jason Grout
Make top-level metadata dictionary not optional.
r7955 self.assertEqual(new_msg['metadata'],msg['metadata'])
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(new_msg['buffers'],[b'bar'])
Brian E. Granger
More tests for Session.send/recv.
r4234
content = msg['content']
header = msg['header']
parent = msg['parent_header']
Jason Grout
Make top-level metadata dictionary not optional.
r7955 metadata = msg['metadata']
Brian E. Granger
More tests for Session.send/recv.
r4234 msg_type = header['msg_type']
MinRK
remove MockSocket in test_session...
r9340 self.session.send(A, None, content=content, parent=parent,
Jason Grout
Make top-level metadata dictionary not optional.
r7955 header=header, metadata=metadata, ident=b'foo', buffers=[b'bar'])
MinRK
remove MockSocket in test_session...
r9340 ident, msg_list = self.session.feed_identities(B.recv_multipart())
Brian E. Granger
More tests for Session.send/recv.
r4234 new_msg = self.session.unserialize(msg_list)
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(ident[0], b'foo')
self.assertEqual(new_msg['msg_id'],msg['msg_id'])
self.assertEqual(new_msg['msg_type'],msg['msg_type'])
self.assertEqual(new_msg['header'],msg['header'])
self.assertEqual(new_msg['content'],msg['content'])
Jason Grout
Make top-level metadata dictionary not optional.
r7955 self.assertEqual(new_msg['metadata'],msg['metadata'])
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(new_msg['parent_header'],msg['parent_header'])
self.assertEqual(new_msg['buffers'],[b'bar'])
Brian E. Granger
More tests for Session.send/recv.
r4234
MinRK
remove MockSocket in test_session...
r9340 self.session.send(A, msg, ident=b'foo', buffers=[b'bar'])
ident, new_msg = self.session.recv(B)
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(ident[0], b'foo')
self.assertEqual(new_msg['msg_id'],msg['msg_id'])
self.assertEqual(new_msg['msg_type'],msg['msg_type'])
self.assertEqual(new_msg['header'],msg['header'])
self.assertEqual(new_msg['content'],msg['content'])
Jason Grout
Make top-level metadata dictionary not optional.
r7955 self.assertEqual(new_msg['metadata'],msg['metadata'])
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(new_msg['parent_header'],msg['parent_header'])
self.assertEqual(new_msg['buffers'],[b'bar'])
Brian E. Granger
More tests for Session.send/recv.
r4234
MinRK
remove MockSocket in test_session...
r9340 A.close()
B.close()
ctx.term()
Brian E. Granger
More tests for Session.send/recv.
r4234
MinRK
zmq kernels now started via newapp
r3970 def test_args(self):
MinRK
merge IPython.parallel.streamsession into IPython.zmq.session...
r4006 """initialization arguments for Session"""
MinRK
zmq kernels now started via newapp
r3970 s = self.session
self.assertTrue(s.pack is ss.default_packer)
self.assertTrue(s.unpack is ss.default_unpacker)
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(s.username, os.environ.get('USER', u'username'))
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
merge IPython.parallel.streamsession into IPython.zmq.session...
r4006 s = ss.Session()
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(s.username, os.environ.get('USER', u'username'))
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
merge IPython.parallel.streamsession into IPython.zmq.session...
r4006 self.assertRaises(TypeError, ss.Session, pack='hi')
self.assertRaises(TypeError, ss.Session, unpack='hi')
MinRK
zmq kernels now started via newapp
r3970 u = str(uuid.uuid4())
Brian E. Granger
More tests for Session.send/recv.
r4234 s = ss.Session(username=u'carrot', session=u)
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(s.session, u)
self.assertEqual(s.username, u'carrot')
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
zmq kernels now started via newapp
r3970 def test_tracking(self):
"""test tracking messages"""
a,b = self.create_bound_pair(zmq.PAIR, zmq.PAIR)
s = self.session
MinRK
fix inverted copy-threshold
r7973 s.copy_threshold = 1
MinRK
zmq kernels now started via newapp
r3970 stream = ZMQStream(a)
msg = s.send(a, 'hello', track=False)
MinRK
tweak non-tracking session test
r7974 self.assertTrue(msg['tracker'] is ss.DONE)
MinRK
zmq kernels now started via newapp
r3970 msg = s.send(a, 'hello', track=True)
self.assertTrue(isinstance(msg['tracker'], zmq.MessageTracker))
M = zmq.Message(b'hi there', track=True)
msg = s.send(a, 'hello', buffers=[M], track=True)
t = msg['tracker']
self.assertTrue(isinstance(t, zmq.MessageTracker))
self.assertRaises(zmq.NotDone, t.wait, .1)
del M
t.wait(1) # this will raise
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
zmq kernels now started via newapp
r3970 def test_unique_msg_ids(self):
"""test that messages receive unique ids"""
ids = set()
for i in range(2**12):
h = self.session.msg_header('test')
msg_id = h['msg_id']
self.assertTrue(msg_id not in ids)
ids.add(msg_id)
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
zmq kernels now started via newapp
r3970 def test_feed_identities(self):
"""scrub the front for zmq IDENTITIES"""
theids = "engine client other".split()
content = dict(code='whoda',stuff=object())
themsg = self.session.msg('execute',content=content)
pmsg = theids
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
add Session.bsession trait for session id as bytes
r4770 def test_session_id(self):
session = ss.Session()
# get bs before us
bs = session.bsession
us = session.session
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(us.encode('ascii'), bs)
MinRK
add Session.bsession trait for session id as bytes
r4770 session = ss.Session()
# get us before bs
us = session.session
bs = session.bsession
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(us.encode('ascii'), bs)
MinRK
add Session.bsession trait for session id as bytes
r4770 # change propagates:
session.session = 'something else'
bs = session.bsession
us = session.session
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(us.encode('ascii'), bs)
MinRK
add Session.bsession trait for session id as bytes
r4770 session = ss.Session(session='stuff')
# get us before bs
Bradley M. Froehle
s/assertEquals/assertEqual/
r7874 self.assertEqual(session.bsession, session.session.encode('ascii'))
self.assertEqual(b'stuff', session.bsession)
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
cull Session digest history...
r10811 def test_zero_digest_history(self):
session = ss.Session(digest_history_size=0)
for i in range(11):
session._add_digest(uuid.uuid4().bytes)
self.assertEqual(len(session.digest_history), 0)
def test_cull_digest_history(self):
session = ss.Session(digest_history_size=100)
for i in range(100):
session._add_digest(uuid.uuid4().bytes)
self.assertTrue(len(session.digest_history) == 100)
session._add_digest(uuid.uuid4().bytes)
self.assertTrue(len(session.digest_history) == 91)
for i in range(9):
session._add_digest(uuid.uuid4().bytes)
self.assertTrue(len(session.digest_history) == 100)
session._add_digest(uuid.uuid4().bytes)
self.assertTrue(len(session.digest_history) == 91)
MinRK
test invalid Session pack and unpack
r12773
def test_bad_pack(self):
try:
session = ss.Session(pack=_bad_packer)
except ValueError as e:
self.assertIn("could not serialize", str(e))
self.assertIn("don't work", str(e))
else:
self.fail("Should have raised ValueError")
def test_bad_unpack(self):
try:
session = ss.Session(unpack=_bad_unpacker)
except ValueError as e:
self.assertIn("could not handle output", str(e))
self.assertIn("don't work either", str(e))
else:
self.fail("Should have raised ValueError")
def test_bad_packer(self):
try:
session = ss.Session(packer=__name__ + '._bad_packer')
except ValueError as e:
self.assertIn("could not serialize", str(e))
self.assertIn("don't work", str(e))
else:
self.fail("Should have raised ValueError")
def test_bad_unpacker(self):
try:
session = ss.Session(unpacker=__name__ + '._bad_unpacker')
except ValueError as e:
self.assertIn("could not handle output", str(e))
self.assertIn("don't work either", str(e))
else:
self.fail("Should have raised ValueError")
def test_bad_roundtrip(self):
with self.assertRaises(ValueError):
MinRK
test date time treatment in Session...
r13523 session = ss.Session(unpack=lambda b: 5)
def _datetime_test(self, session):
content = dict(t=datetime.now())
metadata = dict(t=datetime.now())
p = session.msg('msg')
msg = session.msg('msg', content=content, metadata=metadata, parent=p['header'])
smsg = session.serialize(msg)
msg2 = session.unserialize(session.feed_identities(smsg)[1])
assert isinstance(msg2['header']['date'], datetime)
self.assertEqual(msg['header'], msg2['header'])
self.assertEqual(msg['parent_header'], msg2['parent_header'])
self.assertEqual(msg['parent_header'], msg2['parent_header'])
assert isinstance(msg['content']['t'], datetime)
assert isinstance(msg['metadata']['t'], datetime)
assert isinstance(msg2['content']['t'], string_types)
assert isinstance(msg2['metadata']['t'], string_types)
self.assertEqual(msg['content'], jsonutil.extract_dates(msg2['content']))
self.assertEqual(msg['content'], jsonutil.extract_dates(msg2['content']))
def test_datetimes(self):
self._datetime_test(self.session)
def test_datetimes_pickle(self):
session = ss.Session(packer='pickle')
self._datetime_test(session)
@skipif(module_not_available('msgpack'))
def test_datetimes_msgpack(self):
MinRK
specify encoding in msgpack.unpackb...
r16766 import msgpack
session = ss.Session(
pack=msgpack.packb,
unpack=lambda buf: msgpack.unpackb(buf, encoding='utf8'),
)
MinRK
test date time treatment in Session...
r13523 self._datetime_test(session)
MinRK
test invalid Session pack and unpack
r12773
Doug Blank
Added test_send_raw() for issue #4839, see pull request 4840
r14643 def test_send_raw(self):
ctx = zmq.Context.instance()
A = ctx.socket(zmq.PAIR)
B = ctx.socket(zmq.PAIR)
A.bind("inproc://test")
B.connect("inproc://test")
msg = self.session.msg('execute', content=dict(a=10))
msg_list = [self.session.pack(msg[part]) for part in
['header', 'parent_header', 'metadata', 'content']]
self.session.send_raw(A, msg_list, ident=b'foo')
ident, new_msg_list = self.session.feed_identities(B.recv_multipart())
new_msg = self.session.unserialize(new_msg_list)
self.assertEqual(ident[0], b'foo')
self.assertEqual(new_msg['msg_type'],msg['msg_type'])
self.assertEqual(new_msg['header'],msg['header'])
self.assertEqual(new_msg['parent_header'],msg['parent_header'])
self.assertEqual(new_msg['content'],msg['content'])
self.assertEqual(new_msg['metadata'],msg['metadata'])
A.close()
B.close()
ctx.term()