本文整理汇总了Python中twisted.python.filepath.FilePath.makedirs方法的典型用法代码示例。如果您正苦于以下问题:Python FilePath.makedirs方法的具体用法?Python FilePath.makedirs怎么用?Python FilePath.makedirs使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.python.filepath.FilePath
的用法示例。
在下文中一共展示了FilePath.makedirs方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_saveEncryptedDeprecation
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_saveEncryptedDeprecation(self):
"""
Persisting data with encryption is deprecated.
"""
tempDir = FilePath(self.mktemp())
tempDir.makedirs()
persistedPath = tempDir.child('epersisttest.python')
data = b'once I was the king of spain'
persistance = sob.Persistent(data, 'test-data')
persistance.save(filename=persistedPath.path, passphrase=b'some-pass')
# Check deprecation message.
warnings = self.flushWarnings([persistance._saveTemp])
self.assertEqual(1, len(warnings))
self.assertIs(DeprecationWarning, warnings[0]['category'])
self.assertEqual(
'Saving encrypted persisted data is deprecated since '
'Twisted 15.5.0',
warnings[0]['message'])
# Check that data is still valid, even if we are deprecating this
# functionality.
loadedData = sob.load(
persistedPath.path, persistance.style, b'some-pass')
self.assertEqual(data, loadedData)
self.flushWarnings([sob.load])
示例2: test_doFile_withFilenameGenerator
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_doFile_withFilenameGenerator(self):
base = FilePath(self.mktemp())
base.makedirs()
def filenameGenerator(originalFileName, outputExtension):
name = os.path.splitext(FilePath(originalFileName).basename())[0]
return base.child(name + outputExtension).path
templ = dom.parse(open(d['template']))
tree.doFile(self.file, self.linkrel, d['ext'], d['baseurl'], templ, d, filenameGenerator)
self.assertXMLEqual(
"""\
<?xml version="1.0" ?><!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'><html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head><title>Twisted Documentation: My Test Lore Input</title></head>
<body bgcolor="white">
<h1 class="title">My Test Lore Input</h1>
<div class="content">
<span/>
<p>A Body.</p>
</div>
<a href="index.xhtml">Index</a>
</body>
</html>""",
base.child("simple.xhtml").getContent())
示例3: pathEntryTree
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def pathEntryTree(self, tree):
"""
Create some files in a hierarchy, based on a dictionary describing those
files. The resulting hierarchy will be placed onto sys.path for the
duration of the test.
@param tree: A dictionary representing a directory structure. Keys are
strings, representing filenames, dictionary values represent
directories, string values represent file contents.
@return: another dictionary similar to the input, with file content
strings replaced with L{FilePath} objects pointing at where those
contents are now stored.
"""
def makeSomeFiles(pathobj, dirdict):
pathdict = {}
for (key, value) in dirdict.items():
child = pathobj.child(key)
if isinstance(value, bytes):
pathdict[key] = child
child.setContent(value)
elif isinstance(value, dict):
child.createDirectory()
pathdict[key] = makeSomeFiles(child, value)
else:
raise ValueError("only strings and dicts allowed as values")
return pathdict
base = FilePath(self.mktemp().encode("utf-8"))
base.makedirs()
result = makeSomeFiles(base, tree)
# On Python 3, sys.path cannot include byte paths:
self.replaceSysPath([base.path.decode("utf-8")] + sys.path)
self.replaceSysModules(sys.modules.copy())
return result
示例4: test_branch_multi_volumes
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_branch_multi_volumes(self, volumes):
"""
Always show the last checked-out branch for all volumes in ``list``.
"""
tmpdir = FilePath(self.mktemp())
tmpdir.makedirs()
dvol = VoluminousOptions()
for volume, branch in volumes:
dvol.parseOptions(ARGS + ["-p", tmpdir.path, "init", volume])
dvol.parseOptions(ARGS + ["-p", tmpdir.path, "commit", "-m", "hello"])
dvol.parseOptions(ARGS + ["-p", tmpdir.path, "checkout", "-b", branch])
dvol.parseOptions(ARGS + ["-p", tmpdir.path, "list"])
lines = dvol.voluminous.getOutput()[-1].split("\n")
header, rest = lines[0], lines[1:]
expected_volumes = [[volume, branch] for volume, branch in volumes]
# `init` activates the volume, so the last initialized volume is the
# active one.
expected_volumes[-1] = [
'*', expected_volumes[-1][0], expected_volumes[-1][1]]
self.assertEqual(['VOLUME', 'BRANCH', 'CONTAINERS'], header.split())
self.assertEqual(
sorted(expected_volumes),
sorted([line.split() for line in rest]),
)
示例5: test_inputNewVersionWithDefault
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_inputNewVersionWithDefault(self):
"""
L{inputNewVersionWithDefault} should prompt for a new version number,
using C{raw_input}, finding the current version number in a I{NEWS.txt}
file in the grandparent of the C{initPath} of the project it is passed
and supplying that as a default.
"""
projectPath = FilePath(self.mktemp()).child('FakeProject')
projectPath.makedirs()
projectPath.child('NEWS.txt').setContent('0.9.99')
packagePath = projectPath.child('fakeproject')
initPath = packagePath.child('__init__.py')
project = Project(name="FakeProject", initPath=initPath,
package=None, version=None)
def checkPrompt(prompt):
self.assertEqual(prompt, "New version for FakeProject (default 0.9.99)? ")
return ""
self.assertEqual(
inputNewVersionWithDefault(project, raw_input=checkPrompt),
(0, 9, 99))
self.assertEqual(
inputNewVersionWithDefault(project, raw_input=lambda _: "6.7.89"),
(6, 7, 89))
示例6: Tests
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
class Tests(SynchronousTestCase):
def setUp(self):
self.options = options_type()
self.scratch_directory = FilePath(self.mktemp())
self.scratch_directory.makedirs()
self.sample_content = yaml.safe_dump({
u"control-service": {
u"hostname": u"10.0.0.1",
u"port": 4524,
},
u"version": 1,
})
self.config = self.scratch_directory.child('dataset-config.yml')
self.config.setContent(self.sample_content)
def test_default_config_file(self):
"""
The default config file is a FilePath with path
``/etc/flocker/agent.yml``.
"""
self.options.parseOptions([])
self.assertEqual(
self.options["agent-config"],
FilePath("/etc/flocker/agent.yml"))
def test_custom_config_file(self):
"""
The ``--config-file`` command-line option allows configuring
the config file.
"""
self.options.parseOptions(
[b"--agent-config", b"/etc/foo.yml"])
self.assertEqual(
self.options["agent-config"],
FilePath("/etc/foo.yml"))
示例7: test_directory
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_directory(self):
"""
A directory can exist
"""
root = FilePath(self.mktemp())
root.makedirs()
root.chmod(0777)
stdout, stderr, code = self.runScript(['inspect'], json.dumps({
'kind': 'file',
'path': root.path,
}))
data = json.loads(stdout)
self.assertEqual(data['kind'], 'file')
self.assertEqual(data['path'], root.path)
self.assertEqual(data['exists'], True)
self.assertEqual(data['filetype'], 'dir')
self.assertEqual(data['owner'], pwd.getpwuid(os.geteuid()).pw_name)
self.assertEqual(data['group'], grp.getgrgid(os.getegid()).gr_name)
self.assertEqual(data['perms'], '0777')
root.restat()
self.assertEqual(data['ctime'], int(root.statinfo.st_ctime))
self.assertEqual(type(data['ctime']), int)
self.assertEqual(data['mtime'], int(root.statinfo.st_mtime))
self.assertEqual(type(data['mtime']), int)
self.assertEqual(data['atime'], int(root.statinfo.st_atime))
self.assertEqual(type(data['atime']), int)
示例8: test_json_to_yaml
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_json_to_yaml(self):
"""
Running `crossbar convert` with a YAML config file will convert it to
JSON.
"""
cbdir = FilePath(self.mktemp())
cbdir.makedirs()
config_file = cbdir.child("config.json")
config_file.setContent(b"""{
"foo": {
"bar": "spam",
"baz": {
"foo": "cat"
}
}
}""")
cli.run("crossbar",
["convert", "--config={}".format(config_file.path)])
self.assertIn(
("YAML formatted configuration written"),
self.stdout.getvalue())
with open(cbdir.child("config.yaml").path) as f:
self.assertEqual(f.read(), """foo:
bar: spam
baz:
foo: cat
""")
示例9: test_unix_already_listening_cant_delete
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_unix_already_listening_cant_delete(self):
"""
A config with type = "unix" will create an endpoint for a UNIX socket
at the given path, and delete it if required. If it can't delete it, it
will raise an exception.
"""
parent_fp = FilePath("/tmp").child(uuid4().hex)
parent_fp.makedirs()
fp = parent_fp.child(uuid4().hex)
# Something is already there
fp.setContent(b"")
fp.chmod(0o544)
parent_fp.chmod(0o544)
reactor = SelectReactor()
config = {
"type": "unix",
"path": fp.path
}
with self.assertRaises(OSError) as e:
create_listening_endpoint_from_config(config, self.cbdir,
reactor, self.log)
self.assertEqual(e.exception.errno, 13) # Permission Denied
parent_fp.chmod(0o777)
parent_fp.remove()
示例10: MakeCredentialsTests
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
class MakeCredentialsTests(SynchronousTestCase):
def setUp(self):
self.path = FilePath(self.mktemp())
self.path.makedirs()
self.patch(certificate, "_generateKey", lambda: testKey)
def _makeCredentials(self):
return certificate.makeCredentials(self.path, u"[email protected]")
def test_makeCredentials(self):
"""Making credentials creates a key with matching certificate and
writes it to disk under the given path.
"""
self.assertRaises(IOError, certificate.getContextFactory, self.path)
self._makeCredentials()
certificate.getContextFactory(self.path)
def test_makeCredentialsMultipleTimes(self):
"""Attempting to generate credentials when the credentials file
exists already raises OSError.
"""
self.assertRaises(IOError, certificate.getContextFactory, self.path)
self._makeCredentials()
certificate.getContextFactory(self.path)
self.assertRaises(OSError, self._makeCredentials)
certificate.getContextFactory(self.path)
示例11: test_insertImages
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_insertImages(self):
"""
L{formulaeToImages} replaces any elements with the I{latexformula}
class with I{img} elements which refer to external images generated
based on the latex in the original elements.
"""
parent = Element('div')
base = FilePath(self.mktemp())
base.makedirs()
macros = Element('span')
macros.setAttribute('class', 'latexmacros')
text = Text()
text.data = 'foo'
macros.appendChild(text)
parent.appendChild(macros)
formula = Element('span')
formula.setAttribute('class', 'latexformula')
text = Text()
text.data = 'bar'
formula.appendChild(text)
parent.appendChild(formula)
# Avoid actually executing the commands to generate images from the
# latex. It might be nice to have some assertions about what commands
# are executed, or perhaps even execute them and make sure an image
# file is created, but that is a task for another day.
commands = []
formulaeToImages(parent, base.path, _system=commands.append)
self.assertEqual(
parent.toxml(),
'<div><span><br/><img src="latexformula0.png"/><br/></span></div>')
示例12: test_load_error_on_unreadable_key_file
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_load_error_on_unreadable_key_file(self):
"""
A ``PathError`` is raised if the key file path given to
``CertificateAuthority.from_path`` cannot be opened for reading.
"""
path = FilePath(self.mktemp())
path.makedirs()
crt_path = path.child(b"cluster.crt")
crt_file = crt_path.open(b'w')
crt_file.write(b"dummy")
crt_file.close()
key_path = path.child(b"cluster.key")
key_file = key_path.open(b'w')
key_file.write(b"dummy")
key_file.close()
# make file unreadable
key_path.chmod(64)
e = self.assertRaises(
PathError, CertificateAuthority.from_path, path
)
expected = (
b"Private key file {path} could not be opened. "
b"Check file permissions."
).format(path=key_path.path)
self.assertEqual(str(e), expected)
示例13: test_saveKeysha256
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_saveKeysha256(self):
"""
L{_saveKey} will generate key fingerprint in
L{FingerprintFormats.SHA256-BASE64} format if explicitly specified.
"""
base = FilePath(self.mktemp())
base.makedirs()
filename = base.child('id_rsa').path
key = Key.fromString(privateRSA_openssh)
_saveKey(key, {'filename': filename, 'pass': 'passphrase',
'format': 'sha256-base64'})
self.assertEqual(
self.stdout.getvalue(),
"Your identification has been saved in %s\n"
"Your public key has been saved in %s.pub\n"
"The key fingerprint in <FingerprintFormats=SHA256_BASE64> is:\n"
"ryaugIFT0B8ItuszldMEU7q14rG/wj9HkRosMeBWkts=\n" % (
filename,
filename))
self.assertEqual(
key.fromString(
base.child('id_rsa').getContent(), None, 'passphrase'),
key)
self.assertEqual(
Key.fromString(base.child('id_rsa.pub').getContent()),
key.public())
示例14: test_saveKeyECDSA
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_saveKeyECDSA(self):
"""
L{_saveKey} writes the private and public parts of a key to two
different files and writes a report of this to standard out.
Test with ECDSA key.
"""
base = FilePath(self.mktemp())
base.makedirs()
filename = base.child('id_ecdsa').path
key = Key.fromString(privateECDSA_openssh)
_saveKey(key, {'filename': filename, 'pass': 'passphrase',
'format': 'md5-hex'})
self.assertEqual(
self.stdout.getvalue(),
"Your identification has been saved in %s\n"
"Your public key has been saved in %s.pub\n"
"The key fingerprint in <FingerprintFormats=MD5_HEX> is:\n"
"e2:3b:e8:1c:f8:c9:c7:de:8b:c0:00:68:2e:c9:2c:8a\n" % (
filename,
filename))
self.assertEqual(
key.fromString(
base.child('id_ecdsa').getContent(), None, 'passphrase'),
key)
self.assertEqual(
Key.fromString(base.child('id_ecdsa.pub').getContent()),
key.public())
示例15: test_load_error_on_unreadable_key_file
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import makedirs [as 别名]
def test_load_error_on_unreadable_key_file(self):
"""
A ``PathError`` is raised if the key file path given to
``UserCredential.from_path`` cannot be opened for reading.
"""
path = FilePath(self.mktemp())
path.makedirs()
crt_path = path.child(self.cert_file_name)
crt_file = crt_path.open(b'w')
crt_file.write(b"dummy")
crt_file.close()
key_path = path.child(self.key_file_name)
key_file = key_path.open(b'w')
key_file.write(b"dummy")
key_file.close()
# make file unreadable
key_path.chmod(0o100)
e = self.assertRaises(
PathError, cls.from_path,
path, **kwargs
)
expected = (
"Private key file could not be opened. "
"Permission denied {path}"
).format(path=key_path.path)
self.assertEqual(str(e), expected)