fixed subscription table

This commit is contained in:
2025-02-02 00:02:31 -05:00
parent a1ab31acfe
commit ef5f57e678
5389 changed files with 686710 additions and 28 deletions

View File

@@ -0,0 +1,166 @@
# 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 pytest
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
#-----------------------------------------------------------------------------
@pytest.mark.parametrize("method_mime", _mime_map.items())
def test_rich_output_empty(method_mime):
"""RichOutput with no args"""
rich = capture.RichOutput()
method, mime = method_mime
assert getattr(rich, method)() is None
def test_rich_output():
"""test RichOutput basics"""
data = basic_data
metadata = basic_metadata
rich = capture.RichOutput(data=data, metadata=metadata)
assert rich._repr_html_() == data["text/html"]
assert rich._repr_png_() == (data["image/png"], metadata["image/png"])
assert rich._repr_latex_() is None
assert rich._repr_javascript_() is None
assert rich._repr_svg_() is None
@pytest.mark.parametrize("method_mime", _mime_map.items())
def test_rich_output_no_metadata(method_mime):
"""test RichOutput with no metadata"""
data = full_data
rich = capture.RichOutput(data=data)
method, mime = method_mime
assert getattr(rich, method)() == data[mime]
@pytest.mark.parametrize("method_mime", _mime_map.items())
def test_rich_output_metadata(method_mime):
"""test RichOutput with metadata"""
data = full_data
metadata = full_metadata
rich = capture.RichOutput(data=data, metadata=metadata)
method, mime = method_mime
assert 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()
assert len(cap.outputs) == 1
rich2 = cap.outputs[0]
assert rich2.data == rich.data
assert 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()
assert hello_stdout == cap.stdout
assert 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()
assert "" == cap.stdout
assert hello_stderr == cap.stderr
assert 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()
assert hello_stdout == cap.stdout
assert "" == cap.stderr
assert 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()
assert hello_stdout == cap.stdout
assert hello_stderr == cap.stderr
assert 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,7 @@
from IPython.utils.syspathcontext import appended_to_syspath
import pytest
def test_append_deprecated():
with pytest.warns(DeprecationWarning):
appended_to_syspath(".")

View File

@@ -0,0 +1,66 @@
from IPython.utils.dir2 import dir2
import pytest
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
assert res.count("x") == 1
assert res.count("__class__") == 1
def test_SubClass():
class SubClass(Base):
y = 2
res = dir2(SubClass())
assert "y" in res
assert res.count("y") == 1
assert 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:
def __getattr__(self, attr):
raise KeyError("I should be caught")
def some_method(self):
return True
class SillierWithDir(MisbehavingGetattr):
def __dir__(self):
return ["some_method"]
for bad_klass in (MisbehavingGetattr, SillierWithDir):
obj = bad_klass()
assert obj.some_method()
with pytest.raises(KeyError):
obj.other_method()
res = dir2(obj)
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,40 @@
"""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 pytest
from IPython.utils.importstring import import_item
#-----------------------------------------------------------------------------
# Tests
#-----------------------------------------------------------------------------
def test_import_plain():
"Test simple imports"
import os
os2 = import_item("os")
assert os is os2
def test_import_nested():
"Test nested imports from the stdlib"
from os import path
path2 = import_item("os.path")
assert path is path2
def test_import_raises():
"Test that failing imports raise the right exception"
pytest.raises(ImportError, import_item, "IPython.foobar")

View File

@@ -0,0 +1,61 @@
# 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
import unittest
from IPython.utils.io import 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)
assert chan.getvalue() == text + "\n"
tee.close()
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()
self.assertEqual(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)
class TestIOStream(unittest.TestCase):
def test_capture_output(self):
"""capture_output() context works"""
with capture_output() as io:
print("hi, stdout")
print("hi, stderr", file=sys.stderr)
self.assertEqual(io.stdout, "hi, stdout\n")
self.assertEqual(io.stderr, "hi, stderr\n")

View File

@@ -0,0 +1,107 @@
# 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 shutil
import sys
import tempfile
from pathlib import Path
import IPython.utils.module_paths as mp
TEST_FILE_PATH = Path(__file__).resolve().parent
TMP_TEST_DIR = Path(tempfile.mkdtemp(suffix="with.dot"))
#
# Setup/teardown functions/decorators
#
old_syspath = sys.path
def make_empty_file(fname):
open(fname, "w", encoding="utf-8").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...
Path(TMP_TEST_DIR / "xmod").mkdir(parents=True)
Path(TMP_TEST_DIR / "nomod").mkdir(parents=True)
make_empty_file(TMP_TEST_DIR / "xmod/__init__.py")
make_empty_file(TMP_TEST_DIR / "xmod/sub.py")
make_empty_file(TMP_TEST_DIR / "pack.py")
make_empty_file(TMP_TEST_DIR / "packpyc.pyc")
sys.path = [str(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.
"""
assert "." in str(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 = TMP_TEST_DIR / "xmod" / "__init__.py"
assert Path(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 = TMP_TEST_DIR / "xmod" / "__init__.py"
assert Path(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 = TMP_TEST_DIR / "xmod" / "sub.py"
assert Path(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 = TMP_TEST_DIR / "pack.py"
assert Path(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?
"""
assert mp.find_mod("packpyc") == None

View File

@@ -0,0 +1,38 @@
import io
import os.path
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)
assert 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)
assert 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()
assert (
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)
assert "coding: iso-8859-5" not in source_no_cookie

View File

@@ -0,0 +1,506 @@
# 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 importlib import reload
from os.path import abspath, join
from unittest.mock import patch
import pytest
from tempfile import TemporaryDirectory
import IPython
from IPython import paths
from IPython.testing import decorators as dec
from IPython.testing.decorators import (
onlyif_unicode_paths,
skip_if_not_win32,
skip_win32,
)
from IPython.testing.tools import make_tempfile
from IPython.utils import path
# 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)
# Build decorator that uses the setup_environment/setup_environment
@pytest.fixture
def environment():
global oldstuff, platformstuff
oldstuff = (
env.copy(),
os.name,
sys.platform,
path.get_home_dir,
IPython.__file__,
os.getcwd(),
)
yield
(
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)
assert not hasattr(sys, "frozen")
with_environment = pytest.mark.usefixtures("environment")
@skip_if_not_win32
@with_environment
def test_get_home_dir_1(monkeypatch):
"""Testcase for py2exe logic, un-compressed lib
"""
unfrozen = path.get_home_dir()
monkeypatch.setattr(sys, "frozen", True, raising=False)
#fake filename for IPython.__init__
IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
home_dir = path.get_home_dir()
assert home_dir == unfrozen
@skip_if_not_win32
@with_environment
def test_get_home_dir_2(monkeypatch):
"""Testcase for py2exe logic, compressed lib
"""
unfrozen = path.get_home_dir()
monkeypatch.setattr(sys, "frozen", True, raising=False)
# 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)
assert home_dir == unfrozen
@skip_win32
@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
assert 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
@with_environment
def test_get_home_dir_5(monkeypatch):
"""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
monkeypatch.setattr(os, "name", "posix")
pytest.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(monkeypatch):
"""Using registry hack for 'My Documents', os=='nt'
HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
"""
monkeypatch.setattr(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()
assert home_dir == abspath(HOME_TEST_DIR)
@with_environment
def test_get_xdg_dir_0(monkeypatch):
"""test_get_xdg_dir_0, check xdg_dir"""
monkeypatch.setattr(path, "_writable_dir", lambda path: True)
monkeypatch.setattr(path, "get_home_dir", lambda: "somewhere")
monkeypatch.setattr(os, "name", "posix")
monkeypatch.setattr(sys, "platform", "linux2")
env.pop('IPYTHON_DIR', None)
env.pop('IPYTHONDIR', None)
env.pop('XDG_CONFIG_HOME', None)
assert path.get_xdg_dir() == os.path.join("somewhere", ".config")
@with_environment
def test_get_xdg_dir_1(monkeypatch):
"""test_get_xdg_dir_1, check nonexistent xdg_dir"""
monkeypatch.setattr(path, "get_home_dir", lambda: HOME_TEST_DIR)
monkeypatch.setattr(os, "name", "posix")
monkeypatch.setattr(sys, "platform", "linux2")
env.pop("IPYTHON_DIR", None)
env.pop("IPYTHONDIR", None)
env.pop("XDG_CONFIG_HOME", None)
assert path.get_xdg_dir() is None
@with_environment
def test_get_xdg_dir_2(monkeypatch):
"""test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
monkeypatch.setattr(path, "get_home_dir", lambda: HOME_TEST_DIR)
monkeypatch.setattr(os, "name", "posix")
monkeypatch.setattr(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)
assert path.get_xdg_dir() == cfgdir
@with_environment
def test_get_xdg_dir_3(monkeypatch):
"""test_get_xdg_dir_3, check xdg_dir not used on non-posix systems"""
monkeypatch.setattr(path, "get_home_dir", lambda: HOME_TEST_DIR)
monkeypatch.setattr(os, "name", "nt")
monkeypatch.setattr(sys, "platform", "win32")
env.pop("IPYTHON_DIR", None)
env.pop("IPYTHONDIR", None)
env.pop("XDG_CONFIG_HOME", None)
cfgdir = os.path.join(path.get_home_dir(), ".config")
os.makedirs(cfgdir, exist_ok=True)
assert path.get_xdg_dir() is 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)
assert evaluated_path.lower() == long_path.lower()
@dec.skip_win32
def test_get_long_path_name():
p = path.get_long_path_name("/usr/local")
assert p == "/usr/local"
@dec.skip_win32 # can't create not-user-writable dir on win
@with_environment
def test_not_writable_ipdir():
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", encoding="utf-8").close()
except IOError:
pass
else:
# I can still write to an unwritable dir,
# assume I'm root and skip the test
pytest.skip("I can't create directories that I can't write to")
with pytest.warns(UserWarning, match="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"):
assert path.get_py_filename("foo.py") == "foo.py"
assert path.get_py_filename("foo") == "foo.py"
with make_tempfile("foo"):
assert path.get_py_filename("foo") == "foo"
pytest.raises(IOError, path.get_py_filename, "foo.py")
pytest.raises(IOError, path.get_py_filename, "foo")
pytest.raises(IOError, path.get_py_filename, "foo.py")
true_fn = "foo with spaces.py"
with make_tempfile(true_fn):
assert path.get_py_filename("foo with spaces") == true_fn
assert path.get_py_filename("foo with spaces.py") == true_fn
pytest.raises(IOError, path.get_py_filename, '"foo with spaces.py"')
pytest.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", encoding="utf-8").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.
assert 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]']),
]:
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]']),
]:
self.check_match(patterns, matches)
@pytest.mark.parametrize(
"globstr, unescaped_globstr",
[
(r"\*\[\!\]\?", "*[!]?"),
(r"\\*", r"\*"),
(r"\\\*", r"\*"),
(r"\\a", r"\a"),
(r"\a", r"\a"),
],
)
def test_unescape_glob(globstr, unescaped_globstr):
assert path.unescape_glob(globstr) == unescaped_globstr
@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", encoding="utf-8").close() # touch
with pytest.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", encoding="utf-8") 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):
assert (
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):
assert (
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, "rb") as a_f:
with open(b, "rb") as b_f:
assert 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", encoding="utf-8").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)
assert sorted(os.listdir(self.tempdir.name)) == ["src", "target"]

View File

@@ -0,0 +1,188 @@
"""
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
import pytest
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")
assert path.endswith("ls")
@dec.skip_if_not_win32
def test_find_cmd_pythonw():
"""Try to find pythonw on Windows."""
path = find_cmd('pythonw')
assert path.lower().endswith('pythonw.exe'), path
def test_find_cmd_fail():
"""Make sure that FindCmdError is raised if we can't find the cmd."""
pytest.raises(FindCmdError, find_cmd, "asdfasdf")
@dec.skip_win32
@pytest.mark.parametrize(
"argstr, argv",
[
("hi", ["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.
("h\u01cello", ["h\u01cello"]),
('something "with quotes"', ["something", '"with quotes"']),
],
)
def test_arg_split(argstr, argv):
"""Ensure that argument lines are correctly split like in a shell."""
assert arg_split(argstr) == argv
@dec.skip_if_not_win32
@pytest.mark.parametrize(
"argstr,argv",
[
("hi", ["hi"]),
("hello there", ["hello", "there"]),
("h\u01cello", ["h\u01cello"]),
('something "with quotes"', ["something", "with quotes"]),
],
)
def test_arg_split_win32(argstr, argv):
"""Ensure that argument lines are correctly split like in a shell."""
assert 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(f'{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 pytest.skip("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, f"The process wasn't interrupted. Status: {status}"
)
def test_getoutput(self):
out = getoutput(f'{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(f'{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(f'{python} "{self.fname}"')
self.assertEqual(out, 'on stdout')
self.assertEqual(err, 'on stderr')
self.assertEqual(code, 0)

View File

@@ -0,0 +1,70 @@
# 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
#-----------------------------------------------------------------------------
# our own
import sys
from IPython.utils.PyColorize import Parser
import io
import pytest
@pytest.fixture(scope="module", params=("Linux", "NoColor", "LightBG", "Neutral"))
def style(request):
yield request.param
#-----------------------------------------------------------------------------
# Test functions
#-----------------------------------------------------------------------------
sample = """
def function(arg, *args, kwarg=True, **kwargs):
'''
this is docs
'''
pass is True
False == None
with io.open(ru'unicode', encoding='utf-8'):
raise ValueError("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_parse_sample(style):
"""and test writing to a buffer"""
buf = io.StringIO()
p = Parser(style=style)
p.format(sample, buf)
buf.seek(0)
f1 = buf.read()
assert "ERROR" not in f1
def test_parse_error(style):
p = Parser(style=style)
f1 = p.format(r"\ " if sys.version_info >= (3, 12) else ")", "str")
if style != "NoColor":
assert "ERROR" in f1

View File

@@ -0,0 +1,12 @@
from IPython.utils.shimmodule import ShimModule
import IPython
def test_shimmodule_repr_does_not_fail_on_import_error():
shim_module = ShimModule("shim_module", mirror="mirrored_module_does_not_exist")
repr(shim_module)
def test_shimmodule_repr_forwards_to_module():
shim_module = ShimModule("shim_module", mirror="IPython")
assert repr(shim_module) == repr(IPython)

View File

@@ -0,0 +1,22 @@
# 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 pytest
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())
def test_num_cpus():
with pytest.deprecated_call():
sysinfo.num_cpus()

View File

@@ -0,0 +1,29 @@
#-----------------------------------------------------------------------------
# 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.
#-----------------------------------------------------------------------------
from pathlib import Path
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 Path(name).exists()
file.write(b'test')
assert file.closed
assert not Path(name).exists()
def test_temporary_working_directory():
with TemporaryWorkingDirectory() as directory:
directory_path = Path(directory).resolve()
assert directory_path.exists()
assert Path.cwd().resolve() == directory_path
assert not directory_path.exists()
assert Path.cwd().resolve() != directory_path

View File

@@ -0,0 +1,268 @@
# 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
from pathlib import Path
import pytest
from IPython.utils import text
#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
@pytest.mark.parametrize(
"expected, width, row_first, spread",
(
(
"aaaaa bbbbb ccccc ddddd\n",
80,
False,
False,
),
(
"aaaaa ccccc\nbbbbb ddddd\n",
25,
False,
False,
),
(
"aaaaa ccccc\nbbbbb ddddd\n",
12,
False,
False,
),
(
"aaaaa\nbbbbb\nccccc\nddddd\n",
10,
False,
False,
),
(
"aaaaa bbbbb ccccc ddddd\n",
80,
True,
False,
),
(
"aaaaa bbbbb\nccccc ddddd\n",
25,
True,
False,
),
(
"aaaaa bbbbb\nccccc ddddd\n",
12,
True,
False,
),
(
"aaaaa\nbbbbb\nccccc\nddddd\n",
10,
True,
False,
),
(
"aaaaa bbbbb ccccc ddddd\n",
40,
False,
True,
),
(
"aaaaa ccccc\nbbbbb ddddd\n",
20,
False,
True,
),
(
"aaaaa ccccc\nbbbbb ddddd\n",
12,
False,
True,
),
(
"aaaaa\nbbbbb\nccccc\nddddd\n",
10,
False,
True,
),
),
)
def test_columnize(expected, width, row_first, spread):
"""Basic columnize tests."""
size = 5
items = [l*size for l in 'abcd']
with pytest.warns(PendingDeprecationWarning):
out = text.columnize(
items, displaywidth=width, row_first=row_first, spread=spread
)
assert out == expected
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]
with pytest.warns(PendingDeprecationWarning):
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)
assert longer_line <= displaywidth, (
f"Columnize displayed something lager than displaywidth : {longer_line}\n"
f"longer element : {longer_element}\n"
f"displaywidth : {displaywidth}\n"
f"number of element : {nitems}\n"
f"size of each element : {rand_len}\n"
f"row_first={row_first}\n"
)
@pytest.mark.parametrize("row_first", [True, False])
def test_columnize_medium(row_first):
"""Test with inputs than shouldn't be wider than 80"""
size = 40
items = [l*size for l in 'abc']
with pytest.warns(PendingDeprecationWarning):
out = text.columnize(items, row_first=row_first, displaywidth=80)
assert out == "\n".join(items + [""]), "row_first={0}".format(row_first)
@pytest.mark.parametrize("row_first", [True, False])
def test_columnize_long(row_first):
"""Test columnize with inputs longer than the display window"""
size = 11
items = [l*size for l in 'abc']
with pytest.warns(PendingDeprecationWarning):
out = text.columnize(items, row_first=row_first, displaywidth=size - 1)
assert 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)
assert s == "12 3 hello"
s = f.format(" ".join(["{n//%i}" % i for i in range(1, 8)]), **ns)
assert s == "12 6 4 3 2 2 1"
s = f.format("{[n//i for i in range(1,8)]}", **ns)
assert s == "[12, 6, 4, 3, 2, 2, 1]"
s = f.format("{stuff!s}", **ns)
assert s == ns["stuff"]
s = f.format("{stuff!r}", **ns)
assert s == repr(ns["stuff"])
# Check with unicode:
s = f.format("{u}", **ns)
assert s == ns["u"]
# This decodes in a platform dependent manner, but it shouldn't error out
s = f.format("{b}", **ns)
pytest.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)
assert s == " ['hello', 'there'] "
s = f.format(" {stuff.split()[::-1]} ", **ns)
assert s == " ['there', 'hello'] "
s = f.format("{stuff[::2]}", **ns)
assert s == ns["stuff"][::2]
pytest.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)
assert s == "c +9.869604"
s = f.format("{stuff[slice(1,4)]}", **ns)
assert s == "ell"
s = f.format("{a[:]}", a=[1, 2])
assert 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)
assert s == "12"
s = f.format("$n.real", **ns)
assert s == "12"
s = f.format("$n/{stuff[:5]}", **ns)
assert s == "12/hello"
s = f.format("$n $$HOME", **ns)
assert s == "12 $HOME"
s = f.format("${foo}", foo="HOME")
assert s == "$HOME"
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)"""
assert text.strip_email_quotes(src) == cln
def test_strip_email2():
src = "> > > list()"
cln = "list()"
assert text.strip_email_quotes(src) == cln
def test_LSString():
lss = text.LSString("abc\ndef")
assert lss.l == ["abc", "def"]
assert lss.s == "abc def"
lss = text.LSString(os.getcwd())
assert isinstance(lss.p[0], Path)
def test_SList():
sl = text.SList(["a 11", "b 1", "a 2"])
assert sl.n == "a 11\nb 1\na 2"
assert sl.s == "a 11 b 1 a 2"
assert sl.grep(lambda x: x.startswith("a")) == text.SList(["a 11", "a 2"])
assert sl.fields(0) == text.SList(["a", "b", "a"])
assert sl.sort(field=1, nums=True) == text.SList(["b 1", "a 2", "a 11"])

View File

@@ -0,0 +1,141 @@
"""Tests for tokenutil"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
import pytest
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:])
assert 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)
assert line == ""
assert 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)
assert line == "Two\n"
assert 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)
assert line == "pri"
assert offset == 4
@pytest.mark.parametrize(
"c, token",
zip(
list(range(16, 22)) + list(range(22, 28)),
["int"] * (22 - 16) + ["map"] * (28 - 22),
),
)
def test_multiline_statement(c, token):
cell = """a = (1,
3)
int()
map()
"""
expect_token(token, 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)