##// 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:

r15343:2790d687
r18548:61431d7d
Show More
test_nbextensions.py
272 lines | 9.5 KiB | text/x-python | PythonLexer
# coding: utf-8
"""Test installation of notebook extensions"""
#-----------------------------------------------------------------------------
# Copyright (C) 2014 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 glob
import os
import re
import tarfile
import zipfile
from io import BytesIO
from os.path import basename, join as pjoin
from unittest import TestCase
import IPython.testing.tools as tt
import IPython.testing.decorators as dec
from IPython.utils import py3compat
from IPython.utils.tempdir import TemporaryDirectory
from IPython.html import nbextensions
from IPython.html.nbextensions import install_nbextension, check_nbextension
#-----------------------------------------------------------------------------
# Test functions
#-----------------------------------------------------------------------------
def touch(file, mtime=None):
"""ensure a file exists, and set its modification time
returns the modification time of the file
"""
open(file, 'a').close()
# set explicit mtime
if mtime:
atime = os.stat(file).st_atime
os.utime(file, (atime, mtime))
return os.stat(file).st_mtime
class TestInstallNBExtension(TestCase):
def tempdir(self):
td = TemporaryDirectory()
self.tempdirs.append(td)
return py3compat.cast_unicode(td.name)
def setUp(self):
self.tempdirs = []
src = self.src = self.tempdir()
self.files = files = [
pjoin(u'ƒile'),
pjoin(u'∂ir', u'ƒile1'),
pjoin(u'∂ir', u'∂ir2', u'ƒile2'),
]
for file in files:
fullpath = os.path.join(self.src, file)
parent = os.path.dirname(fullpath)
if not os.path.exists(parent):
os.makedirs(parent)
touch(fullpath)
self.ipdir = self.tempdir()
self.save_get_ipython_dir = nbextensions.get_ipython_dir
nbextensions.get_ipython_dir = lambda : self.ipdir
def tearDown(self):
for td in self.tempdirs:
td.cleanup()
nbextensions.get_ipython_dir = self.save_get_ipython_dir
def assert_path_exists(self, path):
if not os.path.exists(path):
do_exist = os.listdir(os.path.dirname(path))
self.fail(u"%s should exist (found %s)" % (path, do_exist))
def assert_not_path_exists(self, path):
if os.path.exists(path):
self.fail(u"%s should not exist" % path)
def assert_installed(self, relative_path, ipdir=None):
self.assert_path_exists(
pjoin(ipdir or self.ipdir, u'nbextensions', relative_path)
)
def assert_not_installed(self, relative_path, ipdir=None):
self.assert_not_path_exists(
pjoin(ipdir or self.ipdir, u'nbextensions', relative_path)
)
def test_create_ipython_dir(self):
"""install_nbextension when ipython_dir doesn't exist"""
with TemporaryDirectory() as td:
ipdir = pjoin(td, u'ipython')
install_nbextension(self.src, ipython_dir=ipdir)
self.assert_path_exists(ipdir)
for file in self.files:
self.assert_installed(
pjoin(basename(self.src), file),
ipdir
)
def test_create_nbextensions(self):
with TemporaryDirectory() as ipdir:
install_nbextension(self.src, ipython_dir=ipdir)
self.assert_installed(
pjoin(basename(self.src), u'ƒile'),
ipdir
)
def test_single_file(self):
file = self.files[0]
install_nbextension(pjoin(self.src, file))
self.assert_installed(file)
def test_single_dir(self):
d = u'∂ir'
install_nbextension(pjoin(self.src, d))
self.assert_installed(self.files[-1])
def test_install_nbextension(self):
install_nbextension(glob.glob(pjoin(self.src, '*')))
for file in self.files:
self.assert_installed(file)
def test_overwrite_file(self):
with TemporaryDirectory() as d:
fname = u'ƒ.js'
src = pjoin(d, fname)
with open(src, 'w') as f:
f.write('first')
mtime = touch(src)
dest = pjoin(self.ipdir, u'nbextensions', fname)
install_nbextension(src)
with open(src, 'w') as f:
f.write('overwrite')
mtime = touch(src, mtime - 100)
install_nbextension(src, overwrite=True)
with open(dest) as f:
self.assertEqual(f.read(), 'overwrite')
def test_overwrite_dir(self):
with TemporaryDirectory() as src:
# src = py3compat.cast_unicode_py2(src)
base = basename(src)
fname = u'ƒ.js'
touch(pjoin(src, fname))
install_nbextension(src)
self.assert_installed(pjoin(base, fname))
os.remove(pjoin(src, fname))
fname2 = u'∂.js'
touch(pjoin(src, fname2))
install_nbextension(src, overwrite=True)
self.assert_installed(pjoin(base, fname2))
self.assert_not_installed(pjoin(base, fname))
def test_update_file(self):
with TemporaryDirectory() as d:
fname = u'ƒ.js'
src = pjoin(d, fname)
with open(src, 'w') as f:
f.write('first')
mtime = touch(src)
install_nbextension(src)
self.assert_installed(fname)
dest = pjoin(self.ipdir, u'nbextensions', fname)
old_mtime = os.stat(dest).st_mtime
with open(src, 'w') as f:
f.write('overwrite')
touch(src, mtime + 10)
install_nbextension(src)
with open(dest) as f:
self.assertEqual(f.read(), 'overwrite')
def test_skip_old_file(self):
with TemporaryDirectory() as d:
fname = u'ƒ.js'
src = pjoin(d, fname)
mtime = touch(src)
install_nbextension(src)
self.assert_installed(fname)
dest = pjoin(self.ipdir, u'nbextensions', fname)
old_mtime = os.stat(dest).st_mtime
mtime = touch(src, mtime - 100)
install_nbextension(src)
new_mtime = os.stat(dest).st_mtime
self.assertEqual(new_mtime, old_mtime)
def test_quiet(self):
with tt.AssertNotPrints(re.compile(r'.+')):
install_nbextension(self.src, verbose=0)
def test_install_zip(self):
path = pjoin(self.src, "myjsext.zip")
with zipfile.ZipFile(path, 'w') as f:
f.writestr("a.js", b"b();")
f.writestr("foo/a.js", b"foo();")
install_nbextension(path)
self.assert_installed("a.js")
self.assert_installed(pjoin("foo", "a.js"))
def test_install_tar(self):
def _add_file(f, fname, buf):
info = tarfile.TarInfo(fname)
info.size = len(buf)
f.addfile(info, BytesIO(buf))
for i,ext in enumerate((".tar.gz", ".tgz", ".tar.bz2")):
path = pjoin(self.src, "myjsext" + ext)
with tarfile.open(path, 'w') as f:
_add_file(f, "b%i.js" % i, b"b();")
_add_file(f, "foo/b%i.js" % i, b"foo();")
install_nbextension(path)
self.assert_installed("b%i.js" % i)
self.assert_installed(pjoin("foo", "b%i.js" % i))
def test_install_url(self):
def fake_urlretrieve(url, dest):
touch(dest)
save_urlretrieve = nbextensions.urlretrieve
nbextensions.urlretrieve = fake_urlretrieve
try:
install_nbextension("http://example.com/path/to/foo.js")
self.assert_installed("foo.js")
install_nbextension("https://example.com/path/to/another/bar.js")
self.assert_installed("bar.js")
finally:
nbextensions.urlretrieve = save_urlretrieve
def test_check_nbextension(self):
with TemporaryDirectory() as d:
f = u'ƒ.js'
src = pjoin(d, f)
touch(src)
install_nbextension(src)
assert check_nbextension(f, self.ipdir)
assert check_nbextension([f], self.ipdir)
assert not check_nbextension([f, pjoin('dne', f)], self.ipdir)
@dec.skip_win32
def test_install_symlink(self):
with TemporaryDirectory() as d:
f = u'ƒ.js'
src = pjoin(d, f)
touch(src)
install_nbextension(src, symlink=True)
dest = pjoin(self.ipdir, u'nbextensions', f)
assert os.path.islink(dest)
link = os.readlink(dest)
self.assertEqual(link, src)
def test_install_symlink_bad(self):
with self.assertRaises(ValueError):
install_nbextension("http://example.com/foo.js", symlink=True)
with TemporaryDirectory() as d:
zf = u'ƒ.zip'
zsrc = pjoin(d, zf)
with zipfile.ZipFile(zsrc, 'w') as z:
z.writestr("a.js", b"b();")
with self.assertRaises(ValueError):
install_nbextension(zsrc, symlink=True)