def test_abspath_file_completions():
ip = get_ipython()
with TemporaryDirectory() as tmpdir:
prefix = os.path.join(tmpdir, 'foo')
suffixes = ['1', '2']
names = [prefix+s for s in suffixes]
for n in names:
open(n, 'w').close()
# Check simple completion
c = ip.complete(prefix)[1]
nt.assert_equal(c, names)
# Now check with a function call
cmd = 'a = f("%s' % prefix
c = ip.complete(prefix, cmd)[1]
comp = [prefix+s for s in suffixes]
nt.assert_equal(c, comp)
python类assert_equal()的实例源码
def test_local_file_completions():
ip = get_ipython()
with TemporaryWorkingDirectory():
prefix = './foo'
suffixes = ['1', '2']
names = [prefix+s for s in suffixes]
for n in names:
open(n, 'w').close()
# Check simple completion
c = ip.complete(prefix)[1]
nt.assert_equal(c, names)
# Now check with a function call
cmd = 'a = f("%s' % prefix
c = ip.complete(prefix, cmd)[1]
comp = set(prefix+s for s in suffixes)
nt.assert_true(comp.issubset(set(c)))
def test_magic_completion_shadowing():
ip = get_ipython()
c = ip.Completer
# Before importing matplotlib, %matplotlib magic should be the only option.
text, matches = c.complete("mat")
nt.assert_equal(matches, ["%matplotlib"])
# The newly introduced name should shadow the magic.
ip.run_cell("matplotlib = 1")
text, matches = c.complete("mat")
nt.assert_equal(matches, ["matplotlib"])
# After removing matplotlib from namespace, the magic should again be
# the only option.
del ip.user_ns["matplotlib"]
text, matches = c.complete("mat")
nt.assert_equal(matches, ["%matplotlib"])
def test_paste_echo(self):
"Also test self.paste echoing, by temporarily faking the writer"
w = StringIO()
writer = ip.write
ip.write = w.write
code = """
a = 100
b = 200"""
try:
self.paste(code,'')
out = w.getvalue()
finally:
ip.write = writer
nt.assert_equal(ip.user_ns['a'], 100)
nt.assert_equal(ip.user_ns['b'], 200)
nt.assert_equal(out, code+"\n## -- End pasted text --\n")
def test_select_figure_formats_kwargs():
ip = get_ipython()
kwargs = dict(quality=10, bbox_inches='tight')
pt.select_figure_formats(ip, 'png', **kwargs)
formatter = ip.display_formatter.formatters['image/png']
f = formatter.lookup_by_type(Figure)
cell = f.__closure__[0].cell_contents
nt.assert_equal(cell, kwargs)
# check that the formatter doesn't raise
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.plot([1,2,3])
plt.draw()
formatter.enabled = True
png = formatter(fig)
assert png.startswith(_PNG)
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_getdoc():
class A(object):
"""standard docstring"""
pass
class B(object):
"""standard docstring"""
def getdoc(self):
return "custom docstring"
class C(object):
"""standard docstring"""
def getdoc(self):
return None
a = A()
b = B()
c = C()
nt.assert_equal(oinspect.getdoc(a), "standard docstring")
nt.assert_equal(oinspect.getdoc(b), "custom docstring")
nt.assert_equal(oinspect.getdoc(c), "standard docstring")
def test_property_docstring_is_in_info_for_detail_level_0():
class A(object):
@property
def foobar(self):
"""This is `foobar` property."""
pass
ip.user_ns['a_obj'] = A()
nt.assert_equal(
'This is `foobar` property.',
ip.object_inspect('a_obj.foobar', detail_level=0)['docstring'])
ip.user_ns['a_cls'] = A
nt.assert_equal(
'This is `foobar` property.',
ip.object_inspect('a_cls.foobar', detail_level=0)['docstring'])
def test_ofind_slotted_attributes(self):
class A(object):
__slots__ = ['foo']
def __init__(self):
self.foo = 'bar'
a = A()
found = ip._ofind('a.foo', [('locals', locals())])
info = dict(found=True, isalias=False, ismagic=False,
namespace='locals', obj=a.foo, parent=a)
nt.assert_equal(found, info)
found = ip._ofind('a.bar', [('locals', locals())])
info = dict(found=False, isalias=False, ismagic=False,
namespace=None, obj=None, parent=a)
nt.assert_equal(found, info)
def test_user_expression():
# enable all formatters
ip.display_formatter.active_types = ip.display_formatter.format_types
query = {
'a' : '1 + 2',
'b' : '1/0',
}
r = ip.user_expressions(query)
import pprint
pprint.pprint(r)
nt.assert_equal(set(r.keys()), set(query.keys()))
a = r['a']
nt.assert_equal({'status', 'data', 'metadata'}, set(a.keys()))
nt.assert_equal(a['status'], 'ok')
data = a['data']
metadata = a['metadata']
nt.assert_equal(data.get('text/plain'), '3')
b = r['b']
nt.assert_equal(b['status'], 'error')
nt.assert_equal(b['ename'], 'ZeroDivisionError')
# back to text only
ip.display_formatter.active_types = ['text/plain']
def test_histmanager_disabled():
"""Ensure that disabling the history manager doesn't create a database."""
cfg = Config()
cfg.HistoryAccessor.enabled = False
ip = get_ipython()
with TemporaryDirectory() as tmpdir:
hist_manager_ori = ip.history_manager
hist_file = os.path.join(tmpdir, 'history.sqlite')
cfg.HistoryManager.hist_file = hist_file
try:
ip.history_manager = HistoryManager(shell=ip, config=cfg)
hist = [u'a=1', u'def f():\n test = 1\n return test', u"b='€Æ¾÷ß'"]
for i, h in enumerate(hist, start=1):
ip.history_manager.store_inputs(i, h)
nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
ip.history_manager.reset()
ip.history_manager.end_session()
finally:
ip.history_manager = hist_manager_ori
# hist_file should not be created
nt.assert_false(os.path.exists(hist_file))
def test_tb_syntaxerror():
"""test %tb after a SyntaxError"""
ip = get_ipython()
ip.run_cell("for")
# trap and validate stdout
save_stdout = sys.stdout
try:
sys.stdout = StringIO()
ip.run_cell("%tb")
out = sys.stdout.getvalue()
finally:
sys.stdout = save_stdout
# trim output, and only check the last line
last_line = out.rstrip().splitlines()[-1].strip()
nt.assert_equal(last_line, "SyntaxError: invalid syntax")
def test_dirops():
"""Test various directory handling operations."""
# curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
curpath = os.getcwd
startdir = os.getcwd()
ipdir = os.path.realpath(_ip.ipython_dir)
try:
_ip.magic('cd "%s"' % ipdir)
nt.assert_equal(curpath(), ipdir)
_ip.magic('cd -')
nt.assert_equal(curpath(), startdir)
_ip.magic('pushd "%s"' % ipdir)
nt.assert_equal(curpath(), ipdir)
_ip.magic('popd')
nt.assert_equal(curpath(), startdir)
finally:
os.chdir(startdir)
def test_xdel(self):
"""Test that references from %run are cleared by xdel."""
src = ("class A(object):\n"
" monitor = []\n"
" def __del__(self):\n"
" self.monitor.append(1)\n"
"a = A()\n")
self.mktmp(src)
# %run creates some hidden references...
_ip.magic("run %s" % self.fname)
# ... as does the displayhook.
_ip.run_cell("a")
monitor = _ip.user_ns["A"].monitor
nt.assert_equal(monitor, [])
_ip.magic("xdel a")
# Check that a's __del__ method has been called.
nt.assert_equal(monitor, [1])
def test_line_cell_info():
"""%%foo and %foo magics are distinguishable to inspect"""
ip = get_ipython()
ip.magics_manager.register(FooFoo)
oinfo = ip.object_inspect('foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
oinfo = ip.object_inspect('%%foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
oinfo = ip.object_inspect('%foo')
nt.assert_true(oinfo['found'])
nt.assert_true(oinfo['ismagic'])
nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)