本文整理汇总了Python中IPython.utils.tempdir.TemporaryDirectory.cleanup方法的典型用法代码示例。如果您正苦于以下问题:Python TemporaryDirectory.cleanup方法的具体用法?Python TemporaryDirectory.cleanup怎么用?Python TemporaryDirectory.cleanup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类IPython.utils.tempdir.TemporaryDirectory
的用法示例。
在下文中一共展示了TemporaryDirectory.cleanup方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: PickleShareDBTestCase
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class PickleShareDBTestCase(TestCase):
def setUp(self):
self.tempdir = TemporaryDirectory()
def tearDown(self):
self.tempdir.cleanup()
def test_picklesharedb(self):
db = PickleShareDB(self.tempdir.name)
db.clear()
print("Should be empty:", db.items())
db['hello'] = 15
db['aku ankka'] = [1, 2, 313]
db['paths/nest/ok/keyname'] = [1, (5, 46)]
db.hset('hash', 'aku', 12)
db.hset('hash', 'ankka', 313)
self.assertEqual(db.hget('hash', 'aku'), 12)
self.assertEqual(db.hget('hash', 'ankka'), 313)
print("all hashed", db.hdict('hash'))
print(db.keys())
print(db.keys('paths/nest/ok/k*'))
print(dict(db)) # snapsot of whole db
db.uncache() # frees memory, causes re-reads later
# shorthand for accessing deeply nested files
lnk = db.getlink('myobjects/test')
lnk.foo = 2
lnk.bar = lnk.foo + 5
self.assertEqual(lnk.bar, 7)
@skip("Too slow for regular running.")
def test_stress(self):
db = PickleShareDB('~/fsdbtest')
import time
import sys
for i in range(1000):
for j in range(1000):
if i % 15 == 0 and i < 200:
if str(j) in db:
del db[str(j)]
continue
if j % 33 == 0:
time.sleep(0.02)
db[str(j)] = db.get(str(j), []) + \
[(i, j, "proc %d" % os.getpid())]
db.hset('hash', j, db.hget('hash', j, 15) + 1)
print(i, end=' ')
sys.stdout.flush()
if i % 10 == 0:
db.uncache()
示例2: test_extension
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
def test_extension():
tmpdir = TemporaryDirectory()
orig_ipython_dir = _ip.ipython_dir
try:
_ip.ipython_dir = tmpdir.name
nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
_ip.magic("install_ext %s" % url)
_ip.user_ns.pop('arq', None)
invalidate_caches() # Clear import caches
_ip.magic("load_ext daft_extension")
nt.assert_equal(_ip.user_ns['arq'], 185)
_ip.magic("unload_ext daft_extension")
assert 'arq' not in _ip.user_ns
finally:
_ip.ipython_dir = orig_ipython_dir
tmpdir.cleanup()
示例3: FileTestCase
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class FileTestCase(TestContentsManager):
def setUp(self):
self._temp_dir = TemporaryDirectory()
self.td = self._temp_dir.name
self._file_manager = FileContentsManager(root_dir=self.td)
self.contents_manager = HybridContentsManager(
managers={'': self._file_manager}
)
def tearDown(self):
self._temp_dir.cleanup()
def make_dir(self, api_path):
"""make a subdirectory at api_path
override in subclasses if contents are not on the filesystem.
"""
_make_dir(self._file_manager, api_path)
示例4: test_get_ipython_dir_3
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
def test_get_ipython_dir_3():
"""test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist."""
tmphome = TemporaryDirectory()
try:
with patch_get_home_dir(tmphome.name):
os.name = "posix"
env.pop('IPYTHON_DIR', None)
env.pop('IPYTHONDIR', None)
env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
with warnings.catch_warnings(record=True) as w:
ipdir = path.get_ipython_dir()
nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython"))
if sys.platform != 'darwin':
nt.assert_equal(len(w), 1)
nt.assert_in('Moving', str(w[0]))
finally:
tmphome.cleanup()
示例5: test_get_ipython_dir_3
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
def test_get_ipython_dir_3():
"""test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist."""
tmphome = TemporaryDirectory()
try:
with patch_get_home_dir(tmphome.name), \
patch('os.name', 'posix'), \
modified_env({
'IPYTHON_DIR': None,
'IPYTHONDIR': None,
'XDG_CONFIG_HOME': XDG_TEST_DIR,
}), warnings.catch_warnings(record=True) as w:
ipdir = paths.get_ipython_dir()
nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython"))
if sys.platform != 'darwin':
nt.assert_equal(len(w), 1)
nt.assert_in('Moving', str(w[0]))
finally:
tmphome.cleanup()
示例6: TestLinkOrCopy
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestLinkOrCopy(object):
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'])
示例7: TestMagicRunWithPackage
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestMagicRunWithPackage(unittest.TestCase):
def writefile(self, name, content):
path = os.path.join(self.tempdir.name, name)
d = os.path.dirname(path)
if not os.path.isdir(d):
os.makedirs(d)
with open(path, 'w') as f:
f.write(textwrap.dedent(content))
def setUp(self):
self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
"""Temporary valid python package name."""
self.value = int(random.random() * 10000)
self.tempdir = TemporaryDirectory()
self.__orig_cwd = py3compat.getcwd()
sys.path.insert(0, self.tempdir.name)
self.writefile(os.path.join(package, '__init__.py'), '')
self.writefile(os.path.join(package, 'sub.py'), """
x = {0!r}
""".format(self.value))
self.writefile(os.path.join(package, 'relative.py'), """
from .sub import x
""")
self.writefile(os.path.join(package, 'absolute.py'), """
from {0}.sub import x
""".format(package))
def tearDown(self):
os.chdir(self.__orig_cwd)
sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
self.tempdir.cleanup()
def check_run_submodule(self, submodule, opts=''):
_ip.user_ns.pop('x', None)
_ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
self.assertEqual(_ip.user_ns['x'], self.value,
'Variable `x` is not loaded from module `{0}`.'
.format(submodule))
def test_run_submodule_with_absolute_import(self):
self.check_run_submodule('absolute')
def test_run_submodule_with_relative_import(self):
"""Run submodule that has a relative import statement (#2727)."""
self.check_run_submodule('relative')
def test_prun_submodule_with_absolute_import(self):
self.check_run_submodule('absolute', '-p')
def test_prun_submodule_with_relative_import(self):
self.check_run_submodule('relative', '-p')
def with_fake_debugger(func):
@functools.wraps(func)
def wrapper(*args, **kwds):
with tt.monkeypatch(debugger.Pdb, 'run', staticmethod(eval)):
return func(*args, **kwds)
return wrapper
@with_fake_debugger
def test_debug_run_submodule_with_absolute_import(self):
self.check_run_submodule('absolute', '-d')
@with_fake_debugger
def test_debug_run_submodule_with_relative_import(self):
self.check_run_submodule('relative', '-d')
示例8: TestContentsManager
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestContentsManager(TestCase):
def setUp(self):
self._temp_dir = TemporaryDirectory()
self.td = self._temp_dir.name
self.contents_manager = FileContentsManager(
root_dir=self.td,
)
def tearDown(self):
self._temp_dir.cleanup()
def make_dir(self, abs_path, rel_path):
"""make subdirectory, rel_path is the relative path
to that directory from the location where the server started"""
os_path = os.path.join(abs_path, rel_path)
try:
os.makedirs(os_path)
except OSError:
print("Directory already exists: %r" % os_path)
return os_path
def add_code_cell(self, nb):
output = nbformat.new_output("display_data", {'application/javascript': "alert('hi');"})
cell = nbformat.new_code_cell("print('hi')", outputs=[output])
nb.cells.append(cell)
def new_notebook(self):
cm = self.contents_manager
model = cm.new_untitled(type='notebook')
name = model['name']
path = model['path']
full_model = cm.get(path)
nb = full_model['content']
self.add_code_cell(nb)
cm.save(full_model, path)
return nb, name, path
def test_new_untitled(self):
cm = self.contents_manager
# Test in root directory
model = cm.new_untitled(type='notebook')
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertIn('type', model)
self.assertEqual(model['type'], 'notebook')
self.assertEqual(model['name'], 'Untitled.ipynb')
self.assertEqual(model['path'], 'Untitled.ipynb')
# Test in sub-directory
model = cm.new_untitled(type='directory')
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertIn('type', model)
self.assertEqual(model['type'], 'directory')
self.assertEqual(model['name'], 'Untitled Folder')
self.assertEqual(model['path'], 'Untitled Folder')
sub_dir = model['path']
model = cm.new_untitled(path=sub_dir)
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertIn('type', model)
self.assertEqual(model['type'], 'file')
self.assertEqual(model['name'], 'untitled')
self.assertEqual(model['path'], '%s/untitled' % sub_dir)
def test_get(self):
cm = self.contents_manager
# Create a notebook
model = cm.new_untitled(type='notebook')
name = model['name']
path = model['path']
# Check that we 'get' on the notebook we just created
model2 = cm.get(path)
assert isinstance(model2, dict)
self.assertIn('name', model2)
self.assertIn('path', model2)
self.assertEqual(model['name'], name)
self.assertEqual(model['path'], path)
nb_as_file = cm.get(path, content=True, type='file')
self.assertEqual(nb_as_file['path'], path)
self.assertEqual(nb_as_file['type'], 'file')
self.assertEqual(nb_as_file['format'], 'text')
self.assertNotIsInstance(nb_as_file['content'], dict)
nb_as_bin_file = cm.get(path, content=True, type='file', format='base64')
self.assertEqual(nb_as_bin_file['format'], 'base64')
# Test in sub-directory
sub_dir = '/foo/'
self.make_dir(cm.root_dir, 'foo')
model = cm.new_untitled(path=sub_dir, ext='.ipynb')
#.........这里部分代码省略.........
示例9: TestLinkOrCopy
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestLinkOrCopy(object):
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_equals(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_equals(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_equals(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)
示例10: TestNotebookManager
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestNotebookManager(TestCase):
def setUp(self):
self._temp_dir = TemporaryDirectory()
self.td = self._temp_dir.name
self.notebook_manager = FileNotebookManager(
notebook_dir=self.td,
log=logging.getLogger()
)
def tearDown(self):
self._temp_dir.cleanup()
def make_dir(self, abs_path, rel_path):
"""make subdirectory, rel_path is the relative path
to that directory from the location where the server started"""
os_path = os.path.join(abs_path, rel_path)
try:
os.makedirs(os_path)
except OSError:
print("Directory already exists: %r" % os_path)
def add_code_cell(self, nb):
output = current.new_output("display_data", output_javascript="alert('hi');")
cell = current.new_code_cell("print('hi')", outputs=[output])
if not nb.worksheets:
nb.worksheets.append(current.new_worksheet())
nb.worksheets[0].cells.append(cell)
def new_notebook(self):
nbm = self.notebook_manager
model = nbm.create_notebook()
name = model['name']
path = model['path']
full_model = nbm.get_notebook(name, path)
nb = full_model['content']
self.add_code_cell(nb)
nbm.save_notebook(full_model, name, path)
return nb, name, path
def test_create_notebook(self):
nm = self.notebook_manager
# Test in root directory
model = nm.create_notebook()
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertEqual(model['name'], 'Untitled0.ipynb')
self.assertEqual(model['path'], '')
# Test in sub-directory
sub_dir = '/foo/'
self.make_dir(nm.notebook_dir, 'foo')
model = nm.create_notebook(None, sub_dir)
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertEqual(model['name'], 'Untitled0.ipynb')
self.assertEqual(model['path'], sub_dir.strip('/'))
def test_get_notebook(self):
nm = self.notebook_manager
# Create a notebook
model = nm.create_notebook()
name = model['name']
path = model['path']
# Check that we 'get' on the notebook we just created
model2 = nm.get_notebook(name, path)
assert isinstance(model2, dict)
self.assertIn('name', model2)
self.assertIn('path', model2)
self.assertEqual(model['name'], name)
self.assertEqual(model['path'], path)
# Test in sub-directory
sub_dir = '/foo/'
self.make_dir(nm.notebook_dir, 'foo')
model = nm.create_notebook(None, sub_dir)
model2 = nm.get_notebook(name, sub_dir)
assert isinstance(model2, dict)
self.assertIn('name', model2)
self.assertIn('path', model2)
self.assertIn('content', model2)
self.assertEqual(model2['name'], 'Untitled0.ipynb')
self.assertEqual(model2['path'], sub_dir.strip('/'))
def test_update_notebook(self):
nm = self.notebook_manager
# Create a notebook
model = nm.create_notebook()
name = model['name']
path = model['path']
# Change the name in the model for rename
model['name'] = 'test.ipynb'
model = nm.update_notebook(model, name, path)
assert isinstance(model, dict)
#.........这里部分代码省略.........
示例11: TestContentsManager
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestContentsManager(TestCase):
def setUp(self):
self._temp_dir = TemporaryDirectory()
self.td = self._temp_dir.name
self.contents_manager = FileContentsManager(
root_dir=self.td,
)
def tearDown(self):
self._temp_dir.cleanup()
def make_dir(self, api_path):
"""make a subdirectory at api_path
override in subclasses if contents are not on the filesystem.
"""
_make_dir(self.contents_manager, api_path)
def add_code_cell(self, nb):
output = nbformat.new_output("display_data", {'application/javascript': "alert('hi');"})
cell = nbformat.new_code_cell("print('hi')", outputs=[output])
nb.cells.append(cell)
def new_notebook(self):
cm = self.contents_manager
model = cm.new_untitled(type='notebook')
name = model['name']
path = model['path']
full_model = cm.get(path)
nb = full_model['content']
nb['metadata']['counter'] = int(1e6 * time.time())
self.add_code_cell(nb)
cm.save(full_model, path)
return nb, name, path
def test_new_untitled(self):
cm = self.contents_manager
# Test in root directory
model = cm.new_untitled(type='notebook')
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertIn('type', model)
self.assertEqual(model['type'], 'notebook')
self.assertEqual(model['name'], 'Untitled.ipynb')
self.assertEqual(model['path'], 'Untitled.ipynb')
# Test in sub-directory
model = cm.new_untitled(type='directory')
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertIn('type', model)
self.assertEqual(model['type'], 'directory')
self.assertEqual(model['name'], 'Untitled Folder')
self.assertEqual(model['path'], 'Untitled Folder')
sub_dir = model['path']
model = cm.new_untitled(path=sub_dir)
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertIn('type', model)
self.assertEqual(model['type'], 'file')
self.assertEqual(model['name'], 'untitled')
self.assertEqual(model['path'], '%s/untitled' % sub_dir)
def test_get(self):
cm = self.contents_manager
# Create a notebook
model = cm.new_untitled(type='notebook')
name = model['name']
path = model['path']
# Check that we 'get' on the notebook we just created
model2 = cm.get(path)
assert isinstance(model2, dict)
self.assertIn('name', model2)
self.assertIn('path', model2)
self.assertEqual(model['name'], name)
self.assertEqual(model['path'], path)
nb_as_file = cm.get(path, content=True, type='file')
self.assertEqual(nb_as_file['path'], path)
self.assertEqual(nb_as_file['type'], 'file')
self.assertEqual(nb_as_file['format'], 'text')
self.assertNotIsInstance(nb_as_file['content'], dict)
nb_as_bin_file = cm.get(path, content=True, type='file', format='base64')
self.assertEqual(nb_as_bin_file['format'], 'base64')
# Test in sub-directory
sub_dir = '/foo/'
self.make_dir('foo')
model = cm.new_untitled(path=sub_dir, ext='.ipynb')
model2 = cm.get(sub_dir + name)
assert isinstance(model2, dict)
#.........这里部分代码省略.........
示例12: TestContentsManager
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestContentsManager(TestCase):
def setUp(self):
self._temp_dir = TemporaryDirectory()
self.td = self._temp_dir.name
self.contents_manager = FileContentsManager(
root_dir=self.td,
log=logging.getLogger()
)
def tearDown(self):
self._temp_dir.cleanup()
def make_dir(self, abs_path, rel_path):
"""make subdirectory, rel_path is the relative path
to that directory from the location where the server started"""
os_path = os.path.join(abs_path, rel_path)
try:
os.makedirs(os_path)
except OSError:
print("Directory already exists: %r" % os_path)
return os_path
def add_code_cell(self, nb):
output = current.new_output("display_data", output_javascript="alert('hi');")
cell = current.new_code_cell("print('hi')", outputs=[output])
if not nb.worksheets:
nb.worksheets.append(current.new_worksheet())
nb.worksheets[0].cells.append(cell)
def new_notebook(self):
cm = self.contents_manager
model = cm.create_file()
name = model['name']
path = model['path']
full_model = cm.get_model(name, path)
nb = full_model['content']
self.add_code_cell(nb)
cm.save(full_model, name, path)
return nb, name, path
def test_create_file(self):
cm = self.contents_manager
# Test in root directory
model = cm.create_file()
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertEqual(model['name'], 'Untitled0.ipynb')
self.assertEqual(model['path'], '')
# Test in sub-directory
sub_dir = '/foo/'
self.make_dir(cm.root_dir, 'foo')
model = cm.create_file(None, sub_dir)
assert isinstance(model, dict)
self.assertIn('name', model)
self.assertIn('path', model)
self.assertEqual(model['name'], 'Untitled0.ipynb')
self.assertEqual(model['path'], sub_dir.strip('/'))
def test_get(self):
cm = self.contents_manager
# Create a notebook
model = cm.create_file()
name = model['name']
path = model['path']
# Check that we 'get' on the notebook we just created
model2 = cm.get_model(name, path)
assert isinstance(model2, dict)
self.assertIn('name', model2)
self.assertIn('path', model2)
self.assertEqual(model['name'], name)
self.assertEqual(model['path'], path)
# Test in sub-directory
sub_dir = '/foo/'
self.make_dir(cm.root_dir, 'foo')
model = cm.create_file(None, sub_dir)
model2 = cm.get_model(name, sub_dir)
assert isinstance(model2, dict)
self.assertIn('name', model2)
self.assertIn('path', model2)
self.assertIn('content', model2)
self.assertEqual(model2['name'], 'Untitled0.ipynb')
self.assertEqual(model2['path'], sub_dir.strip('/'))
@dec.skip_win32
def test_bad_symlink(self):
cm = self.contents_manager
path = 'test bad symlink'
os_path = self.make_dir(cm.root_dir, path)
file_model = cm.create_file(path=path, ext='.txt')
# create a broken symlink
os.symlink("target", os.path.join(os_path, "bad symlink"))
#.........这里部分代码省略.........
示例13: TestMagicRunWithPackage
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestMagicRunWithPackage(unittest.TestCase):
def writefile(self, name, content):
path = os.path.join(self.tempdir.name, name)
d = os.path.dirname(path)
if not os.path.isdir(d):
os.makedirs(d)
with open(path, 'w') as f:
f.write(textwrap.dedent(content))
def setUp(self):
self.package = package = 'tmp{0}'.format(''.join([random.choice(string.ascii_letters) for i in range(10)]))
"""Temporary (probably) valid python package name."""
self.value = int(random.random() * 10000)
self.tempdir = TemporaryDirectory()
self.__orig_cwd = os.getcwd()
sys.path.insert(0, self.tempdir.name)
self.writefile(os.path.join(package, '__init__.py'), '')
self.writefile(os.path.join(package, 'sub.py'), """
x = {0!r}
""".format(self.value))
self.writefile(os.path.join(package, 'relative.py'), """
from .sub import x
""")
self.writefile(os.path.join(package, 'absolute.py'), """
from {0}.sub import x
""".format(package))
self.writefile(os.path.join(package, 'args.py'), """
import sys
a = " ".join(sys.argv[1:])
""".format(package))
def tearDown(self):
os.chdir(self.__orig_cwd)
sys.path[:] = [p for p in sys.path if p != self.tempdir.name]
self.tempdir.cleanup()
def check_run_submodule(self, submodule, opts=''):
_ip.user_ns.pop('x', None)
_ip.magic('run {2} -m {0}.{1}'.format(self.package, submodule, opts))
self.assertEqual(_ip.user_ns['x'], self.value,
'Variable `x` is not loaded from module `{0}`.'
.format(submodule))
def test_run_submodule_with_absolute_import(self):
self.check_run_submodule('absolute')
def test_run_submodule_with_relative_import(self):
"""Run submodule that has a relative import statement (#2727)."""
self.check_run_submodule('relative')
def test_prun_submodule_with_absolute_import(self):
self.check_run_submodule('absolute', '-p')
def test_prun_submodule_with_relative_import(self):
self.check_run_submodule('relative', '-p')
def with_fake_debugger(func):
@functools.wraps(func)
def wrapper(*args, **kwds):
with patch.object(debugger.Pdb, 'run', staticmethod(eval)):
return func(*args, **kwds)
return wrapper
@with_fake_debugger
def test_debug_run_submodule_with_absolute_import(self):
self.check_run_submodule('absolute', '-d')
@with_fake_debugger
def test_debug_run_submodule_with_relative_import(self):
self.check_run_submodule('relative', '-d')
def test_module_options(self):
_ip.user_ns.pop('a', None)
test_opts = '-x abc -m test'
_ip.run_line_magic('run', '-m {0}.args {1}'.format(self.package, test_opts))
nt.assert_equal(_ip.user_ns['a'], test_opts)
def test_module_options_with_separator(self):
_ip.user_ns.pop('a', None)
test_opts = '-x abc -m test'
_ip.run_line_magic('run', '-m {0}.args -- {1}'.format(self.package, test_opts))
nt.assert_equal(_ip.user_ns['a'], test_opts)
示例14: TestUploadDownload
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestUploadDownload(TestCase):
def setUp(self):
drop_testing_db_tables()
migrate_testing_db()
self.td = TemporaryDirectory()
self.checkpoints = PostgresCheckpoints(
user_id='test',
db_url=TEST_DB_URL,
)
self.contents = FileContentsManager(
root_dir=self.td.name,
checkpoints=self.checkpoints,
)
self.checkpoints.ensure_user()
def tearDown(self):
self.td.cleanup()
def add_markdown_cell(self, path):
# Load and update
model = self.contents.get(path=path)
model['content'].cells.append(
new_markdown_cell('Created by test: ' + path)
)
# Save and checkpoint again.
self.contents.save(model, path=path)
return model
def test_download_checkpoints(self):
"""
Create two checkpoints for two notebooks, then call
download_checkpoints.
Assert that we get the correct version of both notebooks.
"""
self.contents.new({'type': 'directory'}, 'subdir')
paths = ('a.ipynb', 'subdir/a.ipynb')
expected_content = {}
for path in paths:
# Create and checkpoint.
self.contents.new(path=path)
self.contents.create_checkpoint(path)
model = self.add_markdown_cell(path)
self.contents.create_checkpoint(path)
# Assert greater because FileContentsManager creates a checkpoint
# on creation, but this isn't part of the spec.
self.assertGreater(len(self.contents.list_checkpoints(path)), 2)
# Store the content to verify correctness after download.
expected_content[path] = model['content']
with TemporaryDirectory() as td:
download_checkpoints(
self.checkpoints.db_url,
td,
user='test',
)
fm = FileContentsManager(root_dir=td)
root_entries = sorted(m['path'] for m in fm.get('')['content'])
self.assertEqual(root_entries, ['a.ipynb', 'subdir'])
subdir_entries = sorted(
m['path'] for m in fm.get('subdir')['content']
)
self.assertEqual(subdir_entries, ['subdir/a.ipynb'])
for path in paths:
content = fm.get(path)['content']
self.assertEqual(expected_content[path], content)
def test_checkpoint_all(self):
"""
Test that checkpoint_all correctly makes a checkpoint for all files.
"""
paths = populate(self.contents)
original_content_minus_trust = {
# Remove metadata that we expect to have dropped
path: strip_transient(self.contents.get(path)['content'])
for path in paths
}
original_cps = {}
for path in paths:
# Create a checkpoint, then update the file.
original_cps[path] = self.contents.create_checkpoint(path)
self.add_markdown_cell(path)
# Verify that we still have the old version checkpointed.
cp_content = {
path: self.checkpoints.get_notebook_checkpoint(
cp['id'],
path,
)['content']
#.........这里部分代码省略.........
示例15: TestContentsManager
# 需要导入模块: from IPython.utils.tempdir import TemporaryDirectory [as 别名]
# 或者: from IPython.utils.tempdir.TemporaryDirectory import cleanup [as 别名]
class TestContentsManager(TestCase):
def setUp(self):
self._temp_dir = TemporaryDirectory()
self.td = self._temp_dir.name
self.contents_manager = FileContentsManager(root_dir=self.td)
def tearDown(self):
self._temp_dir.cleanup()
@contextmanager
def assertRaisesHTTPError(self, status, msg=None):
msg = msg or "Should have raised HTTPError(%i)" % status
try:
yield
except HTTPError as e:
self.assertEqual(e.status_code, status)
else:
self.fail(msg)
def make_dir(self, api_path):
"""make a subdirectory at api_path
override in subclasses if contents are not on the filesystem.
"""
_make_dir(self.contents_manager, api_path)
def add_code_cell(self, nb):
output = nbformat.new_output("display_data", {"application/javascript": "alert('hi');"})
cell = nbformat.new_code_cell("print('hi')", outputs=[output])
nb.cells.append(cell)
def new_notebook(self):
cm = self.contents_manager
model = cm.new_untitled(type="notebook")
name = model["name"]
path = model["path"]
full_model = cm.get(path)
nb = full_model["content"]
nb["metadata"]["counter"] = int(1e6 * time.time())
self.add_code_cell(nb)
cm.save(full_model, path)
return nb, name, path
def test_new_untitled(self):
cm = self.contents_manager
# Test in root directory
model = cm.new_untitled(type="notebook")
assert isinstance(model, dict)
self.assertIn("name", model)
self.assertIn("path", model)
self.assertIn("type", model)
self.assertEqual(model["type"], "notebook")
self.assertEqual(model["name"], "Untitled.ipynb")
self.assertEqual(model["path"], "Untitled.ipynb")
# Test in sub-directory
model = cm.new_untitled(type="directory")
assert isinstance(model, dict)
self.assertIn("name", model)
self.assertIn("path", model)
self.assertIn("type", model)
self.assertEqual(model["type"], "directory")
self.assertEqual(model["name"], "Untitled Folder")
self.assertEqual(model["path"], "Untitled Folder")
sub_dir = model["path"]
model = cm.new_untitled(path=sub_dir)
assert isinstance(model, dict)
self.assertIn("name", model)
self.assertIn("path", model)
self.assertIn("type", model)
self.assertEqual(model["type"], "file")
self.assertEqual(model["name"], "untitled")
self.assertEqual(model["path"], "%s/untitled" % sub_dir)
def test_get(self):
cm = self.contents_manager
# Create a notebook
model = cm.new_untitled(type="notebook")
name = model["name"]
path = model["path"]
# Check that we 'get' on the notebook we just created
model2 = cm.get(path)
assert isinstance(model2, dict)
self.assertIn("name", model2)
self.assertIn("path", model2)
self.assertEqual(model["name"], name)
self.assertEqual(model["path"], path)
nb_as_file = cm.get(path, content=True, type="file")
self.assertEqual(nb_as_file["path"], path)
self.assertEqual(nb_as_file["type"], "file")
self.assertEqual(nb_as_file["format"], "text")
self.assertNotIsInstance(nb_as_file["content"], dict)
nb_as_bin_file = cm.get(path, content=True, type="file", format="base64")
self.assertEqual(nb_as_bin_file["format"], "base64")
#.........这里部分代码省略.........