本文整理汇总了Python中tempfile.TemporaryDirectory类的典型用法代码示例。如果您正苦于以下问题:Python TemporaryDirectory类的具体用法?Python TemporaryDirectory怎么用?Python TemporaryDirectory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了TemporaryDirectory类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: DiskJobResultTests
class DiskJobResultTests(TestCase):
def setUp(self):
self.scratch_dir = TemporaryDirectory()
def tearDown(self):
self.scratch_dir.cleanup()
def test_smoke(self):
result = DiskJobResult({})
self.assertEqual(str(result), "None")
self.assertEqual(repr(result), "<DiskJobResult outcome:None>")
self.assertIsNone(result.outcome)
self.assertIsNone(result.comments)
self.assertEqual(result.io_log, ())
self.assertIsNone(result.return_code)
def test_everything(self):
result = DiskJobResult({
'outcome': IJobResult.OUTCOME_PASS,
'comments': "it said blah",
'io_log_filename': make_io_log([
(0, 'stdout', b'blah\n')
], self.scratch_dir.name),
'return_code': 0
})
self.assertEqual(str(result), "pass")
self.assertEqual(repr(result), "<DiskJobResult outcome:'pass'>")
self.assertEqual(result.outcome, IJobResult.OUTCOME_PASS)
self.assertEqual(result.comments, "it said blah")
self.assertEqual(result.io_log, ((0, 'stdout', b'blah\n'),))
self.assertEqual(result.return_code, 0)
开发者ID:jds2001,项目名称:ocp-checkbox,代码行数:32,代码来源:test_result.py
示例2: GitRepositoryTest
class GitRepositoryTest(TestCase):
def setUp(self):
self.tmpdir = TemporaryDirectory()
self.repo1 = GitRepository(
self.tmpdir.name,
url="https://github.com/st-tu-dresden/inloop.git",
branch="master"
)
self.repo2 = GitRepository(
self.tmpdir.name,
url="https://github.com/st-tu-dresden/inloop-java-repository-example.git",
branch="master"
)
def tearDown(self):
self.tmpdir.cleanup()
def test_git_operations(self):
self.repo1.synchronize()
self.assertTrue(self.get_path(".git").exists())
self.assertTrue(self.get_path("manage.py").exists())
self.assertEqual(b"", self.run_command("git status -s"))
self.repo2.synchronize()
self.assertFalse(self.get_path("manage.py").exists())
self.assertTrue(self.get_path("build.xml").exists())
self.assertEqual(b"", self.run_command("git status -s"))
def get_path(self, name):
return Path(self.tmpdir.name).joinpath(name)
def run_command(self, command):
return check_output(command.split(), cwd=self.tmpdir.name)
开发者ID:st-tu-dresden,项目名称:inloop,代码行数:33,代码来源:tests.py
示例3: NamedFileInTemporaryDirectory
class NamedFileInTemporaryDirectory(object):
"""Open a file named `filename` in a temporary directory.
This context manager is preferred over :class:`tempfile.NamedTemporaryFile`
when one needs to reopen the file, because on Windows only one handle on a
file can be open at a time. You can close the returned handle explicitly
inside the context without deleting the file, and the context manager will
delete the whole directory when it exits.
Arguments `mode` and `bufsize` are passed to `open`.
Rest of the arguments are passed to `TemporaryDirectory`.
Usage example::
with NamedFileInTemporaryDirectory('myfile', 'wb') as f:
f.write('stuff')
f.close()
# You can now pass f.name to things that will re-open the file
"""
def __init__(self, filename, mode='w+b', bufsize=-1, **kwds):
self._tmpdir = TemporaryDirectory(**kwds)
path = _os.path.join(self._tmpdir.name, filename)
self.file = open(path, mode, bufsize)
def cleanup(self):
self.file.close()
self._tmpdir.cleanup()
__del__ = cleanup
def __enter__(self):
return self.file
def __exit__(self, type, value, traceback):
self.cleanup()
开发者ID:kasalak,项目名称:palindromic,代码行数:35,代码来源:tempdir.py
示例4: test_dcm2niix_run
def test_dcm2niix_run():
dicomDir = os.path.join(TEST_DATA_DIR, "sourcedata", "sub-01")
tmpBase = os.path.join(TEST_DATA_DIR, "tmp")
#tmpDir = TemporaryDirectory(dir=tmpBase)
tmpDir = TemporaryDirectory()
app = Dcm2niix([dicomDir], tmpDir.name)
app.run()
helperDir = os.path.join(
tmpDir.name, DEFAULT.tmpDirName, DEFAULT.helperDir, "*")
ls = sorted(glob(helperDir))
firstMtime = [os.stat(_).st_mtime for _ in ls]
assert 'localizer_20100603125600' in ls[0]
#files should not be change after a rerun
app.run()
secondMtime = [os.stat(_).st_mtime for _ in ls]
assert firstMtime == secondMtime
#files should be change after a forced rerun
app.run(force=True)
thirdMtime = [os.stat(_).st_mtime for _ in ls]
assert firstMtime != thirdMtime
tmpDir.cleanup()
开发者ID:cbedetti,项目名称:Dcm2Bids,代码行数:27,代码来源:test_dcm2niix.py
示例5: NamedFileInTemporaryDirectory
class NamedFileInTemporaryDirectory(object):
def __init__(self, filename, mode='w+b', bufsize=-1, **kwds):
"""
Open a file named `filename` in a temporary directory.
This context manager is preferred over `NamedTemporaryFile` in
stdlib `tempfile` when one needs to reopen the file.
Arguments `mode` and `bufsize` are passed to `open`.
Rest of the arguments are passed to `TemporaryDirectory`.
"""
self._tmpdir = TemporaryDirectory(**kwds)
path = _os.path.join(self._tmpdir.name, filename)
self.file = open(path, mode, bufsize)
def cleanup(self):
self.file.close()
self._tmpdir.cleanup()
__del__ = cleanup
def __enter__(self):
return self.file
def __exit__(self, type, value, traceback):
self.cleanup()
开发者ID:pykomke,项目名称:Kurz_Python_KE,代码行数:28,代码来源:tempdir.py
示例6: test_load_from_file_with_relative_paths
def test_load_from_file_with_relative_paths(self):
"""
When explicitly setting a config file, paths should be relative to the
config file, not the working directory.
"""
config_dir = TemporaryDirectory()
config_fname = os.path.join(config_dir.name, 'mkdocs.yml')
docs_dir = os.path.join(config_dir.name, 'src')
os.mkdir(docs_dir)
config_file = open(config_fname, 'w')
try:
config_file.write("docs_dir: src\nsite_name: MkDocs Test\n")
config_file.flush()
config_file.close()
cfg = base.load_config(config_file=config_file)
self.assertTrue(isinstance(cfg, base.Config))
self.assertEqual(cfg['site_name'], 'MkDocs Test')
self.assertEqual(cfg['docs_dir'], docs_dir)
self.assertEqual(cfg.config_file_path, config_fname)
self.assertIsInstance(cfg.config_file_path, utils.text_type)
finally:
config_dir.cleanup()
开发者ID:mkdocs,项目名称:mkdocs,代码行数:26,代码来源:base_tests.py
示例7: TestStatelog
class TestStatelog(unittest.TestCase):
def setUp(self):
self.tmpdir = TemporaryDirectory()
self.logpath = os.path.join(self.tmpdir.name, 'statelog')
self.nonexist = os.path.join(self.tmpdir.name, 'nonexist')
with open(self.logpath, 'wb') as fw:
fw.write(b'001\n')
fw.write(b'002\n')
def tearDown(self):
self.tmpdir.cleanup()
def test_load(self):
state = pop3.statelog_load(self.logpath)
self.assertEqual(state, {b'001', b'002'})
def test_load_fallback(self):
state = pop3.statelog_load(self.nonexist)
self.assertEqual(state, set())
def test_create(self):
pop3.statelog_save(self.logpath, {b'001', b'002'})
with open(self.logpath, 'rb') as fp:
self.assertEqual(fp.readline(), b'001\n')
self.assertEqual(fp.readline(), b'002\n')
开发者ID:fujimotos,项目名称:eubin,代码行数:26,代码来源:test_pop3.py
示例8: TemporaryRepository
class TemporaryRepository(object):
"""A Git repository initialized in a temporary directory as a context manager.
usage:
with TemporaryRepository() as tempRepo:
print("workdir:", tempRepo.workdir)
print("path:", tempRepo.path)
index = repo.index
index.read()
index.add("...")
index.write()
tree = index.write_tree()
repo.create_commit('HEAD', author, comitter, message, tree, [])
"""
def __init__(self, is_bare=False, clone_from_repo=None):
self.temp_dir = TemporaryDirectory()
if clone_from_repo:
self.repo = clone_repository(clone_from_repo.path, self.temp_dir.name)
else:
self.repo = init_repository(self.temp_dir.name, is_bare)
def __enter__(self):
return self.repo
def __exit__(self, type, value, traceback):
self.temp_dir.cleanup()
开发者ID:AKSW,项目名称:QuitStore,代码行数:27,代码来源:helpers.py
示例9: save_document
def save_document(self):
tempdirectory = TemporaryDirectory()
document = self.generate_document(tempdirectory.name)
if document:
with open(document, 'rb') as f:
self.data_file.save(path.basename(document), File(f))
self.last_update_of_data_file = datetime.datetime.now()
tempdirectory.cleanup()
开发者ID:shackspace,项目名称:shackbureau,代码行数:8,代码来源:models.py
示例10: testInitNotExistingsRepo
def testInitNotExistingsRepo(self):
dir = TemporaryDirectory()
repo = quit.git.Repository(dir.name, create=True)
self.assertFalse(repo.is_bare)
self.assertEqual(len(repo.revisions()), 0)
dir.cleanup()
开发者ID:AKSW,项目名称:QuitStore,代码行数:8,代码来源:test_git.py
示例11: test_dcm2bids
def test_dcm2bids():
tmpBase = os.path.join(TEST_DATA_DIR, "tmp")
#bidsDir = TemporaryDirectory(dir=tmpBase)
bidsDir = TemporaryDirectory()
tmpSubDir = os.path.join(bidsDir.name, DEFAULT.tmpDirName, "sub-01")
shutil.copytree(
os.path.join(TEST_DATA_DIR, "sidecars"),
tmpSubDir)
app = Dcm2bids(
[TEST_DATA_DIR], "01",
os.path.join(TEST_DATA_DIR, "config_test.json"),
bidsDir.name
)
app.run()
layout = BIDSLayout(bidsDir.name, validate=False)
assert layout.get_subjects() == ["01"]
assert layout.get_sessions() == []
assert layout.get_tasks() == ["rest"]
assert layout.get_runs() == [1,2,3]
app = Dcm2bids(
[TEST_DATA_DIR], "01",
os.path.join(TEST_DATA_DIR, "config_test.json"),
bidsDir.name
)
app.run()
fmapFile = os.path.join(
bidsDir.name, "sub-01", "fmap", "sub-01_echo-492_fmap.json")
data = load_json(fmapFile)
fmapMtime = os.stat(fmapFile).st_mtime
assert data["IntendedFor"] == "dwi/sub-01_dwi.nii.gz"
data = load_json(os.path.join(
bidsDir.name, "sub-01", "localizer", "sub-01_run-01_localizer.json"))
assert data["ProcedureStepDescription"] == "Modify by dcm2bids"
#rerun
shutil.rmtree(tmpSubDir)
shutil.copytree(
os.path.join(TEST_DATA_DIR, "sidecars"),
tmpSubDir)
app = Dcm2bids(
[TEST_DATA_DIR], "01",
os.path.join(TEST_DATA_DIR, "config_test.json"),
bidsDir.name
)
app.run()
fmapMtimeRerun = os.stat(fmapFile).st_mtime
assert fmapMtime == fmapMtimeRerun
bidsDir.cleanup()
开发者ID:cbedetti,项目名称:Dcm2Bids,代码行数:58,代码来源:test_dcm2bids.py
示例12: testCloneNotExistingRepo
def testCloneNotExistingRepo(self):
environ["QUIT_SSH_KEY_HOME"] = "./tests/assets/sshkey/"
REMOTE_URL = '[email protected]:AKSW/ThereIsNoQuitStoreRepo.git'
dir = TemporaryDirectory()
with self.assertRaises(Exception) as context:
quit.git.Repository(dir.name, create=True, origin=REMOTE_URL)
dir.cleanup()
开发者ID:AKSW,项目名称:QuitStore,代码行数:9,代码来源:test_git.py
示例13: testCloneRepo
def testCloneRepo(self):
REMOTE_NAME = 'origin'
REMOTE_URL = 'git://github.com/AKSW/QuitStore.example.git'
dir = TemporaryDirectory()
repo = quit.git.Repository(dir.name, create=True, origin=REMOTE_URL)
self.assertTrue(path.exists(path.join(dir.name, 'example.nq')))
self.assertFalse(repo.is_bare)
dir.cleanup()
开发者ID:AKSW,项目名称:QuitStore,代码行数:9,代码来源:test_git.py
示例14: MyTest
class MyTest(TestCase):
def setUp(self):
self.test_dir = TemporaryDirectory()
def tearDown(self):
self.test_dir.cleanup()
# Test methods follow
# 2016.07.08 add
def test_sample(self):
print(self.test_dir)
开发者ID:sasaki-seiji,项目名称:EffectivePython,代码行数:9,代码来源:item_56.py
示例15: testCloneRepoViaSSH
def testCloneRepoViaSSH(self):
environ["QUIT_SSH_KEY_HOME"] = "./tests/assets/sshkey/"
REMOTE_URL = '[email protected]:AKSW/QuitStore.example.git'
dir = TemporaryDirectory()
repo = quit.git.Repository(dir.name, create=True, origin=REMOTE_URL)
self.assertTrue(path.exists(path.join(dir.name, 'example.nt')))
self.assertFalse(repo.is_bare)
dir.cleanup()
开发者ID:AKSW,项目名称:QuitStore,代码行数:10,代码来源:test_git.py
示例16: BaseRecorderTest
class BaseRecorderTest(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
self.original_dir = os.getcwd()
self.temp_dir = TemporaryDirectory()
os.chdir(self.temp_dir.name)
def tearDown(self):
self.temp_dir.cleanup()
os.chdir(self.original_dir)
unittest.TestCase.tearDown(self)
开发者ID:Willianvdv,项目名称:wpull,代码行数:11,代码来源:base_test.py
示例17: CLITestCase
class CLITestCase(unittest.TestCase):
def setUp(self):
self.temp_dir = TemporaryDirectory()
self.output_file_index = 0
def tearDown(self):
self.temp_dir.cleanup()
def exec(self, string):
args = ['-b', self.temp_dir.name]
args.extend(shlex.split(string))
process_args(args)
def list_output(self, string=''):
temp_text_file = os.path.join(self.temp_dir.name,
'temp{}.txt'.format(self.output_file_index))
self.output_file_index += 1
self.exec('list --pipe-to "cat > {}" {}'.format(temp_text_file, string))
with open(temp_text_file) as f:
text = f.read()
return text
def populate(self, num_entries=20):
for i in range(num_entries):
self.exec('new -m "{}"'.format(shlex.quote(random_text())))
def test_list(self):
self.populate(20)
text = self.list_output()
self.assertTrue(len(text.split('\n'))>20*3)
def test_edit(self):
self.exec('new --message "Hello world"')
original_text = self.list_output()
self.exec('edit -m "New text"')
modified_text = self.list_output()
self.assertTrue(re.search('Hello world', original_text))
self.assertTrue(re.search('New text', modified_text))
self.assertTrue(re.sub('Hello world', 'New text', original_text))
def test_search(self):
self.populate(2)
search_string = 'stringthatwontgetgeneratedbyaccident'
self.exec('new -m "hello world\n test text {}inthisentry"'.format(search_string))
self.populate(2)
all_entries = self.list_output()
search_matches = self.list_output(search_string)
self.assertNotEqual(all_entries, search_matches)
self.assertTrue(re.search(search_string, all_entries))
self.assertTrue(re.search(search_string, search_matches))
开发者ID:davidxmoody,项目名称:diary,代码行数:54,代码来源:test_cli.py
示例18: setUp
def setUp(self):
self.dir = TemporaryDirectory()
self.remotedir = TemporaryDirectory()
self.file = NamedTemporaryFile(dir=self.dir.name, delete=False)
self.filename = path.basename(self.file.name)
self.author = Signature('QuitStoreTest', '[email protected]')
self.comitter = Signature('QuitStoreTest', '[email protected]')
# Initialize repository
init_repository(self.dir.name, False)
开发者ID:AKSW,项目名称:QuitStore,代码行数:11,代码来源:test_git.py
示例19: LoadScriptTest
class LoadScriptTest(unittest.TestCase):
def setUp(self):
self.tempdir = TemporaryDirectory()
for filename, contents in self.script_files:
with open(os.path.join(self.tempdir.name, filename), "xt") as f:
f.write(contents)
def tearDown(self):
self.tempdir.cleanup()
开发者ID:Intevation,项目名称:intelmq-mailgen,代码行数:11,代码来源:test_script.py
示例20: testCloneRepoViaSSHNoKeyFiles
def testCloneRepoViaSSHNoKeyFiles(self):
environ["QUIT_SSH_KEY_HOME"] = "./tests/assets/nosshkey/"
if "SSH_AUTH_SOCK" in environ:
del environ["SSH_AUTH_SOCK"]
REMOTE_URL = '[email protected]:AKSW/QuitStore.example.git'
dir = TemporaryDirectory()
with self.assertRaises(Exception) as context:
quit.git.Repository(dir.name, create=True, origin=REMOTE_URL)
dir.cleanup()
开发者ID:AKSW,项目名称:QuitStore,代码行数:11,代码来源:test_git.py
注:本文中的tempfile.TemporaryDirectory类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论