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


Python FilePath.sibling方法代码示例

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


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

示例1: test_file_logging_rotation_5_files

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import sibling [as 别名]
    def test_file_logging_rotation_5_files(self):
        """
        Only 5 logfiles are kept.
        """
        logfile = FilePath(self.mktemp()).child('foo.log')
        logfile.parent().makedirs()
        # This file will become foo.log.1
        with logfile.open('w') as f:
            f.write(b'0')
            f.truncate(int(MiB(100).to_Byte().value))
        # These file extensions will be incremented
        for i in range(1, 5):
            sibling = logfile.sibling(logfile.basename() + u'.' + unicode(i))
            with sibling.open('w') as f:
                f.write(bytes(i))

        d = self.run_script(EliotScript, options=['--logfile', logfile.path])

        def verify_logfiles(stdout_messages, logfile):
            logfile_dir = logfile.parent()
            self.assertEqual(
                # The contents of the files will now be an integer one less
                # than the integer in the file name.
                map(bytes, range(0, 4)),
                list(
                    logfile_dir.child('foo.log.{}'.format(i)).open().read(1)
                    for i
                    in range(1, 5)
                )
            )
        d.addCallback(verify_logfiles, logfile=logfile)

        return d
开发者ID:gitstorage,项目名称:flocker,代码行数:35,代码来源:test_script.py

示例2: test_renamedSource

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import sibling [as 别名]
    def test_renamedSource(self):
        """
        Warnings emitted by a function defined in a file which has been renamed
        since it was initially compiled can still be flushed.

        This is testing the code which specifically supports working around the
        unfortunate behavior of CPython to write a .py source file name into
        the .pyc files it generates and then trust that it is correct in
        various places.  If source files are renamed, .pyc files may not be
        regenerated, but they will contain incorrect filenames.
        """
        package = FilePath(self.mktemp().encode('utf-8')).child(b'twisted_private_helper')
        package.makedirs()
        package.child(b'__init__.py').setContent(b'')
        package.child(b'module.py').setContent(b'''
import warnings
def foo():
    warnings.warn("oh no")
''')
        pathEntry = package.parent().path.decode('utf-8')
        sys.path.insert(0, pathEntry)
        self.addCleanup(sys.path.remove, pathEntry)

        # Import it to cause pycs to be generated
        from twisted_private_helper import module

        # Clean up the state resulting from that import; we're not going to use
        # this module, so it should go away.
        del sys.modules['twisted_private_helper']
        del sys.modules[module.__name__]

        # Some Python versions have extra state related to the just
        # imported/renamed package.  Clean it up too.  See also
        # http://bugs.python.org/issue15912
        try:
            from importlib import invalidate_caches
        except ImportError:
            pass
        else:
            invalidate_caches()

        # Rename the source directory
        package.moveTo(package.sibling(b'twisted_renamed_helper'))

        # Import the newly renamed version
        from twisted_renamed_helper import module
        self.addCleanup(sys.modules.pop, 'twisted_renamed_helper')
        self.addCleanup(sys.modules.pop, module.__name__)

        # Generate the warning
        module.foo()

        # Flush it
        self.assertEqual(len(self.flushWarnings([module.foo])), 1)
开发者ID:alfonsjose,项目名称:international-orders-app,代码行数:56,代码来源:test_warning.py

示例3: TitleExtractionTests

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import sibling [as 别名]
class TitleExtractionTests(unittest.TestCase):
    """
    Tests for title extraction in L{eridanusstd.linkdb}.
    """
    def setUp(self):
        self.path = FilePath(__file__)


    def test_extractTitle(self):
        data = self.path.sibling('index.html').open().read()
        self.assertEquals(
            linkdb._extractTitle(data),
            u'Google')
开发者ID:mithrandi,项目名称:eridanus,代码行数:15,代码来源:test_linkdb.py

示例4: TwitterTestsMixin

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import sibling [as 别名]
class TwitterTestsMixin(object):
    """
    Mixin for Twitter tests.
    """
    def setUp(self):
        self.path = FilePath(__file__)
        self.store = Store()
        self.plugin = twitter_plugin.Twitter(store=self.store)


    def objectify(self, filename):
        """
        Read XML, from a file, and parse it with C{lxml.objectify}.
        """
        return lxml.objectify.fromstring(
            self.path.sibling(filename).getContent())
开发者ID:mithrandi,项目名称:eridanus,代码行数:18,代码来源:test_twitter.py

示例5: WarnAboutFunctionTests

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import sibling [as 别名]
class WarnAboutFunctionTests(SynchronousTestCase):
    """
    Tests for L{twisted.python.deprecate.warnAboutFunction} which allows the
    callers of a function to issue a C{DeprecationWarning} about that function.
    """
    def setUp(self):
        """
        Create a file that will have known line numbers when emitting warnings.
        """
        self.package = FilePath(self.mktemp().encode("utf-8")
                                ).child(b'twisted_private_helper')
        self.package.makedirs()
        self.package.child(b'__init__.py').setContent(b'')
        self.package.child(b'module.py').setContent(b'''
"A module string"

from twisted.python import deprecate

def testFunction():
    "A doc string"
    a = 1 + 2
    return a

def callTestFunction():
    b = testFunction()
    if b == 3:
        deprecate.warnAboutFunction(testFunction, "A Warning String")
''')
        # Python 3 doesn't accept bytes in sys.path:
        packagePath = self.package.parent().path.decode("utf-8")
        sys.path.insert(0, packagePath)
        self.addCleanup(sys.path.remove, packagePath)

        modules = sys.modules.copy()
        self.addCleanup(
            lambda: (sys.modules.clear(), sys.modules.update(modules)))

        # On Windows on Python 3, most FilePath interactions produce
        # DeprecationWarnings, so flush them here so that they don't interfere
        # with the tests.
        if platform.isWindows() and _PY3:
            self.flushWarnings()


    def test_warning(self):
        """
        L{deprecate.warnAboutFunction} emits a warning the file and line number
        of which point to the beginning of the implementation of the function
        passed to it.
        """
        def aFunc():
            pass
        deprecate.warnAboutFunction(aFunc, 'A Warning Message')
        warningsShown = self.flushWarnings()
        filename = __file__
        if filename.lower().endswith('.pyc'):
            filename = filename[:-1]
        self.assertSamePath(
            FilePath(warningsShown[0]["filename"]), FilePath(filename))
        self.assertEqual(warningsShown[0]["message"], "A Warning Message")


    def test_warningLineNumber(self):
        """
        L{deprecate.warnAboutFunction} emits a C{DeprecationWarning} with the
        number of a line within the implementation of the function passed to it.
        """
        from twisted_private_helper import module
        module.callTestFunction()
        warningsShown = self.flushWarnings()
        self.assertSamePath(
            FilePath(warningsShown[0]["filename"].encode("utf-8")),
            self.package.sibling(b'twisted_private_helper').child(b'module.py'))
        # Line number 9 is the last line in the testFunction in the helper
        # module.
        self.assertEqual(warningsShown[0]["lineno"], 9)
        self.assertEqual(warningsShown[0]["message"], "A Warning String")
        self.assertEqual(len(warningsShown), 1)


    def assertSamePath(self, first, second):
        """
        Assert that the two paths are the same, considering case normalization
        appropriate for the current platform.

        @type first: L{FilePath}
        @type second: L{FilePath}

        @raise C{self.failureType}: If the paths are not the same.
        """
        self.assertTrue(
            normcase(first.path) == normcase(second.path),
            "%r != %r" % (first, second))


    def test_renamedFile(self):
        """
        Even if the implementation of a deprecated function is moved around on
        the filesystem, the line number in the warning emitted by
        L{deprecate.warnAboutFunction} points to a line in the implementation of
#.........这里部分代码省略.........
开发者ID:JohnDoes95,项目名称:project_parser,代码行数:103,代码来源:test_deprecate.py

示例6: CreateSubversionRepositoryTests

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import sibling [as 别名]
class CreateSubversionRepositoryTests(TestCase):
    """
    Tests for L{createSubversionRepository}.

    @ivar commands: A list of the commands which have been executed.
    """

    def setUp(self):
        self.commands = []
        self.repository = FilePath(self.mktemp())
        self.workingCopy = self.repository.sibling('working')


    def runCommand(self, command):
        """
        Record the execution of a command.  Inspect the command and create a
        directory if it is an "svn co" command.
        """
        if self.workingCopy.isdir():
            children = list(self.workingCopy.walk())
            children.remove(self.workingCopy)
        else:
            children = None
        self.commands.append((command, children))
        if command.startswith("svn co "):
            self.workingCopy.makedirs()


    def test_emptyRepository(self):
        """
        L{createSubversionRepository} should create a repository with no
        entries or revisions if it is passed an empty dictionary.
        """
        createSubversionRepository(self.repository, {}, False, self.commands.append)
        self.assertEqual(
            self.commands,
            ["svnadmin create " + self.repository.path])


    def _fileTest(self, entry, contents):
        """
        """
        createSubversionRepository(
            self.repository, {entry: contents}, False, self.runCommand)

        repo = self.repository.path
        wc = self.workingCopy.path
        self.assertEqual(
            self.commands,
            [("svnadmin create " + repo, None),
             ("svn co file://" + repo + " " + wc, None),
             ("svn add " + self.workingCopy.child(entry).path,
              [self.workingCopy.child(entry)]),
             ("svn commit -m 'Create specified files' " + self.workingCopy.path,
              [self.workingCopy.child(entry)])])


    def test_emptyFile(self):
        """
        L{createSubversionRepository} should create a repository with one empty
        file in it if passed a dictionary with one key mapped to the empty
        string.
        """
        entry = 'filename'
        contents = ''
        self._fileTest(entry, contents)
        self.assertEqual(self.workingCopy.child(entry).getContent(), contents)


    def test_fileWithContents(self):
        """
        L{createSubversionRepository} should create a repository with a file
        with the contents given as the corresponding value.
        """
        entry = 'filename'
        contents = 'some bytes\n'
        self._fileTest(entry, contents)
        self.assertEqual(
            self.workingCopy.child(entry).getContent(), contents)


    def test_directory(self):
        """
        L{createSubversionRepository} should create a directory for a key with
        a C{dict} as a value.
        """
        entry = 'dirname'
        contents = {}
        self._fileTest(entry, contents)
        self.assertTrue(self.workingCopy.child(entry).isdir())


    def test_directoryContainingFile(self):
        """
        For a key associated with a value of a C{dict} with a key associated
        with a value of a C{str}, L{createSubversionRepository} should create a
        directory containing a file with the specified string as its content.
        """
        directory = 'dirname'
        file = 'filename'
#.........这里部分代码省略.........
开发者ID:rcarmo,项目名称:divmod.org,代码行数:103,代码来源:test_subversion.py

示例7: FilePath

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import sibling [as 别名]
# Copyright ClusterHQ Inc.  See LICENSE file for details.

# Generate a v5 configuration.
# Hash to recreate: 1ce62d2dc43d631954d7583c574259e89997829e

from twisted.python.filepath import FilePath

from flocker.control._model import Configuration
from flocker.control._persistence import wire_encode
from flocker.control.test.test_persistence import TEST_DEPLOYMENTS

_VERSION = 5

if __name__ == "__main__":
    myfile = FilePath(__file__)
    for i, deployment in enumerate(TEST_DEPLOYMENTS, start=1):
        encoding = wire_encode(
            Configuration(version=_VERSION, deployment=deployment)
        )
        myfile.sibling(
            b"configuration_%d_v%d.json" % (i, _VERSION)
        ).setContent(encoding)
开发者ID:332054781,项目名称:flocker,代码行数:24,代码来源:configuration_v5.py

示例8: FeedUpdatesTests

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import sibling [as 别名]

#.........这里部分代码省略.........
        @d.addCallback
        def disallowDupes(dummy):
            self.assertRaises(errors.InvalidIdentifier,
                self.plugin.subscribe, self.source, u'foo', u'url', u'title')

        return d


    def test_unsubscribe(self):
        """
        Unsubscribing deletes the relevant L{SubscribedFeed} item. Attempting
        to unsubscribe from a nonexistant feed raises
        L{eridanusstd.errors.InvalidIdentifier}.
        """
        self.assertRaises(errors.InvalidIdentifier,
            self.plugin.unsubscribe, self.source, u'wrong')

        d = self.plugin.subscribe(self.source, u'foo', u'url', u'title')

        @d.addCallback
        def unsubscribeIt(sub):
            d = self.plugin.unsubscribe(self.source, u'foo')
            d.addCallback(lambda dummy: sub)
            return d

        @d.addCallback
        def unsubscibed(sub):
            self.assertIdentical(sub._unsubscribe, None)
            self.assertRaises(errors.InvalidIdentifier,
                self.plugin.unsubscribe, self.source, u'foo')

        return d


    def test_getSubscription(self):
        """
        L{FeedUpdates.getSubscription} finds
        the single subscription with the specified identifier attributed to the
        specified feed subscriber. L{FeedUpdates.getSubscriptions} retrieves
        all feeds for a given subsciber.
        """
        self.assertIdentical(
            self.plugin.getSubscription(u'notthere', self.source.channel),
            None)

        subs = []
        d = self.plugin.subscribe(self.source, u'foo', u'url', u'title')

        @d.addCallback
        def subscribed(sub):
            subs.append(sub)
            self.assertIdentical(
                self.plugin.getSubscription(u'foo', self.source.channel),
                sub)
            return self.plugin.subscribe(self.source, u'bar', u'url', u'title')


        @d.addCallback
        def subscribedAgain(sub):
            subs.append(sub)
            subs.sort(key=lambda s: s.id)
            self.assertEquals(
                list(self.plugin.getSubscriptions(self.source.channel)),
                subs)

        return d


    def parse(self, path):
        """
        Parse the XML document at C{path} into a C{list} of C{domish} objects.
        """
        elements = []
        stream = domish.ExpatElementStream()
        stream.DocumentStartEvent = lambda root: None
        stream.DocumentEndEvent = lambda: None
        stream.ElementEvent = elements.append
        stream.parse(path.open().read())
        return elements


    def test_itemsReceived(self):
        """
        C{FeedUpdates.itemsReceived} is called with some Superfeedr item domish
        instances, which then triggers C{source.notice}.
        """
        elements = self.parse(self.path.sibling('feedupdates_1.xml'))
        items = elements[0].elements(
            uri=u'http://jabber.org/protocol/pubsub#event', name=u'items')
        items = list(items.next().elements(
            uri='http://jabber.org/protocol/pubsub#event', name='item'))

        d = self.plugin.subscribe(self.source, u'foo', u'url', u'title')

        @d.addCallback
        def subscribed(sub):
            self.plugin.itemsReceived(sub, items)
            self.assertEquals(self.source.calls['notice'], len(items))

        return d
开发者ID:mithrandi,项目名称:eridanus,代码行数:104,代码来源:test_feedupdates.py


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