def test_run_tb():
"""Test traceback offset in %run"""
with TemporaryDirectory() as td:
path = pjoin(td, 'foo.py')
with open(path, 'w') as f:
f.write('\n'.join([
"def foo():",
" return bar()",
"def bar():",
" raise RuntimeError('hello!')",
"foo()",
]))
with capture_output() as io:
_ip.magic('run {}'.format(path))
out = io.stdout
nt.assert_not_in("execfile", out)
nt.assert_in("RuntimeError", out)
nt.assert_equal(out.count("---->"), 3)
python类assert_not_in()的实例源码
def test_script_tb():
"""Test traceback offset in `ipython script.py`"""
with TemporaryDirectory() as td:
path = pjoin(td, 'foo.py')
with open(path, 'w') as f:
f.write('\n'.join([
"def foo():",
" return bar()",
"def bar():",
" raise RuntimeError('hello!')",
"foo()",
]))
out, err = tt.ipexec(path)
nt.assert_not_in("execfile", out)
nt.assert_in("RuntimeError", out)
nt.assert_equal(out.count("---->"), 3)
def test_line_cell_magics():
from IPython.core.magic import register_line_cell_magic
@register_line_cell_magic
def _bar_cellm(line, cell):
pass
ip = get_ipython()
c = ip.Completer
# The policy here is trickier, see comments in completion code. The
# returned values depend on whether the user passes %% or not explicitly,
# and this will show a difference if the same name is both a line and cell
# magic.
s, matches = c.complete(None, '_bar_ce')
nt.assert_in('%_bar_cellm', matches)
nt.assert_in('%%_bar_cellm', matches)
s, matches = c.complete(None, '%_bar_ce')
nt.assert_in('%_bar_cellm', matches)
nt.assert_in('%%_bar_cellm', matches)
s, matches = c.complete(None, '%%_bar_ce')
nt.assert_not_in('%_bar_cellm', matches)
nt.assert_in('%%_bar_cellm', matches)
def test_magic_color():
ip = get_ipython()
c = ip.Completer
s, matches = c.complete(None, 'colo')
nt.assert_in('%colors', matches)
s, matches = c.complete(None, 'colo')
nt.assert_not_in('NoColor', matches)
s, matches = c.complete(None, '%colors') # No trailing space
nt.assert_not_in('NoColor', matches)
s, matches = c.complete(None, 'colors ')
nt.assert_in('NoColor', matches)
s, matches = c.complete(None, '%colors ')
nt.assert_in('NoColor', matches)
s, matches = c.complete(None, 'colors NoCo')
nt.assert_list_equal(['NoColor'], matches)
s, matches = c.complete(None, '%colors NoCo')
nt.assert_list_equal(['NoColor'], matches)
def test_inline_twice(self):
"Using '%matplotlib inline' twice should not reset formatters"
ip = self.Shell()
gui, backend = ip.enable_matplotlib('inline')
nt.assert_equal(gui, 'inline')
fmts = {'png'}
active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
pt.select_figure_formats(ip, fmts)
gui, backend = ip.enable_matplotlib('inline')
nt.assert_equal(gui, 'inline')
for mime, f in ip.display_formatter.formatters.items():
if mime in active_mimes:
nt.assert_in(Figure, f)
else:
nt.assert_not_in(Figure, f)
def test_rehashx():
# clear up everything
_ip.alias_manager.clear_aliases()
del _ip.db['syscmdlist']
_ip.magic('rehashx')
# Practically ALL ipython development systems will have more than 10 aliases
nt.assert_true(len(_ip.alias_manager.aliases) > 10)
for name, cmd in _ip.alias_manager.aliases:
# we must strip dots from alias names
nt.assert_not_in('.', name)
# rehashx must fill up syscmdlist
scoms = _ip.db['syscmdlist']
nt.assert_true(len(scoms) > 10)
def test_alias_magic():
"""Test %alias_magic."""
ip = get_ipython()
mm = ip.magics_manager
# Basic operation: both cell and line magics are created, if possible.
ip.run_line_magic('alias_magic', 'timeit_alias timeit')
nt.assert_in('timeit_alias', mm.magics['line'])
nt.assert_in('timeit_alias', mm.magics['cell'])
# --cell is specified, line magic not created.
ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
nt.assert_in('timeit_cell_alias', mm.magics['cell'])
# Test that line alias is created successfully.
ip.run_line_magic('alias_magic', '--line env_alias env')
nt.assert_equal(ip.run_line_magic('env', ''),
ip.run_line_magic('env_alias', ''))
# Test that line alias with parameters passed in is created successfully.
ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
nt.assert_in('history_alias', mm.magics['line'])
def test_lookup_by_type_string():
f = PlainTextFormatter()
type_str = '%s.%s' % (C.__module__, 'C')
f.for_type(type_str, foo_printer)
# verify insertion
nt.assert_in(_mod_name_key(C), f.deferred_printers)
nt.assert_not_in(C, f.type_printers)
nt.assert_is(f.lookup_by_type(type_str), foo_printer)
# lookup by string doesn't cause import
nt.assert_in(_mod_name_key(C), f.deferred_printers)
nt.assert_not_in(C, f.type_printers)
nt.assert_is(f.lookup_by_type(C), foo_printer)
# should move from deferred to imported dict
nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
nt.assert_in(C, f.type_printers)
def test_video_embedding():
"""use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
v = display.Video("http://ignored")
assert not v.embed
html = v._repr_html_()
nt.assert_not_in('src="data:', html)
nt.assert_in('src="http://ignored"', html)
with nt.assert_raises(ValueError):
v = display.Video(b'abc')
with NamedFileInTemporaryDirectory('test.mp4') as f:
f.write(b'abc')
f.close()
v = display.Video(f.name)
assert not v.embed
html = v._repr_html_()
nt.assert_not_in('src="data:', html)
v = display.Video(f.name, embed=True)
html = v._repr_html_()
nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
v = display.Video(f.name, embed=True, mimetype='video/other')
html = v._repr_html_()
nt.assert_in('src="data:video/other;base64,YWJj"',html)
v = display.Video(b'abc', embed=True, mimetype='video/mp4')
html = v._repr_html_()
nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
html = v._repr_html_()
nt.assert_in('src="data:video/xyz;base64,YWJj"',html)
def test_magic_config():
ip = get_ipython()
c = ip.Completer
s, matches = c.complete(None, 'conf')
nt.assert_in('%config', matches)
s, matches = c.complete(None, 'conf')
nt.assert_not_in('AliasManager', matches)
s, matches = c.complete(None, 'config ')
nt.assert_in('AliasManager', matches)
s, matches = c.complete(None, '%config ')
nt.assert_in('AliasManager', matches)
s, matches = c.complete(None, 'config Ali')
nt.assert_list_equal(['AliasManager'], matches)
s, matches = c.complete(None, '%config Ali')
nt.assert_list_equal(['AliasManager'], matches)
s, matches = c.complete(None, 'config AliasManager')
nt.assert_list_equal(['AliasManager'], matches)
s, matches = c.complete(None, '%config AliasManager')
nt.assert_list_equal(['AliasManager'], matches)
s, matches = c.complete(None, 'config AliasManager.')
nt.assert_in('AliasManager.default_aliases', matches)
s, matches = c.complete(None, '%config AliasManager.')
nt.assert_in('AliasManager.default_aliases', matches)
s, matches = c.complete(None, 'config AliasManager.de')
nt.assert_list_equal(['AliasManager.default_aliases'], matches)
s, matches = c.complete(None, 'config AliasManager.de')
nt.assert_list_equal(['AliasManager.default_aliases'], matches)
def test_aimport_module_completer():
ip = get_ipython()
_, matches = ip.complete('i', '%aimport i')
nt.assert_in('io', matches)
nt.assert_not_in('int', matches)
def test_nested_import_module_completer():
ip = get_ipython()
_, matches = ip.complete(None, 'import IPython.co', 17)
nt.assert_in('IPython.core', matches)
nt.assert_not_in('import IPython.core', matches)
nt.assert_not_in('IPython.display', matches)
def test_import_module_completer():
ip = get_ipython()
_, matches = ip.complete('i', 'import i')
nt.assert_in('io', matches)
nt.assert_not_in('int', matches)
def test_from_module_completer():
ip = get_ipython()
_, matches = ip.complete('B', 'from io import B', 16)
nt.assert_in('BytesIO', matches)
nt.assert_not_in('BaseException', matches)
def test_select_figure_formats_str():
ip = get_ipython()
for fmt, active_mime in _fmt_mime_map.items():
pt.select_figure_formats(ip, fmt)
for mime, f in ip.display_formatter.formatters.items():
if mime == active_mime:
nt.assert_in(Figure, f)
else:
nt.assert_not_in(Figure, f)
def test_init_colors():
# ensure colors are not present in signature info
info = inspector.info(HasSignature)
init_def = info['init_definition']
nt.assert_not_in('[0m', init_def)
def test_unregistering(self):
err_transformer = ErrorTransformer()
ip.ast_transformers.append(err_transformer)
with tt.AssertPrints("unregister", channel='stderr'):
ip.run_cell("1 + 2")
# This should have been removed.
nt.assert_not_in(err_transformer, ip.ast_transformers)
def test_alias_lifecycle():
name = 'test_alias1'
cmd = 'echo "Hello"'
am = _ip.alias_manager
am.clear_aliases()
am.define_alias(name, cmd)
assert am.is_alias(name)
nt.assert_equal(am.retrieve_alias(name), cmd)
nt.assert_in((name, cmd), am.aliases)
# Test running the alias
orig_system = _ip.system
result = []
_ip.system = result.append
try:
_ip.run_cell('%{}'.format(name))
result = [c.strip() for c in result]
nt.assert_equal(result, [cmd])
finally:
_ip.system = orig_system
# Test removing the alias
am.undefine_alias(name)
assert not am.is_alias(name)
with nt.assert_raises(ValueError):
am.retrieve_alias(name)
nt.assert_not_in((name, cmd), am.aliases)
def test_for_type_string():
f = PlainTextFormatter()
type_str = '%s.%s' % (C.__module__, 'C')
# initial return, None
nt.assert_is(f.for_type(type_str, foo_printer), None)
# no func queries
nt.assert_is(f.for_type(type_str), foo_printer)
nt.assert_in(_mod_name_key(C), f.deferred_printers)
nt.assert_is(f.for_type(C), foo_printer)
nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
nt.assert_in(C, f.type_printers)
def test_lookup_string():
f = PlainTextFormatter()
type_str = '%s.%s' % (C.__module__, 'C')
f.for_type(type_str, foo_printer)
nt.assert_is(f.lookup(C()), foo_printer)
# should move from deferred to imported dict
nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
nt.assert_in(C, f.type_printers)