Uploaded Test files

This commit is contained in:
Batuhan Berk Başoğlu 2020-11-12 11:05:57 -05:00
parent f584ad9d97
commit 2e81cb7d99
16627 changed files with 2065359 additions and 102444 deletions

View file

@ -0,0 +1,159 @@
# encoding: utf-8
"""Tests for IPython.utils.capture"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 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 sys
import nose.tools as nt
from IPython.utils import capture
#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
_mime_map = dict(
_repr_png_="image/png",
_repr_jpeg_="image/jpeg",
_repr_svg_="image/svg+xml",
_repr_html_="text/html",
_repr_json_="application/json",
_repr_javascript_="application/javascript",
)
basic_data = {
'image/png' : b'binarydata',
'text/html' : "<b>bold</b>",
}
basic_metadata = {
'image/png' : {
'width' : 10,
'height' : 20,
},
}
full_data = {
'image/png' : b'binarydata',
'image/jpeg' : b'binarydata',
'image/svg+xml' : "<svg>",
'text/html' : "<b>bold</b>",
'application/javascript' : "alert();",
'application/json' : "{}",
}
full_metadata = {
'image/png' : {"png" : "exists"},
'image/jpeg' : {"jpeg" : "exists"},
'image/svg+xml' : {"svg" : "exists"},
'text/html' : {"html" : "exists"},
'application/javascript' : {"js" : "exists"},
'application/json' : {"json" : "exists"},
}
hello_stdout = "hello, stdout"
hello_stderr = "hello, stderr"
#-----------------------------------------------------------------------------
# Test Functions
#-----------------------------------------------------------------------------
def test_rich_output_empty():
"""RichOutput with no args"""
rich = capture.RichOutput()
for method, mime in _mime_map.items():
yield nt.assert_equal, getattr(rich, method)(), None
def test_rich_output():
"""test RichOutput basics"""
data = basic_data
metadata = basic_metadata
rich = capture.RichOutput(data=data, metadata=metadata)
yield nt.assert_equal, rich._repr_html_(), data['text/html']
yield nt.assert_equal, rich._repr_png_(), (data['image/png'], metadata['image/png'])
yield nt.assert_equal, rich._repr_latex_(), None
yield nt.assert_equal, rich._repr_javascript_(), None
yield nt.assert_equal, rich._repr_svg_(), None
def test_rich_output_no_metadata():
"""test RichOutput with no metadata"""
data = full_data
rich = capture.RichOutput(data=data)
for method, mime in _mime_map.items():
yield nt.assert_equal, getattr(rich, method)(), data[mime]
def test_rich_output_metadata():
"""test RichOutput with metadata"""
data = full_data
metadata = full_metadata
rich = capture.RichOutput(data=data, metadata=metadata)
for method, mime in _mime_map.items():
yield nt.assert_equal, getattr(rich, method)(), (data[mime], metadata[mime])
def test_rich_output_display():
"""test RichOutput.display
This is a bit circular, because we are actually using the capture code we are testing
to test itself.
"""
data = full_data
rich = capture.RichOutput(data=data)
with capture.capture_output() as cap:
rich.display()
yield nt.assert_equal, len(cap.outputs), 1
rich2 = cap.outputs[0]
yield nt.assert_equal, rich2.data, rich.data
yield nt.assert_equal, rich2.metadata, rich.metadata
def test_capture_output():
"""capture_output works"""
rich = capture.RichOutput(data=full_data)
with capture.capture_output() as cap:
print(hello_stdout, end="")
print(hello_stderr, end="", file=sys.stderr)
rich.display()
yield nt.assert_equal, hello_stdout, cap.stdout
yield nt.assert_equal, hello_stderr, cap.stderr
def test_capture_output_no_stdout():
"""test capture_output(stdout=False)"""
rich = capture.RichOutput(data=full_data)
with capture.capture_output(stdout=False) as cap:
print(hello_stdout, end="")
print(hello_stderr, end="", file=sys.stderr)
rich.display()
yield nt.assert_equal, "", cap.stdout
yield nt.assert_equal, hello_stderr, cap.stderr
yield nt.assert_equal, len(cap.outputs), 1
def test_capture_output_no_stderr():
"""test capture_output(stderr=False)"""
rich = capture.RichOutput(data=full_data)
# add nested capture_output so stderr doesn't make it to nose output
with capture.capture_output(), capture.capture_output(stderr=False) as cap:
print(hello_stdout, end="")
print(hello_stderr, end="", file=sys.stderr)
rich.display()
yield nt.assert_equal, hello_stdout, cap.stdout
yield nt.assert_equal, "", cap.stderr
yield nt.assert_equal, len(cap.outputs), 1
def test_capture_output_no_display():
"""test capture_output(display=False)"""
rich = capture.RichOutput(data=full_data)
with capture.capture_output(display=False) as cap:
print(hello_stdout, end="")
print(hello_stderr, end="", file=sys.stderr)
rich.display()
yield nt.assert_equal, hello_stdout, cap.stdout
yield nt.assert_equal, hello_stderr, cap.stderr
yield nt.assert_equal, cap.outputs, []

View file

@ -0,0 +1,10 @@
from IPython.utils import decorators
def test_flag_calls():
@decorators.flag_calls
def f():
pass
assert not f.called
f()
assert f.called

View file

@ -0,0 +1,58 @@
import nose.tools as nt
from IPython.utils.dir2 import dir2
class Base(object):
x = 1
z = 23
def test_base():
res = dir2(Base())
assert ('x' in res)
assert ('z' in res)
assert ('y' not in res)
assert ('__class__' in res)
nt.assert_equal(res.count('x'), 1)
nt.assert_equal(res.count('__class__'), 1)
def test_SubClass():
class SubClass(Base):
y = 2
res = dir2(SubClass())
assert ('y' in res)
nt.assert_equal(res.count('y'), 1)
nt.assert_equal(res.count('x'), 1)
def test_SubClass_with_trait_names_attr():
# usecase: trait_names is used in a class describing psychological classification
class SubClass(Base):
y = 2
trait_names = 44
res = dir2(SubClass())
assert('trait_names' in res)
def test_misbehaving_object_without_trait_names():
# dir2 shouldn't raise even when objects are dumb and raise
# something other than AttribteErrors on bad getattr.
class MisbehavingGetattr(object):
def __getattr__(self):
raise KeyError("I should be caught")
def some_method(self):
pass
class SillierWithDir(MisbehavingGetattr):
def __dir__(self):
return ['some_method']
for bad_klass in (MisbehavingGetattr, SillierWithDir):
res = dir2(bad_klass())
assert('some_method' in res)

View file

@ -0,0 +1,20 @@
# encoding: utf-8
def test_import_coloransi():
from IPython.utils import coloransi
def test_import_generics():
from IPython.utils import generics
def test_import_ipstruct():
from IPython.utils import ipstruct
def test_import_PyColorize():
from IPython.utils import PyColorize
def test_import_strdispatch():
from IPython.utils import strdispatch
def test_import_wildcard():
from IPython.utils import wildcard

View file

@ -0,0 +1,39 @@
"""Tests for IPython.utils.importstring."""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 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 nose.tools as nt
from IPython.utils.importstring import import_item
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
def test_import_plain():
"Test simple imports"
import os
os2 = import_item('os')
nt.assert_true(os is os2)
def test_import_nested():
"Test nested imports from the stdlib"
from os import path
path2 = import_item('os.path')
nt.assert_true(path is path2)
def test_import_raises():
"Test that failing imports raise the right exception"
nt.assert_raises(ImportError, import_item, 'IPython.foobar')

View file

@ -0,0 +1,89 @@
# encoding: utf-8
"""Tests for io.py"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import sys
from io import StringIO
from subprocess import Popen, PIPE
import unittest
import nose.tools as nt
from IPython.utils.io import IOStream, Tee, capture_output
def test_tee_simple():
"Very simple check with stdout only"
chan = StringIO()
text = 'Hello'
tee = Tee(chan, channel='stdout')
print(text, file=chan)
nt.assert_equal(chan.getvalue(), text+"\n")
class TeeTestCase(unittest.TestCase):
def tchan(self, channel):
trap = StringIO()
chan = StringIO()
text = 'Hello'
std_ori = getattr(sys, channel)
setattr(sys, channel, trap)
tee = Tee(chan, channel=channel)
print(text, end='', file=chan)
trap_val = trap.getvalue()
nt.assert_equal(chan.getvalue(), text)
tee.close()
setattr(sys, channel, std_ori)
assert getattr(sys, channel) == std_ori
def test(self):
for chan in ['stdout', 'stderr']:
self.tchan(chan)
def test_io_init():
"""Test that io.stdin/out/err exist at startup"""
for name in ('stdin', 'stdout', 'stderr'):
cmd = "from IPython.utils import io;print(io.%s.__class__)"%name
with Popen([sys.executable, '-c', cmd], stdout=PIPE) as p:
p.wait()
classname = p.stdout.read().strip().decode('ascii')
# __class__ is a reference to the class object in Python 3, so we can't
# just test for string equality.
assert 'IPython.utils.io.IOStream' in classname, classname
class TestIOStream(unittest.TestCase):
def test_IOStream_init(self):
"""IOStream initializes from a file-like object missing attributes. """
# Cause a failure from getattr and dir(). (Issue #6386)
class BadStringIO(StringIO):
def __dir__(self):
attrs = super().__dir__()
attrs.append('name')
return attrs
with self.assertWarns(DeprecationWarning):
iostream = IOStream(BadStringIO())
iostream.write('hi, bad iostream\n')
assert not hasattr(iostream, 'name')
iostream.close()
def test_capture_output(self):
"""capture_output() context works"""
with capture_output() as io:
print('hi, stdout')
print('hi, stderr', file=sys.stderr)
nt.assert_equal(io.stdout, 'hi, stdout\n')
nt.assert_equal(io.stderr, 'hi, stderr\n')

View file

@ -0,0 +1,114 @@
# encoding: utf-8
"""Tests for IPython.utils.module_paths.py"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-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 shutil
import sys
import tempfile
from os.path import join, abspath, split
from IPython.testing.tools import make_tempfile
import IPython.utils.module_paths as mp
import nose.tools as nt
env = os.environ
TEST_FILE_PATH = split(abspath(__file__))[0]
TMP_TEST_DIR = tempfile.mkdtemp(suffix='with.dot')
#
# Setup/teardown functions/decorators
#
old_syspath = sys.path
def make_empty_file(fname):
open(fname, 'w').close()
def setup_module():
"""Setup testenvironment for the module:
"""
# Do not mask exceptions here. In particular, catching WindowsError is a
# problem because that exception is only defined on Windows...
os.makedirs(join(TMP_TEST_DIR, "xmod"))
os.makedirs(join(TMP_TEST_DIR, "nomod"))
make_empty_file(join(TMP_TEST_DIR, "xmod/__init__.py"))
make_empty_file(join(TMP_TEST_DIR, "xmod/sub.py"))
make_empty_file(join(TMP_TEST_DIR, "pack.py"))
make_empty_file(join(TMP_TEST_DIR, "packpyc.pyc"))
sys.path = [TMP_TEST_DIR]
def teardown_module():
"""Teardown testenvironment for the module:
- Remove tempdir
- restore sys.path
"""
# Note: we remove the parent test dir, which is the root of all test
# subdirs we may have created. Use shutil instead of os.removedirs, so
# that non-empty directories are all recursively removed.
shutil.rmtree(TMP_TEST_DIR)
sys.path = old_syspath
def test_tempdir():
"""
Ensure the test are done with a temporary file that have a dot somewhere.
"""
nt.assert_in('.',TMP_TEST_DIR)
def test_find_mod_1():
"""
Search for a directory's file path.
Expected output: a path to that directory's __init__.py file.
"""
modpath = join(TMP_TEST_DIR, "xmod", "__init__.py")
nt.assert_equal(mp.find_mod("xmod"), modpath)
def test_find_mod_2():
"""
Search for a directory's file path.
Expected output: a path to that directory's __init__.py file.
TODO: Confirm why this is a duplicate test.
"""
modpath = join(TMP_TEST_DIR, "xmod", "__init__.py")
nt.assert_equal(mp.find_mod("xmod"), modpath)
def test_find_mod_3():
"""
Search for a directory + a filename without its .py extension
Expected output: full path with .py extension.
"""
modpath = join(TMP_TEST_DIR, "xmod", "sub.py")
nt.assert_equal(mp.find_mod("xmod.sub"), modpath)
def test_find_mod_4():
"""
Search for a filename without its .py extension
Expected output: full path with .py extension
"""
modpath = join(TMP_TEST_DIR, "pack.py")
nt.assert_equal(mp.find_mod("pack"), modpath)
def test_find_mod_5():
"""
Search for a filename with a .pyc extension
Expected output: TODO: do we exclude or include .pyc files?
"""
nt.assert_equal(mp.find_mod("packpyc"), None)

View file

@ -0,0 +1,39 @@
import io
import os.path
import nose.tools as nt
from IPython.utils import openpy
mydir = os.path.dirname(__file__)
nonascii_path = os.path.join(mydir, "../../core/tests/nonascii.py")
def test_detect_encoding():
with open(nonascii_path, "rb") as f:
enc, lines = openpy.detect_encoding(f.readline)
nt.assert_equal(enc, "iso-8859-5")
def test_read_file():
with io.open(nonascii_path, encoding="iso-8859-5") as f:
read_specified_enc = f.read()
read_detected_enc = openpy.read_py_file(nonascii_path, skip_encoding_cookie=False)
nt.assert_equal(read_detected_enc, read_specified_enc)
assert "coding: iso-8859-5" in read_detected_enc
read_strip_enc_cookie = openpy.read_py_file(
nonascii_path, skip_encoding_cookie=True
)
assert "coding: iso-8859-5" not in read_strip_enc_cookie
def test_source_to_unicode():
with io.open(nonascii_path, "rb") as f:
source_bytes = f.read()
nt.assert_equal(
openpy.source_to_unicode(source_bytes, skip_encoding_cookie=False).splitlines(),
source_bytes.decode("iso-8859-5").splitlines(),
)
source_no_cookie = openpy.source_to_unicode(source_bytes, skip_encoding_cookie=True)
nt.assert_not_in("coding: iso-8859-5", source_no_cookie)

View file

@ -0,0 +1,492 @@
# encoding: utf-8
"""Tests for IPython.utils.path.py"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import os
import shutil
import sys
import tempfile
import unittest
from contextlib import contextmanager
from unittest.mock import patch
from os.path import join, abspath
from imp import reload
from nose import SkipTest, with_setup
import nose.tools as nt
import IPython
from IPython import paths
from IPython.testing import decorators as dec
from IPython.testing.decorators import (skip_if_not_win32, skip_win32,
onlyif_unicode_paths,
skip_win32_py38,)
from IPython.testing.tools import make_tempfile
from IPython.utils import path
from IPython.utils.tempdir import TemporaryDirectory
# Platform-dependent imports
try:
import winreg as wreg
except ImportError:
#Fake _winreg module on non-windows platforms
import types
wr_name = "winreg"
sys.modules[wr_name] = types.ModuleType(wr_name)
try:
import winreg as wreg
except ImportError:
import _winreg as wreg
#Add entries that needs to be stubbed by the testing code
(wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
env = os.environ
TMP_TEST_DIR = tempfile.mkdtemp()
HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
#
# Setup/teardown functions/decorators
#
def setup_module():
"""Setup testenvironment for the module:
- Adds dummy home dir tree
"""
# Do not mask exceptions here. In particular, catching WindowsError is a
# problem because that exception is only defined on Windows...
os.makedirs(os.path.join(HOME_TEST_DIR, 'ipython'))
def teardown_module():
"""Teardown testenvironment for the module:
- Remove dummy home dir tree
"""
# Note: we remove the parent test dir, which is the root of all test
# subdirs we may have created. Use shutil instead of os.removedirs, so
# that non-empty directories are all recursively removed.
shutil.rmtree(TMP_TEST_DIR)
def setup_environment():
"""Setup testenvironment for some functions that are tested
in this module. In particular this functions stores attributes
and other things that we need to stub in some test functions.
This needs to be done on a function level and not module level because
each testfunction needs a pristine environment.
"""
global oldstuff, platformstuff
oldstuff = (env.copy(), os.name, sys.platform, path.get_home_dir, IPython.__file__, os.getcwd())
def teardown_environment():
"""Restore things that were remembered by the setup_environment function
"""
(oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff
os.chdir(old_wd)
reload(path)
for key in list(env):
if key not in oldenv:
del env[key]
env.update(oldenv)
if hasattr(sys, 'frozen'):
del sys.frozen
# Build decorator that uses the setup_environment/setup_environment
with_environment = with_setup(setup_environment, teardown_environment)
@skip_if_not_win32
@with_environment
def test_get_home_dir_1():
"""Testcase for py2exe logic, un-compressed lib
"""
unfrozen = path.get_home_dir()
sys.frozen = True
#fake filename for IPython.__init__
IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
home_dir = path.get_home_dir()
nt.assert_equal(home_dir, unfrozen)
@skip_if_not_win32
@with_environment
def test_get_home_dir_2():
"""Testcase for py2exe logic, compressed lib
"""
unfrozen = path.get_home_dir()
sys.frozen = True
#fake filename for IPython.__init__
IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
home_dir = path.get_home_dir(True)
nt.assert_equal(home_dir, unfrozen)
@skip_win32_py38
@with_environment
def test_get_home_dir_3():
"""get_home_dir() uses $HOME if set"""
env["HOME"] = HOME_TEST_DIR
home_dir = path.get_home_dir(True)
# get_home_dir expands symlinks
nt.assert_equal(home_dir, os.path.realpath(env["HOME"]))
@with_environment
def test_get_home_dir_4():
"""get_home_dir() still works if $HOME is not set"""
if 'HOME' in env: del env['HOME']
# this should still succeed, but we don't care what the answer is
home = path.get_home_dir(False)
@skip_win32_py38
@with_environment
def test_get_home_dir_5():
"""raise HomeDirError if $HOME is specified, but not a writable dir"""
env['HOME'] = abspath(HOME_TEST_DIR+'garbage')
# set os.name = posix, to prevent My Documents fallback on Windows
os.name = 'posix'
nt.assert_raises(path.HomeDirError, path.get_home_dir, True)
# Should we stub wreg fully so we can run the test on all platforms?
@skip_if_not_win32
@with_environment
def test_get_home_dir_8():
"""Using registry hack for 'My Documents', os=='nt'
HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
"""
os.name = 'nt'
# Remove from stub environment all keys that may be set
for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
env.pop(key, None)
class key:
def __enter__(self):
pass
def Close(self):
pass
def __exit__(*args, **kwargs):
pass
with patch.object(wreg, 'OpenKey', return_value=key()), \
patch.object(wreg, 'QueryValueEx', return_value=[abspath(HOME_TEST_DIR)]):
home_dir = path.get_home_dir()
nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
@with_environment
def test_get_xdg_dir_0():
"""test_get_xdg_dir_0, check xdg_dir"""
reload(path)
path._writable_dir = lambda path: True
path.get_home_dir = lambda : 'somewhere'
os.name = "posix"
sys.platform = "linux2"
env.pop('IPYTHON_DIR', None)
env.pop('IPYTHONDIR', None)
env.pop('XDG_CONFIG_HOME', None)
nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
@with_environment
def test_get_xdg_dir_1():
"""test_get_xdg_dir_1, check nonexistent xdg_dir"""
reload(path)
path.get_home_dir = lambda : HOME_TEST_DIR
os.name = "posix"
sys.platform = "linux2"
env.pop('IPYTHON_DIR', None)
env.pop('IPYTHONDIR', None)
env.pop('XDG_CONFIG_HOME', None)
nt.assert_equal(path.get_xdg_dir(), None)
@with_environment
def test_get_xdg_dir_2():
"""test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
reload(path)
path.get_home_dir = lambda : HOME_TEST_DIR
os.name = "posix"
sys.platform = "linux2"
env.pop('IPYTHON_DIR', None)
env.pop('IPYTHONDIR', None)
env.pop('XDG_CONFIG_HOME', None)
cfgdir=os.path.join(path.get_home_dir(), '.config')
if not os.path.exists(cfgdir):
os.makedirs(cfgdir)
nt.assert_equal(path.get_xdg_dir(), cfgdir)
@with_environment
def test_get_xdg_dir_3():
"""test_get_xdg_dir_3, check xdg_dir not used on OS X"""
reload(path)
path.get_home_dir = lambda : HOME_TEST_DIR
os.name = "posix"
sys.platform = "darwin"
env.pop('IPYTHON_DIR', None)
env.pop('IPYTHONDIR', None)
env.pop('XDG_CONFIG_HOME', None)
cfgdir=os.path.join(path.get_home_dir(), '.config')
if not os.path.exists(cfgdir):
os.makedirs(cfgdir)
nt.assert_equal(path.get_xdg_dir(), None)
def test_filefind():
"""Various tests for filefind"""
f = tempfile.NamedTemporaryFile()
# print 'fname:',f.name
alt_dirs = paths.get_ipython_dir()
t = path.filefind(f.name, alt_dirs)
# print 'found:',t
@dec.skip_if_not_win32
def test_get_long_path_name_win32():
with TemporaryDirectory() as tmpdir:
# Make a long path. Expands the path of tmpdir prematurely as it may already have a long
# path component, so ensure we include the long form of it
long_path = os.path.join(path.get_long_path_name(tmpdir), 'this is my long path name')
os.makedirs(long_path)
# Test to see if the short path evaluates correctly.
short_path = os.path.join(tmpdir, 'THISIS~1')
evaluated_path = path.get_long_path_name(short_path)
nt.assert_equal(evaluated_path.lower(), long_path.lower())
@dec.skip_win32
def test_get_long_path_name():
p = path.get_long_path_name('/usr/local')
nt.assert_equal(p,'/usr/local')
class TestRaiseDeprecation(unittest.TestCase):
@dec.skip_win32 # can't create not-user-writable dir on win
@with_environment
def test_not_writable_ipdir(self):
tmpdir = tempfile.mkdtemp()
os.name = "posix"
env.pop('IPYTHON_DIR', None)
env.pop('IPYTHONDIR', None)
env.pop('XDG_CONFIG_HOME', None)
env['HOME'] = tmpdir
ipdir = os.path.join(tmpdir, '.ipython')
os.mkdir(ipdir, 0o555)
try:
open(os.path.join(ipdir, "_foo_"), 'w').close()
except IOError:
pass
else:
# I can still write to an unwritable dir,
# assume I'm root and skip the test
raise SkipTest("I can't create directories that I can't write to")
with self.assertWarnsRegex(UserWarning, 'is not a writable location'):
ipdir = paths.get_ipython_dir()
env.pop('IPYTHON_DIR', None)
@with_environment
def test_get_py_filename():
os.chdir(TMP_TEST_DIR)
with make_tempfile('foo.py'):
nt.assert_equal(path.get_py_filename('foo.py'), 'foo.py')
nt.assert_equal(path.get_py_filename('foo'), 'foo.py')
with make_tempfile('foo'):
nt.assert_equal(path.get_py_filename('foo'), 'foo')
nt.assert_raises(IOError, path.get_py_filename, 'foo.py')
nt.assert_raises(IOError, path.get_py_filename, 'foo')
nt.assert_raises(IOError, path.get_py_filename, 'foo.py')
true_fn = 'foo with spaces.py'
with make_tempfile(true_fn):
nt.assert_equal(path.get_py_filename('foo with spaces'), true_fn)
nt.assert_equal(path.get_py_filename('foo with spaces.py'), true_fn)
nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"')
nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'")
@onlyif_unicode_paths
def test_unicode_in_filename():
"""When a file doesn't exist, the exception raised should be safe to call
str() on - i.e. in Python 2 it must only have ASCII characters.
https://github.com/ipython/ipython/issues/875
"""
try:
# these calls should not throw unicode encode exceptions
path.get_py_filename('fooéè.py')
except IOError as ex:
str(ex)
class TestShellGlob(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.filenames_start_with_a = ['a0', 'a1', 'a2']
cls.filenames_end_with_b = ['0b', '1b', '2b']
cls.filenames = cls.filenames_start_with_a + cls.filenames_end_with_b
cls.tempdir = TemporaryDirectory()
td = cls.tempdir.name
with cls.in_tempdir():
# Create empty files
for fname in cls.filenames:
open(os.path.join(td, fname), 'w').close()
@classmethod
def tearDownClass(cls):
cls.tempdir.cleanup()
@classmethod
@contextmanager
def in_tempdir(cls):
save = os.getcwd()
try:
os.chdir(cls.tempdir.name)
yield
finally:
os.chdir(save)
def check_match(self, patterns, matches):
with self.in_tempdir():
# glob returns unordered list. that's why sorted is required.
nt.assert_equal(sorted(path.shellglob(patterns)),
sorted(matches))
def common_cases(self):
return [
(['*'], self.filenames),
(['a*'], self.filenames_start_with_a),
(['*c'], ['*c']),
(['*', 'a*', '*b', '*c'], self.filenames
+ self.filenames_start_with_a
+ self.filenames_end_with_b
+ ['*c']),
(['a[012]'], self.filenames_start_with_a),
]
@skip_win32
def test_match_posix(self):
for (patterns, matches) in self.common_cases() + [
([r'\*'], ['*']),
([r'a\*', 'a*'], ['a*'] + self.filenames_start_with_a),
([r'a\[012]'], ['a[012]']),
]:
yield (self.check_match, patterns, matches)
@skip_if_not_win32
def test_match_windows(self):
for (patterns, matches) in self.common_cases() + [
# In windows, backslash is interpreted as path
# separator. Therefore, you can't escape glob
# using it.
([r'a\*', 'a*'], [r'a\*'] + self.filenames_start_with_a),
([r'a\[012]'], [r'a\[012]']),
]:
yield (self.check_match, patterns, matches)
def test_unescape_glob():
nt.assert_equal(path.unescape_glob(r'\*\[\!\]\?'), '*[!]?')
nt.assert_equal(path.unescape_glob(r'\\*'), r'\*')
nt.assert_equal(path.unescape_glob(r'\\\*'), r'\*')
nt.assert_equal(path.unescape_glob(r'\\a'), r'\a')
nt.assert_equal(path.unescape_glob(r'\a'), r'\a')
@onlyif_unicode_paths
def test_ensure_dir_exists():
with TemporaryDirectory() as td:
d = os.path.join(td, '∂ir')
path.ensure_dir_exists(d) # create it
assert os.path.isdir(d)
path.ensure_dir_exists(d) # no-op
f = os.path.join(td, 'ƒile')
open(f, 'w').close() # touch
with nt.assert_raises(IOError):
path.ensure_dir_exists(f)
class TestLinkOrCopy(unittest.TestCase):
def setUp(self):
self.tempdir = TemporaryDirectory()
self.src = self.dst("src")
with open(self.src, "w") as f:
f.write("Hello, world!")
def tearDown(self):
self.tempdir.cleanup()
def dst(self, *args):
return os.path.join(self.tempdir.name, *args)
def assert_inode_not_equal(self, a, b):
nt.assert_not_equal(os.stat(a).st_ino, os.stat(b).st_ino,
"%r and %r do reference the same indoes" %(a, b))
def assert_inode_equal(self, a, b):
nt.assert_equal(os.stat(a).st_ino, os.stat(b).st_ino,
"%r and %r do not reference the same indoes" %(a, b))
def assert_content_equal(self, a, b):
with open(a) as a_f:
with open(b) as b_f:
nt.assert_equal(a_f.read(), b_f.read())
@skip_win32
def test_link_successful(self):
dst = self.dst("target")
path.link_or_copy(self.src, dst)
self.assert_inode_equal(self.src, dst)
@skip_win32
def test_link_into_dir(self):
dst = self.dst("some_dir")
os.mkdir(dst)
path.link_or_copy(self.src, dst)
expected_dst = self.dst("some_dir", os.path.basename(self.src))
self.assert_inode_equal(self.src, expected_dst)
@skip_win32
def test_target_exists(self):
dst = self.dst("target")
open(dst, "w").close()
path.link_or_copy(self.src, dst)
self.assert_inode_equal(self.src, dst)
@skip_win32
def test_no_link(self):
real_link = os.link
try:
del os.link
dst = self.dst("target")
path.link_or_copy(self.src, dst)
self.assert_content_equal(self.src, dst)
self.assert_inode_not_equal(self.src, dst)
finally:
os.link = real_link
@skip_if_not_win32
def test_windows(self):
dst = self.dst("target")
path.link_or_copy(self.src, dst)
self.assert_content_equal(self.src, dst)
def test_link_twice(self):
# Linking the same file twice shouldn't leave duplicates around.
# See https://github.com/ipython/ipython/issues/6450
dst = self.dst('target')
path.link_or_copy(self.src, dst)
path.link_or_copy(self.src, dst)
self.assert_inode_equal(self.src, dst)
nt.assert_equal(sorted(os.listdir(self.tempdir.name)), ['src', 'target'])

View file

@ -0,0 +1,195 @@
# encoding: utf-8
"""
Tests for platutils.py
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2008-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 sys
import signal
import os
import time
from _thread import interrupt_main # Py 3
import threading
from unittest import SkipTest
import nose.tools as nt
from IPython.utils.process import (find_cmd, FindCmdError, arg_split,
system, getoutput, getoutputerror,
get_output_error_code)
from IPython.utils.capture import capture_output
from IPython.testing import decorators as dec
from IPython.testing import tools as tt
python = os.path.basename(sys.executable)
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
@dec.skip_win32
def test_find_cmd_ls():
"""Make sure we can find the full path to ls."""
path = find_cmd('ls')
nt.assert_true(path.endswith('ls'))
def has_pywin32():
try:
import win32api
except ImportError:
return False
return True
@dec.onlyif(has_pywin32, "This test requires win32api to run")
def test_find_cmd_pythonw():
"""Try to find pythonw on Windows."""
path = find_cmd('pythonw')
assert path.lower().endswith('pythonw.exe'), path
@dec.onlyif(lambda : sys.platform != 'win32' or has_pywin32(),
"This test runs on posix or in win32 with win32api installed")
def test_find_cmd_fail():
"""Make sure that FindCmdError is raised if we can't find the cmd."""
nt.assert_raises(FindCmdError,find_cmd,'asdfasdf')
@dec.skip_win32
def test_arg_split():
"""Ensure that argument lines are correctly split like in a shell."""
tests = [['hi', ['hi']],
[u'hi', [u'hi']],
['hello there', ['hello', 'there']],
# \u01ce == \N{LATIN SMALL LETTER A WITH CARON}
# Do not use \N because the tests crash with syntax error in
# some cases, for example windows python2.6.
[u'h\u01cello', [u'h\u01cello']],
['something "with quotes"', ['something', '"with quotes"']],
]
for argstr, argv in tests:
nt.assert_equal(arg_split(argstr), argv)
@dec.skip_if_not_win32
def test_arg_split_win32():
"""Ensure that argument lines are correctly split like in a shell."""
tests = [['hi', ['hi']],
[u'hi', [u'hi']],
['hello there', ['hello', 'there']],
[u'h\u01cello', [u'h\u01cello']],
['something "with quotes"', ['something', 'with quotes']],
]
for argstr, argv in tests:
nt.assert_equal(arg_split(argstr), argv)
class SubProcessTestCase(tt.TempFileMixin):
def setUp(self):
"""Make a valid python temp file."""
lines = [ "import sys",
"print('on stdout', end='', file=sys.stdout)",
"print('on stderr', end='', file=sys.stderr)",
"sys.stdout.flush()",
"sys.stderr.flush()"]
self.mktmp('\n'.join(lines))
def test_system(self):
status = system('%s "%s"' % (python, self.fname))
self.assertEqual(status, 0)
def test_system_quotes(self):
status = system('%s -c "import sys"' % python)
self.assertEqual(status, 0)
def assert_interrupts(self, command):
"""
Interrupt a subprocess after a second.
"""
if threading.main_thread() != threading.current_thread():
raise nt.SkipTest("Can't run this test if not in main thread.")
# Some tests can overwrite SIGINT handler (by using pdb for example),
# which then breaks this test, so just make sure it's operating
# normally.
signal.signal(signal.SIGINT, signal.default_int_handler)
def interrupt():
# Wait for subprocess to start:
time.sleep(0.5)
interrupt_main()
threading.Thread(target=interrupt).start()
start = time.time()
try:
result = command()
except KeyboardInterrupt:
# Success!
pass
end = time.time()
self.assertTrue(
end - start < 2, "Process didn't die quickly: %s" % (end - start)
)
return result
def test_system_interrupt(self):
"""
When interrupted in the way ipykernel interrupts IPython, the
subprocess is interrupted.
"""
def command():
return system('%s -c "import time; time.sleep(5)"' % python)
status = self.assert_interrupts(command)
self.assertNotEqual(
status, 0, "The process wasn't interrupted. Status: %s" % (status,)
)
def test_getoutput(self):
out = getoutput('%s "%s"' % (python, self.fname))
# we can't rely on the order the line buffered streams are flushed
try:
self.assertEqual(out, 'on stderron stdout')
except AssertionError:
self.assertEqual(out, 'on stdouton stderr')
def test_getoutput_quoted(self):
out = getoutput('%s -c "print (1)"' % python)
self.assertEqual(out.strip(), '1')
#Invalid quoting on windows
@dec.skip_win32
def test_getoutput_quoted2(self):
out = getoutput("%s -c 'print (1)'" % python)
self.assertEqual(out.strip(), '1')
out = getoutput("%s -c 'print (\"1\")'" % python)
self.assertEqual(out.strip(), '1')
def test_getoutput_error(self):
out, err = getoutputerror('%s "%s"' % (python, self.fname))
self.assertEqual(out, 'on stdout')
self.assertEqual(err, 'on stderr')
def test_get_output_error_code(self):
quiet_exit = '%s -c "import sys; sys.exit(1)"' % python
out, err, code = get_output_error_code(quiet_exit)
self.assertEqual(out, '')
self.assertEqual(err, '')
self.assertEqual(code, 1)
out, err, code = get_output_error_code('%s "%s"' % (python, self.fname))
self.assertEqual(out, 'on stdout')
self.assertEqual(err, 'on stderr')
self.assertEqual(code, 0)

View file

@ -0,0 +1,78 @@
# coding: utf-8
"""Test suite for our color utilities.
Authors
-------
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 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.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# third party
import nose.tools as nt
# our own
from IPython.utils.PyColorize import Parser
import io
#-----------------------------------------------------------------------------
# Test functions
#-----------------------------------------------------------------------------
sample = u"""
def function(arg, *args, kwarg=True, **kwargs):
'''
this is docs
'''
pass is True
False == None
with io.open(ru'unicode'):
raise ValueError("\n escape \r sequence")
print("wěird ünicoðe")
class Bar(Super):
def __init__(self):
super(Bar, self).__init__(1**2, 3^4, 5 or 6)
"""
def test_loop_colors():
for style in ('Linux', 'NoColor','LightBG', 'Neutral'):
def test_unicode_colorize():
p = Parser(style=style)
f1 = p.format('1/0', 'str')
f2 = p.format(u'1/0', 'str')
nt.assert_equal(f1, f2)
def test_parse_sample():
"""and test writing to a buffer"""
buf = io.StringIO()
p = Parser(style=style)
p.format(sample, buf)
buf.seek(0)
f1 = buf.read()
nt.assert_not_in('ERROR', f1)
def test_parse_error():
p = Parser(style=style)
f1 = p.format(')', 'str')
if style != 'NoColor':
nt.assert_in('ERROR', f1)
yield test_unicode_colorize
yield test_parse_sample
yield test_parse_error

View file

@ -0,0 +1,13 @@
import sys
import warnings
from IPython.utils.shimmodule import ShimWarning
def test_shim_warning():
sys.modules.pop('IPython.config', None)
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
import IPython.config
assert len(w) == 1
assert issubclass(w[-1].category, ShimWarning)

View file

@ -0,0 +1,17 @@
# coding: utf-8
"""Test suite for our sysinfo utilities."""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import json
import nose.tools as nt
from IPython.utils import sysinfo
def test_json_getsysinfo():
"""
test that it is easily jsonable and don't return bytes somewhere.
"""
json.dumps(sysinfo.get_sys_info())

View file

@ -0,0 +1,28 @@
#-----------------------------------------------------------------------------
# Copyright (C) 2012- 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.
#-----------------------------------------------------------------------------
import os
from IPython.utils.tempdir import NamedFileInTemporaryDirectory
from IPython.utils.tempdir import TemporaryWorkingDirectory
def test_named_file_in_temporary_directory():
with NamedFileInTemporaryDirectory('filename') as file:
name = file.name
assert not file.closed
assert os.path.exists(name)
file.write(b'test')
assert file.closed
assert not os.path.exists(name)
def test_temporary_working_directory():
with TemporaryWorkingDirectory() as dir:
assert os.path.exists(dir)
assert os.path.realpath(os.curdir) == os.path.realpath(dir)
assert not os.path.exists(dir)
assert os.path.abspath(os.curdir) != dir

View file

@ -0,0 +1,213 @@
# encoding: utf-8
"""Tests for IPython.utils.text"""
#-----------------------------------------------------------------------------
# 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 math
import random
import sys
import nose.tools as nt
from pathlib import Path
from IPython.utils import text
#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
def test_columnize():
"""Basic columnize tests."""
size = 5
items = [l*size for l in 'abcd']
out = text.columnize(items, displaywidth=80)
nt.assert_equal(out, 'aaaaa bbbbb ccccc ddddd\n')
out = text.columnize(items, displaywidth=25)
nt.assert_equal(out, 'aaaaa ccccc\nbbbbb ddddd\n')
out = text.columnize(items, displaywidth=12)
nt.assert_equal(out, 'aaaaa ccccc\nbbbbb ddddd\n')
out = text.columnize(items, displaywidth=10)
nt.assert_equal(out, 'aaaaa\nbbbbb\nccccc\nddddd\n')
out = text.columnize(items, row_first=True, displaywidth=80)
nt.assert_equal(out, 'aaaaa bbbbb ccccc ddddd\n')
out = text.columnize(items, row_first=True, displaywidth=25)
nt.assert_equal(out, 'aaaaa bbbbb\nccccc ddddd\n')
out = text.columnize(items, row_first=True, displaywidth=12)
nt.assert_equal(out, 'aaaaa bbbbb\nccccc ddddd\n')
out = text.columnize(items, row_first=True, displaywidth=10)
nt.assert_equal(out, 'aaaaa\nbbbbb\nccccc\nddddd\n')
out = text.columnize(items, displaywidth=40, spread=True)
nt.assert_equal(out, 'aaaaa bbbbb ccccc ddddd\n')
out = text.columnize(items, displaywidth=20, spread=True)
nt.assert_equal(out, 'aaaaa ccccc\nbbbbb ddddd\n')
out = text.columnize(items, displaywidth=12, spread=True)
nt.assert_equal(out, 'aaaaa ccccc\nbbbbb ddddd\n')
out = text.columnize(items, displaywidth=10, spread=True)
nt.assert_equal(out, 'aaaaa\nbbbbb\nccccc\nddddd\n')
def test_columnize_random():
"""Test with random input to hopefully catch edge case """
for row_first in [True, False]:
for nitems in [random.randint(2,70) for i in range(2,20)]:
displaywidth = random.randint(20,200)
rand_len = [random.randint(2,displaywidth) for i in range(nitems)]
items = ['x'*l for l in rand_len]
out = text.columnize(items, row_first=row_first, displaywidth=displaywidth)
longer_line = max([len(x) for x in out.split('\n')])
longer_element = max(rand_len)
if longer_line > displaywidth:
print("Columnize displayed something lager than displaywidth : %s " % longer_line)
print("longer element : %s " % longer_element)
print("displaywidth : %s " % displaywidth)
print("number of element : %s " % nitems)
print("size of each element :\n %s" % rand_len)
assert False, "row_first={0}".format(row_first)
def test_columnize_medium():
"""Test with inputs than shouldn't be wider than 80"""
size = 40
items = [l*size for l in 'abc']
for row_first in [True, False]:
out = text.columnize(items, row_first=row_first, displaywidth=80)
nt.assert_equal(out, '\n'.join(items+['']), "row_first={0}".format(row_first))
def test_columnize_long():
"""Test columnize with inputs longer than the display window"""
size = 11
items = [l*size for l in 'abc']
for row_first in [True, False]:
out = text.columnize(items, row_first=row_first, displaywidth=size-1)
nt.assert_equal(out, '\n'.join(items+['']), "row_first={0}".format(row_first))
def eval_formatter_check(f):
ns = dict(n=12, pi=math.pi, stuff='hello there', os=os, u=u"café", b="café")
s = f.format("{n} {n//4} {stuff.split()[0]}", **ns)
nt.assert_equal(s, "12 3 hello")
s = f.format(' '.join(['{n//%i}'%i for i in range(1,8)]), **ns)
nt.assert_equal(s, "12 6 4 3 2 2 1")
s = f.format('{[n//i for i in range(1,8)]}', **ns)
nt.assert_equal(s, "[12, 6, 4, 3, 2, 2, 1]")
s = f.format("{stuff!s}", **ns)
nt.assert_equal(s, ns['stuff'])
s = f.format("{stuff!r}", **ns)
nt.assert_equal(s, repr(ns['stuff']))
# Check with unicode:
s = f.format("{u}", **ns)
nt.assert_equal(s, ns['u'])
# This decodes in a platform dependent manner, but it shouldn't error out
s = f.format("{b}", **ns)
nt.assert_raises(NameError, f.format, '{dne}', **ns)
def eval_formatter_slicing_check(f):
ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
s = f.format(" {stuff.split()[:]} ", **ns)
nt.assert_equal(s, " ['hello', 'there'] ")
s = f.format(" {stuff.split()[::-1]} ", **ns)
nt.assert_equal(s, " ['there', 'hello'] ")
s = f.format("{stuff[::2]}", **ns)
nt.assert_equal(s, ns['stuff'][::2])
nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns)
def eval_formatter_no_slicing_check(f):
ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
s = f.format('{n:x} {pi**2:+f}', **ns)
nt.assert_equal(s, "c +9.869604")
s = f.format('{stuff[slice(1,4)]}', **ns)
nt.assert_equal(s, 'ell')
s = f.format("{a[:]}", a=[1, 2])
nt.assert_equal(s, "[1, 2]")
def test_eval_formatter():
f = text.EvalFormatter()
eval_formatter_check(f)
eval_formatter_no_slicing_check(f)
def test_full_eval_formatter():
f = text.FullEvalFormatter()
eval_formatter_check(f)
eval_formatter_slicing_check(f)
def test_dollar_formatter():
f = text.DollarFormatter()
eval_formatter_check(f)
eval_formatter_slicing_check(f)
ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
s = f.format("$n", **ns)
nt.assert_equal(s, "12")
s = f.format("$n.real", **ns)
nt.assert_equal(s, "12")
s = f.format("$n/{stuff[:5]}", **ns)
nt.assert_equal(s, "12/hello")
s = f.format("$n $$HOME", **ns)
nt.assert_equal(s, "12 $HOME")
s = f.format("${foo}", foo="HOME")
nt.assert_equal(s, "$HOME")
def test_long_substr():
data = ['hi']
nt.assert_equal(text.long_substr(data), 'hi')
def test_long_substr2():
data = ['abc', 'abd', 'abf', 'ab']
nt.assert_equal(text.long_substr(data), 'ab')
def test_long_substr_empty():
data = []
nt.assert_equal(text.long_substr(data), '')
def test_strip_email():
src = """\
>> >>> def f(x):
>> ... return x+1
>> ...
>> >>> zz = f(2.5)"""
cln = """\
>>> def f(x):
... return x+1
...
>>> zz = f(2.5)"""
nt.assert_equal(text.strip_email_quotes(src), cln)
def test_strip_email2():
src = '> > > list()'
cln = 'list()'
nt.assert_equal(text.strip_email_quotes(src), cln)
def test_LSString():
lss = text.LSString("abc\ndef")
nt.assert_equal(lss.l, ['abc', 'def'])
nt.assert_equal(lss.s, 'abc def')
lss = text.LSString(os.getcwd())
nt.assert_is_instance(lss.p[0], Path)
def test_SList():
sl = text.SList(['a 11', 'b 1', 'a 2'])
nt.assert_equal(sl.n, 'a 11\nb 1\na 2')
nt.assert_equal(sl.s, 'a 11 b 1 a 2')
nt.assert_equal(sl.grep(lambda x: x.startswith('a')), text.SList(['a 11', 'a 2']))
nt.assert_equal(sl.fields(0), text.SList(['a', 'b', 'a']))
nt.assert_equal(sl.sort(field=1, nums=True), text.SList(['b 1', 'a 2', 'a 11']))

View file

@ -0,0 +1,133 @@
"""Tests for tokenutil"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import nose.tools as nt
from IPython.utils.tokenutil import token_at_cursor, line_at_cursor
def expect_token(expected, cell, cursor_pos):
token = token_at_cursor(cell, cursor_pos)
offset = 0
for line in cell.splitlines():
if offset + len(line) >= cursor_pos:
break
else:
offset += len(line)+1
column = cursor_pos - offset
line_with_cursor = '%s|%s' % (line[:column], line[column:])
nt.assert_equal(token, expected,
"Expected %r, got %r in: %r (pos %i)" % (
expected, token, line_with_cursor, cursor_pos)
)
def test_simple():
cell = "foo"
for i in range(len(cell)):
expect_token("foo", cell, i)
def test_function():
cell = "foo(a=5, b='10')"
expected = 'foo'
# up to `foo(|a=`
for i in range(cell.find('a=') + 1):
expect_token("foo", cell, i)
# find foo after `=`
for i in [cell.find('=') + 1, cell.rfind('=') + 1]:
expect_token("foo", cell, i)
# in between `5,|` and `|b=`
for i in range(cell.find(','), cell.find('b=')):
expect_token("foo", cell, i)
def test_multiline():
cell = '\n'.join([
'a = 5',
'b = hello("string", there)'
])
expected = 'hello'
start = cell.index(expected) + 1
for i in range(start, start + len(expected)):
expect_token(expected, cell, i)
expected = 'hello'
start = cell.index(expected) + 1
for i in range(start, start + len(expected)):
expect_token(expected, cell, i)
def test_multiline_token():
cell = '\n'.join([
'"""\n\nxxxxxxxxxx\n\n"""',
'5, """',
'docstring',
'multiline token',
'""", [',
'2, 3, "complicated"]',
'b = hello("string", there)'
])
expected = 'hello'
start = cell.index(expected) + 1
for i in range(start, start + len(expected)):
expect_token(expected, cell, i)
expected = 'hello'
start = cell.index(expected) + 1
for i in range(start, start + len(expected)):
expect_token(expected, cell, i)
def test_nested_call():
cell = "foo(bar(a=5), b=10)"
expected = 'foo'
start = cell.index('bar') + 1
for i in range(start, start + 3):
expect_token(expected, cell, i)
expected = 'bar'
start = cell.index('a=')
for i in range(start, start + 3):
expect_token(expected, cell, i)
expected = 'foo'
start = cell.index(')') + 1
for i in range(start, len(cell)-1):
expect_token(expected, cell, i)
def test_attrs():
cell = "a = obj.attr.subattr"
expected = 'obj'
idx = cell.find('obj') + 1
for i in range(idx, idx + 3):
expect_token(expected, cell, i)
idx = cell.find('.attr') + 2
expected = 'obj.attr'
for i in range(idx, idx + 4):
expect_token(expected, cell, i)
idx = cell.find('.subattr') + 2
expected = 'obj.attr.subattr'
for i in range(idx, len(cell)):
expect_token(expected, cell, i)
def test_line_at_cursor():
cell = ""
(line, offset) = line_at_cursor(cell, cursor_pos=11)
nt.assert_equal(line, "")
nt.assert_equal(offset, 0)
# The position after a newline should be the start of the following line.
cell = "One\nTwo\n"
(line, offset) = line_at_cursor(cell, cursor_pos=4)
nt.assert_equal(line, "Two\n")
nt.assert_equal(offset, 4)
# The end of a cell should be on the last line
cell = "pri\npri"
(line, offset) = line_at_cursor(cell, cursor_pos=7)
nt.assert_equal(line, "pri")
nt.assert_equal(offset, 4)
def test_multiline_statement():
cell = """a = (1,
3)
int()
map()
"""
for c in range(16, 22):
yield lambda cell, c: expect_token("int", cell, c), cell, c
for c in range(22, 28):
yield lambda cell, c: expect_token("map", cell, c), cell, c

View file

@ -0,0 +1,143 @@
"""Some tests for the wildcard utilities."""
#-----------------------------------------------------------------------------
# Library imports
#-----------------------------------------------------------------------------
# Stdlib
import unittest
# Our own
from IPython.utils import wildcard
#-----------------------------------------------------------------------------
# Globals for test
#-----------------------------------------------------------------------------
class obj_t(object):
pass
root = obj_t()
l = ["arna","abel","ABEL","active","bob","bark","abbot"]
q = ["kate","loop","arne","vito","lucifer","koppel"]
for x in l:
o = obj_t()
setattr(root,x,o)
for y in q:
p = obj_t()
setattr(o,y,p)
root._apan = obj_t()
root._apan.a = 10
root._apan._a = 20
root._apan.__a = 20
root.__anka = obj_t()
root.__anka.a = 10
root.__anka._a = 20
root.__anka.__a = 20
root._APAN = obj_t()
root._APAN.a = 10
root._APAN._a = 20
root._APAN.__a = 20
root.__ANKA = obj_t()
root.__ANKA.a = 10
root.__ANKA._a = 20
root.__ANKA.__a = 20
#-----------------------------------------------------------------------------
# Test cases
#-----------------------------------------------------------------------------
class Tests (unittest.TestCase):
def test_case(self):
ns=root.__dict__
tests=[
("a*", ["abbot","abel","active","arna",]),
("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
("_a*", []),
("_*anka", ["__anka",]),
("_*a*", ["__anka",]),
]
for pat,res in tests:
res.sort()
a=sorted(wildcard.list_namespace(ns,"all",pat,ignore_case=False,
show_all=False).keys())
self.assertEqual(a,res)
def test_case_showall(self):
ns=root.__dict__
tests=[
("a*", ["abbot","abel","active","arna",]),
("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",]),
("_a*", ["_apan"]),
("_*anka", ["__anka",]),
("_*a*", ["__anka","_apan",]),
]
for pat,res in tests:
res.sort()
a=sorted(wildcard.list_namespace(ns,"all",pat,ignore_case=False,
show_all=True).keys())
self.assertEqual(a,res)
def test_nocase(self):
ns=root.__dict__
tests=[
("a*", ["abbot","abel","ABEL","active","arna",]),
("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",
"ABEL.koppel","ABEL.loop",]),
("_a*", []),
("_*anka", ["__anka","__ANKA",]),
("_*a*", ["__anka","__ANKA",]),
]
for pat,res in tests:
res.sort()
a=sorted(wildcard.list_namespace(ns,"all",pat,ignore_case=True,
show_all=False).keys())
self.assertEqual(a,res)
def test_nocase_showall(self):
ns=root.__dict__
tests=[
("a*", ["abbot","abel","ABEL","active","arna",]),
("?b*.?o*",["abbot.koppel","abbot.loop","abel.koppel","abel.loop",
"ABEL.koppel","ABEL.loop",]),
("_a*", ["_apan","_APAN"]),
("_*anka", ["__anka","__ANKA",]),
("_*a*", ["__anka","__ANKA","_apan","_APAN"]),
]
for pat,res in tests:
res.sort()
a=sorted(wildcard.list_namespace(ns,"all",pat,ignore_case=True,
show_all=True).keys())
a.sort()
self.assertEqual(a,res)
def test_dict_attributes(self):
"""Dictionaries should be indexed by attributes, not by keys. This was
causing Github issue 129."""
ns = {"az":{"king":55}, "pq":{1:0}}
tests = [
("a*", ["az"]),
("az.k*", ["az.keys"]),
("pq.k*", ["pq.keys"])
]
for pat, res in tests:
res.sort()
a = sorted(wildcard.list_namespace(ns, "all", pat, ignore_case=False,
show_all=True).keys())
self.assertEqual(a, res)
def test_dict_dir(self):
class A(object):
def __init__(self):
self.a = 1
self.b = 2
def __getattribute__(self, name):
if name=="a":
raise AttributeError
return object.__getattribute__(self, name)
a = A()
adict = wildcard.dict_dir(a)
assert "a" not in adict # change to assertNotIn method in >= 2.7
self.assertEqual(adict["b"], 2)