当前位置: 首页>>代码示例>>Python>>正文


Python FilePath.setContent方法代码示例

本文整理汇总了Python中twisted.python.filepath.FilePath.setContent方法的典型用法代码示例。如果您正苦于以下问题:Python FilePath.setContent方法的具体用法?Python FilePath.setContent怎么用?Python FilePath.setContent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.python.filepath.FilePath的用法示例。


在下文中一共展示了FilePath.setContent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: _configure

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
    def _configure(self, config_yml, dockerArgs={}, dockerOnSocket=False,
            realDockerSocket=False, powerstripPort=0, nullAdapter=False):
        if not realDockerSocket:
            self.dockerAPI = testtools.FakeDockerServer(**dockerArgs)
            if dockerOnSocket:
                self.socketPath = self.mktemp()
                self.dockerServer = reactor.listenUNIX(self.socketPath, self.dockerAPI)
            else:
                self.dockerServer = reactor.listenTCP(0, self.dockerAPI)
                self.dockerPort = self.dockerServer.getHost().port
        else:
            # NB: only supports real docker on socket (not tcp) at the
            # moment
            assert dockerOnSocket, ("must pass dockerOnSocket=True "
                        "if specifying realDockerSocket")
            self.socketPath = realDockerSocket

        self.config = PluginConfiguration()
        tmp = self.mktemp()
        self.config._default_file = tmp
        fp = FilePath(tmp)
        fp.setContent(config_yml)
        self.parser = EndpointParser(self.config)
        if dockerOnSocket:
            self.proxyAPI = powerstrip.ServerProtocolFactory(
                    dockerSocket=self.socketPath, config=self.config)
        else:
            self.proxyAPI = powerstrip.ServerProtocolFactory(
                                dockerAddr="127.0.0.1", dockerPort=self.dockerPort,
                                config=self.config)
        self.proxyServer = reactor.listenTCP(powerstripPort, self.proxyAPI)
        self.proxyPort = self.proxyServer.getHost().port
开发者ID:mbit-cloud,项目名称:powerstrip,代码行数:34,代码来源:testtools.py

示例2: test_generateRecordsDefaultPatterns

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
 def test_generateRecordsDefaultPatterns(self):
     """
     L{LoadSimulator.fromCommandLine} takes an account loader from the
     config file and uses it to generate user records for use in the
     simulation.
     """
     config = VALID_CONFIG.copy()
     config["accounts"] = {
         "loader": "contrib.performance.loadtest.sim.generateRecords",
         "params": {
             "count": 2
         },
     }
     configpath = FilePath(self.mktemp())
     configpath.setContent(writePlistToString(config))
     sim = LoadSimulator.fromCommandLine(['--config', configpath.path],
                                         StringIO())
     self.assertEqual(2, len(sim.records))
     self.assertEqual(sim.records[0].uid, 'user1')
     self.assertEqual(sim.records[0].password, 'user1')
     self.assertEqual(sim.records[0].commonName, 'User 1')
     self.assertEqual(sim.records[0].email, '[email protected]')
     self.assertEqual(sim.records[1].uid, 'user2')
     self.assertEqual(sim.records[1].password, 'user2')
     self.assertEqual(sim.records[1].commonName, 'User 2')
     self.assertEqual(sim.records[1].email, '[email protected]')
开发者ID:redtailtech,项目名称:calendarserver,代码行数:28,代码来源:test_sim.py

示例3: test_twistd

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
 def test_twistd(self):
     """
     Should run twistd with the given arguments
     """
     runner = Runner()
     fake_twistd = FilePath(self.mktemp())
     fake_twistd.setContent('#!%s\n'
                             'import sys, os\n'
                             'print " ".join(sys.argv[1:])\n'
                             'print os.environ["FOO"]\n'
                             'print os.path.abspath(os.curdir)\n'
                             'sys.stdout.flush()\n'
                             'sys.stderr.write("error\\n")\n'
                             'print "stdout"\n'
                             'sys.exit(4)\n' % sys.executable)
     fake_twistd.chmod(0777)
     runner._twistdBin = lambda: fake_twistd.path
     
     path = FilePath(self.mktemp())
     path.makedirs()
     
     d = runner.twistd(['foo', 'bar', 'baz'], env={'FOO': 'foo value'},
                   path=path.path)
     def check(result):
         out, err, code = result
         self.assertEqual(code, 4)
         self.assertEqual(out, 
             'foo bar baz\n'
             'foo value\n'
             '%s\n'
             'stdout\n' % path.path)
         self.assertEqual(err, 'error\n')
     return d.addCallback(check)
开发者ID:iffy,项目名称:grace,代码行数:35,代码来源:test_cli.py

示例4: test_generateRecordsNonDefaultPatterns

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
 def test_generateRecordsNonDefaultPatterns(self):
     """
     L{LoadSimulator.fromCommandLine} takes an account loader from the
     config file and uses it to generate user records for use in the
     simulation.
     """
     config = VALID_CONFIG.copy()
     config["accounts"] = {
         "loader": "contrib.performance.loadtest.sim.generateRecords",
         "params": {
             "count": 3,
             "uidPattern": "USER%03d",
             "passwordPattern": "PASSWORD%03d",
             "namePattern": "Test User %03d",
             "emailPattern": "USER%[email protected]",
         },
     }
     configpath = FilePath(self.mktemp())
     configpath.setContent(writePlistToString(config))
     sim = LoadSimulator.fromCommandLine(['--config', configpath.path],
                                         StringIO())
     self.assertEqual(3, len(sim.records))
     self.assertEqual(sim.records[0].uid, 'USER001')
     self.assertEqual(sim.records[0].password, 'PASSWORD001')
     self.assertEqual(sim.records[0].commonName, 'Test User 001')
     self.assertEqual(sim.records[0].email, '[email protected]')
     self.assertEqual(sim.records[2].uid, 'USER003')
     self.assertEqual(sim.records[2].password, 'PASSWORD003')
     self.assertEqual(sim.records[2].commonName, 'Test User 003')
     self.assertEqual(sim.records[2].email, '[email protected]')
开发者ID:redtailtech,项目名称:calendarserver,代码行数:32,代码来源:test_sim.py

示例5: test_interface

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
    def test_interface(self, cert_and_key):
        """
        ``makeService`` returns an object that provides ``IService``.
        """
        scratch = FilePath(self.mktemp())
        scratch.makedirs()

        cert, key = pem.parse(cert_and_key)

        config = write_kubernetes_configuration(
            scratch, cert, key,
        )

        access_key_id_path = FilePath(self.mktemp())
        access_key_id_path.setContent(b"foo")
        secret_access_key_path = FilePath(self.mktemp())
        secret_access_key_path.setContent(b"bar")
        options = Options()
        options.parseOptions([
            b"--domain", b"s4.example.com",
            b"--kubernetes-namespace", b"testing",
            b"--endpoint", b"http://localhost:8000/",
            b"--aws-access-key-id-path", access_key_id_path.path,
            b"--aws-secret-access-key-path", secret_access_key_path.path,
            b"--introducer-image", b"introducer",
            b"--storageserver-image", b"storageserver",
            b"--kubernetes", b"kubernetes",
            b"--k8s-context", u"testing",
            b"--k8s-config", config.path,
        ])
        service = makeService(options)
        verifyObject(IService, service)
开发者ID:LeastAuthority,项目名称:leastauthority.com,代码行数:34,代码来源:test_subscription_converger.py

示例6: test_single_run

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
    def test_single_run(self):
        """
        Running for the first time successfully reads and parses the configuration.
        """
        yml = """endpoints:
  # adapters are applied in order
  "POST /*/containers/create":
    pre: [flocker, weave]
    post: [weave, flocker]
  "DELETE /*/containers/*":
    pre: [flocker, weave]
    post: [weave, flocker]
adapters:
  flocker: http://flocker/flocker-adapter
  weave: http://weave/weave-adapter"""
        tmp = self.mktemp()
        self.config._default_file = tmp
        fp = FilePath(tmp)
        fp.setContent(yml)
        
        self.config.read_and_parse()

        self.assertEquals((self.config._endpoints, self.config._adapters), ({
                "POST /*/containers/create": {
                    "pre": ["flocker", "weave"],
                    "post": ["weave", "flocker"],
                },
                "DELETE /*/containers/*": {
                    "pre": ["flocker", "weave"],
                    "post": ["weave", "flocker"],
                },
            }, {
                "flocker": "http://flocker/flocker-adapter",
                "weave": "http://weave/weave-adapter",
            }))
开发者ID:mbit-cloud,项目名称:powerstrip,代码行数:37,代码来源:test_config.py

示例7: test_createSSLPortInconsistentCertificateAndKeyFiles

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
    def test_createSSLPortInconsistentCertificateAndKeyFiles(self):
        """
        If different values are specified for the certificate file and the
        private key file when creating an SSL port with I{axiomatic port
        create}, a short error message is written to standard output.

        This reflects an implementation limitation which may be lifted in the
        future.
        """
        certPath = FilePath(self.mktemp())
        certPath.setContent(CERTIFICATE_DATA)
        keyPath = FilePath(self.mktemp())
        keyPath.setContent(PRIVATEKEY_DATA)

        store = Store()
        factory = DummyFactory(store=store)
        self.assertFailStatus(
            1, self._makeConfig(store),
            ["create",
             "--strport", "ssl:8443:privateKey=" + keyPath.path +
             ":certKey=" + certPath.path,
             "--factory-identifier", str(factory.storeID)])
        self.assertEqual(
            "You must specify the same file for certKey and privateKey.\n",
            sys.stdout.getvalue())
        self.assertEqual(store.query(SSLPort).count(), 0)
开发者ID:rcarmo,项目名称:divmod.org,代码行数:28,代码来源:test_port.py

示例8: test_loadPopulationParameters

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
    def test_loadPopulationParameters(self):
        """
        Client weights and profiles are loaded from the [clients]
        section of the configuration file specified.
        """
        config = FilePath(self.mktemp())
        config.setContent(writePlistToString({
                    "clients": [{
                            "software": "contrib.performance.loadtest.ical.OS_X_10_6",
                            "params": {"foo": "bar"},
                            "profiles": [{
                                    "params": {
                                        "interval": 25,
                                        "eventStartDistribution": {
                                            "type": "contrib.performance.stats.NormalDistribution",
                                            "params": {
                                                "mu": 123,
                                                "sigma": 456,
                                                }}},
                                    "class": "contrib.performance.loadtest.profiles.Eventer"}],
                            "weight": 3,
                            }]}))

        sim = LoadSimulator.fromCommandLine(
            ['--config', config.path, '--clients', config.path]
        )
        expectedParameters = PopulationParameters()
        expectedParameters.addClient(
            3, ClientType(OS_X_10_6, {"foo": "bar"}, [ProfileType(Eventer, {
                            "interval": 25,
                            "eventStartDistribution": NormalDistribution(123, 456)})]))
        self.assertEquals(sim.parameters, expectedParameters)
开发者ID:svn2github,项目名称:calendarserver-raw,代码行数:34,代码来源:test_sim.py

示例9: test_parseFileAndReportMismatchedTags

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
    def test_parseFileAndReportMismatchedTags(self):
        """
        If the contents of the file passed to L{tree.parseFileAndReport}
        contain a mismatched tag, L{process.ProcessingFailure} is raised
        indicating the location of the open and close tags which were
        mismatched.
        """
        path = FilePath(self.mktemp())
        path.setContent('  <foo>\n\n  </bar>')

        err = self.assertRaises(
            process.ProcessingFailure, tree.parseFileAndReport, path.path)
        self.assertEqual(
            str(err),
            "mismatched close tag at line 3, column 4; expected </foo> "
            "(from line 1, column 2)")

        # Test a case which requires involves proper close tag handling.
        path.setContent('<foo><bar></bar>\n  </baz>')

        err = self.assertRaises(
            process.ProcessingFailure, tree.parseFileAndReport, path.path)
        self.assertEqual(
            str(err),
            "mismatched close tag at line 2, column 4; expected </foo> "
            "(from line 1, column 0)")
开发者ID:0004c,项目名称:VTK,代码行数:28,代码来源:test_lore.py

示例10: test_file

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
 def test_file(self):
     """
     An existing file has these attributes
     """
     root = FilePath(self.mktemp())
     root.setContent('the content')
     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'], 'file')
     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)
     
     self.assertEqual(data['sha1'], sha1('the content').hexdigest())
     self.assertEqual(data['size'], len('the content'))
开发者ID:hagna,项目名称:mold,代码行数:33,代码来源:test_file.py

示例11: test_addPyListings

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
    def test_addPyListings(self):
        """
        L{tree.addPyListings} accepts a document with nodes with their I{class}
        attribute set to I{py-listing} and replaces those nodes with Python
        source listings from the file given by the node's I{href} attribute.
        """
        listingPath = FilePath(self.mktemp())
        listingPath.setContent('def foo():\n    pass\n')

        parent = dom.Element('div')
        listing = dom.Element('a')
        listing.setAttribute('href', listingPath.basename())
        listing.setAttribute('class', 'py-listing')
        parent.appendChild(listing)

        tree.addPyListings(parent, listingPath.dirname())

        expected = """\
<div><div class="py-listing"><pre><p class="py-linenumber">1
2
</p><span class="py-src-keyword">def</span> <span class="py-src-identifier">foo</span>():
    <span class="py-src-keyword">pass</span>
</pre><div class="caption"> - <a href="temp"><span class="filename">temp</span></a></div></div></div>"""

        self.assertEqual(parent.toxml(), expected)
开发者ID:0004c,项目名称:VTK,代码行数:27,代码来源:test_lore.py

示例12: test_createSSLPort

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
 def test_createSSLPort(self):
     """
     If a given valid strport description of an SSL port and the storeID of
     an extant factory, I{axiomatic port create} creates a new L{SSLPort}
     with the specified configuration and referring to that factory.  The
     certificate file specified is copied to a path inside the Store's files
     directory.  The port is also powered up on the store for L{IService}.
     """
     pemPath = FilePath(self.mktemp())
     pemPath.setContent(CERTIFICATE_DATA + PRIVATEKEY_DATA)
     store = Store(filesdir=self.mktemp())
     factory = DummyFactory(store=store)
     self.assertSuccessStatus(
         self._makeConfig(store),
         ["create", "--strport",
          "ssl:8443:certKey=" + pemPath.path +
          ":privateKey=" + pemPath.path,
          "--factory-identifier", str(factory.storeID)])
     self.assertEqual("Created.\n", sys.stdout.getvalue())
     [ssl] = list(store.query(SSLPort))
     self.assertEqual(ssl.portNumber, 8443)
     self.assertEqual(
         ssl.certificatePath.getContent(),
         CERTIFICATE_DATA + PRIVATEKEY_DATA)
     self.assertIdentical(ssl.factory, factory)
     self.assertEqual(
         pemPath.getContent(), CERTIFICATE_DATA + PRIVATEKEY_DATA)
     self.assertEqual(list(store.interfacesFor(ssl)), [IService])
开发者ID:rcarmo,项目名称:divmod.org,代码行数:30,代码来源:test_port.py

示例13: test_loadDefaultAccountsFromFile

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
 def test_loadDefaultAccountsFromFile(self):
     """
     L{LoadSimulator.fromCommandLine} takes an account loader (with
     empty path)from the config file and uses it to create user
     records for use in the simulation.
     """
     config = VALID_CONFIG.copy()
     config["accounts"] = {
         "loader": "contrib.performance.loadtest.sim.recordsFromCSVFile",
         "params": {
             "path": ""
         },
     }
     configpath = FilePath(self.mktemp())
     configpath.setContent(writePlistToString(config))
     sim = LoadSimulator.fromCommandLine(['--config', configpath.path],
                                         StringIO())
     self.assertEqual(99, len(sim.records))
     self.assertEqual(sim.records[0].uid, 'user01')
     self.assertEqual(sim.records[0].password, 'user01')
     self.assertEqual(sim.records[0].commonName, 'User 01')
     self.assertEqual(sim.records[0].email, '[email protected]')
     self.assertEqual(sim.records[98].uid, 'user99')
     self.assertEqual(sim.records[98].password, 'user99')
     self.assertEqual(sim.records[98].commonName, 'User 99')
     self.assertEqual(sim.records[98].email, '[email protected]')
开发者ID:redtailtech,项目名称:calendarserver,代码行数:28,代码来源:test_sim.py

示例14: _send_configuration

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
    def _send_configuration(self,
                            application_config_yaml=COMPLEX_APPLICATION_YAML,
                            deployment_config_yaml=COMPLEX_DEPLOYMENT_YAML):
        """
        Run ``flocker-deploy`` against the API server.

        :param application_config: Application configuration dictionary.
        :param deployment_config: Deployment configuration dictionary.

        :return: ``Deferred`` that fires with a tuple (stdout, stderr,
            exit code).
        """
        app_config = FilePath(self.mktemp())
        app_config.setContent(safe_dump(application_config_yaml))
        deployment_config = FilePath(self.mktemp())
        deployment_config.setContent(safe_dump(deployment_config_yaml))
        # This duplicates some code in the acceptance tests...
        # https://clusterhq.atlassian.net/browse/FLOC-1904
        return getProcessOutputAndValue(
            b"flocker-deploy", [
                b"--certificates-directory", self.certificate_path.path,
                b"--port",
                unicode(self.port_number).encode("ascii"), b"localhost",
                deployment_config.path, app_config.path
            ],
            env=environ)
开发者ID:wangbinxiang,项目名称:flocker,代码行数:28,代码来源:test_deploy_script.py

示例15: test_loadAccountsFromFile

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import setContent [as 别名]
 def test_loadAccountsFromFile(self):
     """
     L{LoadSimulator.fromCommandLine} takes an account loader from the
     config file and uses it to create user records for use in the
     simulation.
     """
     accounts = FilePath(self.mktemp())
     accounts.setContent("foo,bar,baz,quux\nfoo2,bar2,baz2,quux2\n")
     config = VALID_CONFIG.copy()
     config["accounts"] = {
         "loader": "contrib.performance.loadtest.sim.recordsFromCSVFile",
         "params": {
             "path": accounts.path
         },
     }
     configpath = FilePath(self.mktemp())
     configpath.setContent(writePlistToString(config))
     io = StringIO()
     sim = LoadSimulator.fromCommandLine(['--config', configpath.path], io)
     self.assertEquals(io.getvalue(), "Loaded 2 accounts.\n")
     self.assertEqual(2, len(sim.records))
     self.assertEqual(sim.records[0].uid, 'foo')
     self.assertEqual(sim.records[0].password, 'bar')
     self.assertEqual(sim.records[0].commonName, 'baz')
     self.assertEqual(sim.records[0].email, 'quux')
     self.assertEqual(sim.records[1].uid, 'foo2')
     self.assertEqual(sim.records[1].password, 'bar2')
     self.assertEqual(sim.records[1].commonName, 'baz2')
     self.assertEqual(sim.records[1].email, 'quux2')
开发者ID:redtailtech,项目名称:calendarserver,代码行数:31,代码来源:test_sim.py


注:本文中的twisted.python.filepath.FilePath.setContent方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。