diff options
Diffstat (limited to 'lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test')
23 files changed, 0 insertions, 9681 deletions
diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/__init__.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/__init__.py deleted file mode 100755 index cfdc40d1..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -""" -Unit tests for L{twisted.python}. -""" diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/deprecatedattributes.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/deprecatedattributes.py deleted file mode 100755 index b94c3617..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/deprecatedattributes.py +++ /dev/null @@ -1,21 +0,0 @@ -# Import reflect first, so that circular imports (between deprecate and -# reflect) don't cause headaches. -import twisted.python.reflect -from twisted.python.versions import Version -from twisted.python.deprecate import deprecatedModuleAttribute - - -# Known module-level attributes. -DEPRECATED_ATTRIBUTE = 42 -ANOTHER_ATTRIBUTE = 'hello' - - -version = Version('Twisted', 8, 0, 0) -message = 'Oh noes!' - - -deprecatedModuleAttribute( - version, - message, - __name__, - 'DEPRECATED_ATTRIBUTE') diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/modules_helpers.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/modules_helpers.py deleted file mode 100755 index 15ef6c1d..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/modules_helpers.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Facilities for helping test code which interacts with L{twisted.python.modules}, -or uses Python's own module system to load code. -""" - -import sys - -from twisted.trial.unittest import TestCase -from twisted.python import modules -from twisted.python.filepath import FilePath - -class TwistedModulesTestCase(TestCase): - - def findByIteration(self, modname, where=modules, importPackages=False): - """ - You don't ever actually want to do this, so it's not in the public API, but - sometimes we want to compare the result of an iterative call with a - lookup call and make sure they're the same for test purposes. - """ - for modinfo in where.walkModules(importPackages=importPackages): - if modinfo.name == modname: - return modinfo - self.fail("Unable to find module %r through iteration." % (modname,)) - - - def replaceSysPath(self, sysPath): - """ - Replace sys.path, for the duration of the test, with the given value. - """ - originalSysPath = sys.path[:] - def cleanUpSysPath(): - sys.path[:] = originalSysPath - self.addCleanup(cleanUpSysPath) - sys.path[:] = sysPath - - - def replaceSysModules(self, sysModules): - """ - Replace sys.modules, for the duration of the test, with the given value. - """ - originalSysModules = sys.modules.copy() - def cleanUpSysModules(): - sys.modules.clear() - sys.modules.update(originalSysModules) - self.addCleanup(cleanUpSysModules) - sys.modules.clear() - sys.modules.update(sysModules) - - - def pathEntryWithOnePackage(self, pkgname="test_package"): - """ - Generate a L{FilePath} with one package, named C{pkgname}, on it, and - return the L{FilePath} of the path entry. - """ - entry = FilePath(self.mktemp()) - pkg = entry.child("test_package") - pkg.makedirs() - pkg.child("__init__.py").setContent("") - return entry - - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/pullpipe.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/pullpipe.py deleted file mode 100755 index e6066627..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/pullpipe.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/python -# -*- test-case-name: twisted.python.test.test_sendmsg -*- -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -import sys, os -from struct import unpack - -# This makes me sad. Why aren't things nice? -sys.path.insert(0, __file__.rsplit('/', 4)[0]) - -from twisted.python.sendmsg import recv1msg - -def recvfd(socketfd): - """ - Receive a file descriptor from a L{send1msg} message on the given C{AF_UNIX} - socket. - - @param socketfd: An C{AF_UNIX} socket, attached to another process waiting - to send sockets via the ancillary data mechanism in L{send1msg}. - - @param fd: C{int} - - @return: a 2-tuple of (new file descriptor, description). - - @rtype: 2-tuple of (C{int}, C{str}) - """ - data, flags, ancillary = recv1msg(socketfd) - [(cmsg_level, cmsg_type, packedFD)] = ancillary - # cmsg_level and cmsg_type really need to be SOL_SOCKET / SCM_RIGHTS, but - # since those are the *only* standard values, there's not much point in - # checking. - [unpackedFD] = unpack("i", packedFD) - return (unpackedFD, data) - - -if __name__ == '__main__': - fd, description = recvfd(int(sys.argv[1])) - os.write(fd, "Test fixture data: %s.\n" % (description,)) - os.close(fd) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_components.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_components.py deleted file mode 100755 index c4c1b451..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_components.py +++ /dev/null @@ -1,770 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - - -""" -Test cases for Twisted component architecture. -""" - -from zope.interface import Interface, implements, Attribute -from zope.interface.adapter import AdapterRegistry - -from twisted.trial import unittest -from twisted.python import components -from twisted.python.components import _addHook, _removeHook, proxyForInterface - - -class InterfacesTestCase(unittest.TestCase): - """Test interfaces.""" - -class Compo(components.Componentized): - num = 0 - def inc(self): - self.num = self.num + 1 - return self.num - -class IAdept(Interface): - def adaptorFunc(): - raise NotImplementedError() - -class IElapsed(Interface): - def elapsedFunc(): - """ - 1! - """ - -class Adept(components.Adapter): - implements(IAdept) - def __init__(self, orig): - self.original = orig - self.num = 0 - def adaptorFunc(self): - self.num = self.num + 1 - return self.num, self.original.inc() - -class Elapsed(components.Adapter): - implements(IElapsed) - def elapsedFunc(self): - return 1 - -class AComp(components.Componentized): - pass -class BComp(AComp): - pass -class CComp(BComp): - pass - -class ITest(Interface): - pass -class ITest2(Interface): - pass -class ITest3(Interface): - pass -class ITest4(Interface): - pass -class Test(components.Adapter): - implements(ITest, ITest3, ITest4) - def __init__(self, orig): - pass -class Test2: - implements(ITest2) - temporaryAdapter = 1 - def __init__(self, orig): - pass - - - -class RegistryUsingMixin(object): - """ - Mixin for test cases which modify the global registry somehow. - """ - def setUp(self): - """ - Configure L{twisted.python.components.registerAdapter} to mutate an - alternate registry to improve test isolation. - """ - # Create a brand new, empty registry and put it onto the components - # module where registerAdapter will use it. Also ensure that it goes - # away at the end of the test. - scratchRegistry = AdapterRegistry() - self.patch(components, 'globalRegistry', scratchRegistry) - # Hook the new registry up to the adapter lookup system and ensure that - # association is also discarded after the test. - hook = _addHook(scratchRegistry) - self.addCleanup(_removeHook, hook) - - - -class ComponentizedTestCase(unittest.TestCase, RegistryUsingMixin): - """ - Simple test case for caching in Componentized. - """ - def setUp(self): - RegistryUsingMixin.setUp(self) - - components.registerAdapter(Test, AComp, ITest) - components.registerAdapter(Test, AComp, ITest3) - components.registerAdapter(Test2, AComp, ITest2) - - - def testComponentized(self): - components.registerAdapter(Adept, Compo, IAdept) - components.registerAdapter(Elapsed, Compo, IElapsed) - - c = Compo() - assert c.getComponent(IAdept).adaptorFunc() == (1, 1) - assert c.getComponent(IAdept).adaptorFunc() == (2, 2) - assert IElapsed(IAdept(c)).elapsedFunc() == 1 - - def testInheritanceAdaptation(self): - c = CComp() - co1 = c.getComponent(ITest) - co2 = c.getComponent(ITest) - co3 = c.getComponent(ITest2) - co4 = c.getComponent(ITest2) - assert co1 is co2 - assert co3 is not co4 - c.removeComponent(co1) - co5 = c.getComponent(ITest) - co6 = c.getComponent(ITest) - assert co5 is co6 - assert co1 is not co5 - - def testMultiAdapter(self): - c = CComp() - co1 = c.getComponent(ITest) - co2 = c.getComponent(ITest2) - co3 = c.getComponent(ITest3) - co4 = c.getComponent(ITest4) - self.assertIdentical(None, co4) - self.assertIdentical(co1, co3) - - - def test_getComponentDefaults(self): - """ - Test that a default value specified to Componentized.getComponent if - there is no component for the requested interface. - """ - componentized = components.Componentized() - default = object() - self.assertIdentical( - componentized.getComponent(ITest, default), - default) - self.assertIdentical( - componentized.getComponent(ITest, default=default), - default) - self.assertIdentical( - componentized.getComponent(ITest), - None) - - - -class AdapterTestCase(unittest.TestCase): - """Test adapters.""" - - def testAdapterGetComponent(self): - o = object() - a = Adept(o) - self.assertRaises(components.CannotAdapt, ITest, a) - self.assertEqual(ITest(a, None), None) - - - -class IMeta(Interface): - pass - -class MetaAdder(components.Adapter): - implements(IMeta) - def add(self, num): - return self.original.num + num - -class BackwardsAdder(components.Adapter): - implements(IMeta) - def add(self, num): - return self.original.num - num - -class MetaNumber: - def __init__(self, num): - self.num = num - -class FakeAdder: - def add(self, num): - return num + 5 - -class FakeNumber: - num = 3 - -class ComponentNumber(components.Componentized): - def __init__(self): - self.num = 0 - components.Componentized.__init__(self) - -class ComponentMeta(components.Adapter): - implements(IMeta) - def __init__(self, original): - components.Adapter.__init__(self, original) - self.num = self.original.num - -class ComponentAdder(ComponentMeta): - def add(self, num): - self.num += num - return self.num - -class ComponentDoubler(ComponentMeta): - def add(self, num): - self.num += (num * 2) - return self.original.num - -class IAttrX(Interface): - def x(): - pass - -class IAttrXX(Interface): - def xx(): - pass - -class Xcellent: - implements(IAttrX) - def x(self): - return 'x!' - -class DoubleXAdapter: - num = 42 - def __init__(self, original): - self.original = original - def xx(self): - return (self.original.x(), self.original.x()) - def __cmp__(self, other): - return cmp(self.num, other.num) - - -class TestMetaInterface(RegistryUsingMixin, unittest.TestCase): - def testBasic(self): - components.registerAdapter(MetaAdder, MetaNumber, IMeta) - n = MetaNumber(1) - self.assertEqual(IMeta(n).add(1), 2) - - def testComponentizedInteraction(self): - components.registerAdapter(ComponentAdder, ComponentNumber, IMeta) - c = ComponentNumber() - IMeta(c).add(1) - IMeta(c).add(1) - self.assertEqual(IMeta(c).add(1), 3) - - def testAdapterWithCmp(self): - # Make sure that a __cmp__ on an adapter doesn't break anything - components.registerAdapter(DoubleXAdapter, IAttrX, IAttrXX) - xx = IAttrXX(Xcellent()) - self.assertEqual(('x!', 'x!'), xx.xx()) - - -class RegistrationTestCase(RegistryUsingMixin, unittest.TestCase): - """ - Tests for adapter registration. - """ - def _registerAdapterForClassOrInterface(self, original): - """ - Register an adapter with L{components.registerAdapter} for the given - class or interface and verify that the adapter can be looked up with - L{components.getAdapterFactory}. - """ - adapter = lambda o: None - components.registerAdapter(adapter, original, ITest) - self.assertIdentical( - components.getAdapterFactory(original, ITest, None), - adapter) - - - def test_registerAdapterForClass(self): - """ - Test that an adapter from a class can be registered and then looked - up. - """ - class TheOriginal(object): - pass - return self._registerAdapterForClassOrInterface(TheOriginal) - - - def test_registerAdapterForInterface(self): - """ - Test that an adapter from an interface can be registered and then - looked up. - """ - return self._registerAdapterForClassOrInterface(ITest2) - - - def _duplicateAdapterForClassOrInterface(self, original): - """ - Verify that L{components.registerAdapter} raises L{ValueError} if the - from-type/interface and to-interface pair is not unique. - """ - firstAdapter = lambda o: False - secondAdapter = lambda o: True - components.registerAdapter(firstAdapter, original, ITest) - self.assertRaises( - ValueError, - components.registerAdapter, - secondAdapter, original, ITest) - # Make sure that the original adapter is still around as well - self.assertIdentical( - components.getAdapterFactory(original, ITest, None), - firstAdapter) - - - def test_duplicateAdapterForClass(self): - """ - Test that attempting to register a second adapter from a class - raises the appropriate exception. - """ - class TheOriginal(object): - pass - return self._duplicateAdapterForClassOrInterface(TheOriginal) - - - def test_duplicateAdapterForInterface(self): - """ - Test that attempting to register a second adapter from an interface - raises the appropriate exception. - """ - return self._duplicateAdapterForClassOrInterface(ITest2) - - - def _duplicateAdapterForClassOrInterfaceAllowed(self, original): - """ - Verify that when C{components.ALLOW_DUPLICATES} is set to C{True}, new - adapter registrations for a particular from-type/interface and - to-interface pair replace older registrations. - """ - firstAdapter = lambda o: False - secondAdapter = lambda o: True - class TheInterface(Interface): - pass - components.registerAdapter(firstAdapter, original, TheInterface) - components.ALLOW_DUPLICATES = True - try: - components.registerAdapter(secondAdapter, original, TheInterface) - self.assertIdentical( - components.getAdapterFactory(original, TheInterface, None), - secondAdapter) - finally: - components.ALLOW_DUPLICATES = False - - # It should be rejected again at this point - self.assertRaises( - ValueError, - components.registerAdapter, - firstAdapter, original, TheInterface) - - self.assertIdentical( - components.getAdapterFactory(original, TheInterface, None), - secondAdapter) - - - def test_duplicateAdapterForClassAllowed(self): - """ - Test that when L{components.ALLOW_DUPLICATES} is set to a true - value, duplicate registrations from classes are allowed to override - the original registration. - """ - class TheOriginal(object): - pass - return self._duplicateAdapterForClassOrInterfaceAllowed(TheOriginal) - - - def test_duplicateAdapterForInterfaceAllowed(self): - """ - Test that when L{components.ALLOW_DUPLICATES} is set to a true - value, duplicate registrations from interfaces are allowed to - override the original registration. - """ - class TheOriginal(Interface): - pass - return self._duplicateAdapterForClassOrInterfaceAllowed(TheOriginal) - - - def _multipleInterfacesForClassOrInterface(self, original): - """ - Verify that an adapter can be registered for multiple to-interfaces at a - time. - """ - adapter = lambda o: None - components.registerAdapter(adapter, original, ITest, ITest2) - self.assertIdentical( - components.getAdapterFactory(original, ITest, None), adapter) - self.assertIdentical( - components.getAdapterFactory(original, ITest2, None), adapter) - - - def test_multipleInterfacesForClass(self): - """ - Test the registration of an adapter from a class to several - interfaces at once. - """ - class TheOriginal(object): - pass - return self._multipleInterfacesForClassOrInterface(TheOriginal) - - - def test_multipleInterfacesForInterface(self): - """ - Test the registration of an adapter from an interface to several - interfaces at once. - """ - return self._multipleInterfacesForClassOrInterface(ITest3) - - - def _subclassAdapterRegistrationForClassOrInterface(self, original): - """ - Verify that a new adapter can be registered for a particular - to-interface from a subclass of a type or interface which already has an - adapter registered to that interface and that the subclass adapter takes - precedence over the base class adapter. - """ - firstAdapter = lambda o: True - secondAdapter = lambda o: False - class TheSubclass(original): - pass - components.registerAdapter(firstAdapter, original, ITest) - components.registerAdapter(secondAdapter, TheSubclass, ITest) - self.assertIdentical( - components.getAdapterFactory(original, ITest, None), - firstAdapter) - self.assertIdentical( - components.getAdapterFactory(TheSubclass, ITest, None), - secondAdapter) - - - def test_subclassAdapterRegistrationForClass(self): - """ - Test that an adapter to a particular interface can be registered - from both a class and its subclass. - """ - class TheOriginal(object): - pass - return self._subclassAdapterRegistrationForClassOrInterface(TheOriginal) - - - def test_subclassAdapterRegistrationForInterface(self): - """ - Test that an adapter to a particular interface can be registered - from both an interface and its subclass. - """ - return self._subclassAdapterRegistrationForClassOrInterface(ITest2) - - - -class IProxiedInterface(Interface): - """ - An interface class for use by L{proxyForInterface}. - """ - - ifaceAttribute = Attribute(""" - An example declared attribute, which should be proxied.""") - - def yay(*a, **kw): - """ - A sample method which should be proxied. - """ - -class IProxiedSubInterface(IProxiedInterface): - """ - An interface that derives from another for use with L{proxyForInterface}. - """ - - def boo(self): - """ - A different sample method which should be proxied. - """ - - - -class Yayable(object): - """ - A provider of L{IProxiedInterface} which increments a counter for - every call to C{yay}. - - @ivar yays: The number of times C{yay} has been called. - """ - implements(IProxiedInterface) - - def __init__(self): - self.yays = 0 - self.yayArgs = [] - - def yay(self, *a, **kw): - """ - Increment C{self.yays}. - """ - self.yays += 1 - self.yayArgs.append((a, kw)) - return self.yays - - -class Booable(object): - """ - An implementation of IProxiedSubInterface - """ - implements(IProxiedSubInterface) - yayed = False - booed = False - def yay(self): - """ - Mark the fact that 'yay' has been called. - """ - self.yayed = True - - - def boo(self): - """ - Mark the fact that 'boo' has been called.1 - """ - self.booed = True - - - -class IMultipleMethods(Interface): - """ - An interface with multiple methods. - """ - - def methodOne(): - """ - The first method. Should return 1. - """ - - def methodTwo(): - """ - The second method. Should return 2. - """ - - - -class MultipleMethodImplementor(object): - """ - A precise implementation of L{IMultipleMethods}. - """ - - def methodOne(self): - """ - @return: 1 - """ - return 1 - - - def methodTwo(self): - """ - @return: 2 - """ - return 2 - - - -class ProxyForInterfaceTests(unittest.TestCase): - """ - Tests for L{proxyForInterface}. - """ - - def test_original(self): - """ - Proxy objects should have an C{original} attribute which refers to the - original object passed to the constructor. - """ - original = object() - proxy = proxyForInterface(IProxiedInterface)(original) - self.assertIdentical(proxy.original, original) - - - def test_proxyMethod(self): - """ - The class created from L{proxyForInterface} passes methods on an - interface to the object which is passed to its constructor. - """ - klass = proxyForInterface(IProxiedInterface) - yayable = Yayable() - proxy = klass(yayable) - proxy.yay() - self.assertEqual(proxy.yay(), 2) - self.assertEqual(yayable.yays, 2) - - - def test_proxyAttribute(self): - """ - Proxy objects should proxy declared attributes, but not other - attributes. - """ - yayable = Yayable() - yayable.ifaceAttribute = object() - proxy = proxyForInterface(IProxiedInterface)(yayable) - self.assertIdentical(proxy.ifaceAttribute, yayable.ifaceAttribute) - self.assertRaises(AttributeError, lambda: proxy.yays) - - - def test_proxySetAttribute(self): - """ - The attributes that proxy objects proxy should be assignable and affect - the original object. - """ - yayable = Yayable() - proxy = proxyForInterface(IProxiedInterface)(yayable) - thingy = object() - proxy.ifaceAttribute = thingy - self.assertIdentical(yayable.ifaceAttribute, thingy) - - - def test_proxyDeleteAttribute(self): - """ - The attributes that proxy objects proxy should be deletable and affect - the original object. - """ - yayable = Yayable() - yayable.ifaceAttribute = None - proxy = proxyForInterface(IProxiedInterface)(yayable) - del proxy.ifaceAttribute - self.assertFalse(hasattr(yayable, 'ifaceAttribute')) - - - def test_multipleMethods(self): - """ - [Regression test] The proxy should send its method calls to the correct - method, not the incorrect one. - """ - multi = MultipleMethodImplementor() - proxy = proxyForInterface(IMultipleMethods)(multi) - self.assertEqual(proxy.methodOne(), 1) - self.assertEqual(proxy.methodTwo(), 2) - - - def test_subclassing(self): - """ - It is possible to subclass the result of L{proxyForInterface}. - """ - - class SpecializedProxy(proxyForInterface(IProxiedInterface)): - """ - A specialized proxy which can decrement the number of yays. - """ - def boo(self): - """ - Decrement the number of yays. - """ - self.original.yays -= 1 - - yayable = Yayable() - special = SpecializedProxy(yayable) - self.assertEqual(yayable.yays, 0) - special.boo() - self.assertEqual(yayable.yays, -1) - - - def test_proxyName(self): - """ - The name of a proxy class indicates which interface it proxies. - """ - proxy = proxyForInterface(IProxiedInterface) - self.assertEqual( - proxy.__name__, - "(Proxy for " - "twisted.python.test.test_components.IProxiedInterface)") - - - def test_implements(self): - """ - The resulting proxy implements the interface that it proxies. - """ - proxy = proxyForInterface(IProxiedInterface) - self.assertTrue(IProxiedInterface.implementedBy(proxy)) - - - def test_proxyDescriptorGet(self): - """ - _ProxyDescriptor's __get__ method should return the appropriate - attribute of its argument's 'original' attribute if it is invoked with - an object. If it is invoked with None, it should return a false - class-method emulator instead. - - For some reason, Python's documentation recommends to define - descriptors' __get__ methods with the 'type' parameter as optional, - despite the fact that Python itself never actually calls the descriptor - that way. This is probably do to support 'foo.__get__(bar)' as an - idiom. Let's make sure that the behavior is correct. Since we don't - actually use the 'type' argument at all, this test calls it the - idiomatic way to ensure that signature works; test_proxyInheritance - verifies the how-Python-actually-calls-it signature. - """ - class Sample: - called = False - def hello(self): - self.called = True - fakeProxy = Sample() - testObject = Sample() - fakeProxy.original = testObject - pd = components._ProxyDescriptor("hello", "original") - self.assertEqual(pd.__get__(fakeProxy), testObject.hello) - fakeClassMethod = pd.__get__(None) - fakeClassMethod(fakeProxy) - self.failUnless(testObject.called) - - - def test_proxyInheritance(self): - """ - Subclasses of the class returned from L{proxyForInterface} should be - able to upcall methods by reference to their superclass, as any normal - Python class can. - """ - class YayableWrapper(proxyForInterface(IProxiedInterface)): - """ - This class does not override any functionality. - """ - - class EnhancedWrapper(YayableWrapper): - """ - This class overrides the 'yay' method. - """ - wrappedYays = 1 - def yay(self, *a, **k): - self.wrappedYays += 1 - return YayableWrapper.yay(self, *a, **k) + 7 - - yayable = Yayable() - wrapper = EnhancedWrapper(yayable) - self.assertEqual(wrapper.yay(3, 4, x=5, y=6), 8) - self.assertEqual(yayable.yayArgs, - [((3, 4), dict(x=5, y=6))]) - - - def test_interfaceInheritance(self): - """ - Proxies of subinterfaces generated with proxyForInterface should allow - access to attributes of both the child and the base interfaces. - """ - proxyClass = proxyForInterface(IProxiedSubInterface) - booable = Booable() - proxy = proxyClass(booable) - proxy.yay() - proxy.boo() - self.failUnless(booable.yayed) - self.failUnless(booable.booed) - - - def test_attributeCustomization(self): - """ - The original attribute name can be customized via the - C{originalAttribute} argument of L{proxyForInterface}: the attribute - should change, but the methods of the original object should still be - callable, and the attributes still accessible. - """ - yayable = Yayable() - yayable.ifaceAttribute = object() - proxy = proxyForInterface( - IProxiedInterface, originalAttribute='foo')(yayable) - self.assertIdentical(proxy.foo, yayable) - - # Check the behavior - self.assertEqual(proxy.yay(), 1) - self.assertIdentical(proxy.ifaceAttribute, yayable.ifaceAttribute) - thingy = object() - proxy.ifaceAttribute = thingy - self.assertIdentical(yayable.ifaceAttribute, thingy) - del proxy.ifaceAttribute - self.assertFalse(hasattr(yayable, 'ifaceAttribute')) - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_constants.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_constants.py deleted file mode 100755 index 870d342b..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_constants.py +++ /dev/null @@ -1,778 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Unit tests for L{twisted.python.constants}. -""" - -from twisted.trial.unittest import TestCase - -from twisted.python.constants import ( - NamedConstant, Names, ValueConstant, Values, FlagConstant, Flags) - - -class NamedConstantTests(TestCase): - """ - Tests for the L{twisted.python.constants.NamedConstant} class which is used - to represent individual values. - """ - def setUp(self): - """ - Create a dummy container into which constants can be placed. - """ - class foo(Names): - pass - self.container = foo - - - def test_name(self): - """ - The C{name} attribute of a L{NamedConstant} refers to the value passed - for the C{name} parameter to C{_realize}. - """ - name = NamedConstant() - name._realize(self.container, "bar", None) - self.assertEqual("bar", name.name) - - - def test_representation(self): - """ - The string representation of an instance of L{NamedConstant} includes - the container the instances belongs to as well as the instance's name. - """ - name = NamedConstant() - name._realize(self.container, "bar", None) - self.assertEqual("<foo=bar>", repr(name)) - - - def test_equality(self): - """ - A L{NamedConstant} instance compares equal to itself. - """ - name = NamedConstant() - name._realize(self.container, "bar", None) - self.assertTrue(name == name) - self.assertFalse(name != name) - - - def test_nonequality(self): - """ - Two different L{NamedConstant} instances do not compare equal to each - other. - """ - first = NamedConstant() - first._realize(self.container, "bar", None) - second = NamedConstant() - second._realize(self.container, "bar", None) - self.assertFalse(first == second) - self.assertTrue(first != second) - - - def test_hash(self): - """ - Because two different L{NamedConstant} instances do not compare as equal - to each other, they also have different hashes to avoid collisions when - added to a C{dict} or C{set}. - """ - first = NamedConstant() - first._realize(self.container, "bar", None) - second = NamedConstant() - second._realize(self.container, "bar", None) - self.assertNotEqual(hash(first), hash(second)) - - - -class _ConstantsTestsMixin(object): - """ - Mixin defining test helpers common to multiple types of constants - collections. - """ - def _notInstantiableTest(self, name, cls): - """ - Assert that an attempt to instantiate the constants class raises - C{TypeError}. - - @param name: A C{str} giving the name of the constants collection. - @param cls: The constants class to test. - """ - exc = self.assertRaises(TypeError, cls) - self.assertEqual(name + " may not be instantiated.", str(exc)) - - - -class NamesTests(TestCase, _ConstantsTestsMixin): - """ - Tests for L{twisted.python.constants.Names}, a base class for containers of - related constaints. - """ - def setUp(self): - """ - Create a fresh new L{Names} subclass for each unit test to use. Since - L{Names} is stateful, re-using the same subclass across test methods - makes exercising all of the implementation code paths difficult. - """ - class METHOD(Names): - """ - A container for some named constants to use in unit tests for - L{Names}. - """ - GET = NamedConstant() - PUT = NamedConstant() - POST = NamedConstant() - DELETE = NamedConstant() - - self.METHOD = METHOD - - - def test_notInstantiable(self): - """ - A subclass of L{Names} raises C{TypeError} if an attempt is made to - instantiate it. - """ - self._notInstantiableTest("METHOD", self.METHOD) - - - def test_symbolicAttributes(self): - """ - Each name associated with a L{NamedConstant} instance in the definition - of a L{Names} subclass is available as an attribute on the resulting - class. - """ - self.assertTrue(hasattr(self.METHOD, "GET")) - self.assertTrue(hasattr(self.METHOD, "PUT")) - self.assertTrue(hasattr(self.METHOD, "POST")) - self.assertTrue(hasattr(self.METHOD, "DELETE")) - - - def test_withoutOtherAttributes(self): - """ - As usual, names not defined in the class scope of a L{Names} - subclass are not available as attributes on the resulting class. - """ - self.assertFalse(hasattr(self.METHOD, "foo")) - - - def test_representation(self): - """ - The string representation of a constant on a L{Names} subclass includes - the name of the L{Names} subclass and the name of the constant itself. - """ - self.assertEqual("<METHOD=GET>", repr(self.METHOD.GET)) - - - def test_lookupByName(self): - """ - Constants can be looked up by name using L{Names.lookupByName}. - """ - method = self.METHOD.lookupByName("GET") - self.assertIdentical(self.METHOD.GET, method) - - - def test_notLookupMissingByName(self): - """ - Names not defined with a L{NamedConstant} instance cannot be looked up - using L{Names.lookupByName}. - """ - self.assertRaises(ValueError, self.METHOD.lookupByName, "lookupByName") - self.assertRaises(ValueError, self.METHOD.lookupByName, "__init__") - self.assertRaises(ValueError, self.METHOD.lookupByName, "foo") - - - def test_name(self): - """ - The C{name} attribute of one of the named constants gives that - constant's name. - """ - self.assertEqual("GET", self.METHOD.GET.name) - - - def test_attributeIdentity(self): - """ - Repeated access of an attribute associated with a L{NamedConstant} value - in a L{Names} subclass results in the same object. - """ - self.assertIdentical(self.METHOD.GET, self.METHOD.GET) - - - def test_iterconstants(self): - """ - L{Names.iterconstants} returns an iterator over all of the constants - defined in the class, in the order they were defined. - """ - constants = list(self.METHOD.iterconstants()) - self.assertEqual( - [self.METHOD.GET, self.METHOD.PUT, - self.METHOD.POST, self.METHOD.DELETE], - constants) - - - def test_attributeIterconstantsIdentity(self): - """ - The constants returned from L{Names.iterconstants} are identical to the - constants accessible using attributes. - """ - constants = list(self.METHOD.iterconstants()) - self.assertIdentical(self.METHOD.GET, constants[0]) - self.assertIdentical(self.METHOD.PUT, constants[1]) - self.assertIdentical(self.METHOD.POST, constants[2]) - self.assertIdentical(self.METHOD.DELETE, constants[3]) - - - def test_iterconstantsIdentity(self): - """ - The constants returned from L{Names.iterconstants} are identical on each - call to that method. - """ - constants = list(self.METHOD.iterconstants()) - again = list(self.METHOD.iterconstants()) - self.assertIdentical(again[0], constants[0]) - self.assertIdentical(again[1], constants[1]) - self.assertIdentical(again[2], constants[2]) - self.assertIdentical(again[3], constants[3]) - - - def test_initializedOnce(self): - """ - L{Names._enumerants} is initialized once and its value re-used on - subsequent access. - """ - first = self.METHOD._enumerants - self.METHOD.GET # Side-effects! - second = self.METHOD._enumerants - self.assertIdentical(first, second) - - - -class ValuesTests(TestCase, _ConstantsTestsMixin): - """ - Tests for L{twisted.python.constants.Names}, a base class for containers of - related constaints with arbitrary values. - """ - def setUp(self): - """ - Create a fresh new L{Values} subclass for each unit test to use. Since - L{Values} is stateful, re-using the same subclass across test methods - makes exercising all of the implementation code paths difficult. - """ - class STATUS(Values): - OK = ValueConstant("200") - NOT_FOUND = ValueConstant("404") - - self.STATUS = STATUS - - - def test_notInstantiable(self): - """ - A subclass of L{Values} raises C{TypeError} if an attempt is made to - instantiate it. - """ - self._notInstantiableTest("STATUS", self.STATUS) - - - def test_symbolicAttributes(self): - """ - Each name associated with a L{ValueConstant} instance in the definition - of a L{Values} subclass is available as an attribute on the resulting - class. - """ - self.assertTrue(hasattr(self.STATUS, "OK")) - self.assertTrue(hasattr(self.STATUS, "NOT_FOUND")) - - - def test_withoutOtherAttributes(self): - """ - As usual, names not defined in the class scope of a L{Values} - subclass are not available as attributes on the resulting class. - """ - self.assertFalse(hasattr(self.STATUS, "foo")) - - - def test_representation(self): - """ - The string representation of a constant on a L{Values} subclass includes - the name of the L{Values} subclass and the name of the constant itself. - """ - self.assertEqual("<STATUS=OK>", repr(self.STATUS.OK)) - - - def test_lookupByName(self): - """ - Constants can be looked up by name using L{Values.lookupByName}. - """ - method = self.STATUS.lookupByName("OK") - self.assertIdentical(self.STATUS.OK, method) - - - def test_notLookupMissingByName(self): - """ - Names not defined with a L{ValueConstant} instance cannot be looked up - using L{Values.lookupByName}. - """ - self.assertRaises(ValueError, self.STATUS.lookupByName, "lookupByName") - self.assertRaises(ValueError, self.STATUS.lookupByName, "__init__") - self.assertRaises(ValueError, self.STATUS.lookupByName, "foo") - - - def test_lookupByValue(self): - """ - Constants can be looked up by their associated value, defined by the - argument passed to L{ValueConstant}, using L{Values.lookupByValue}. - """ - status = self.STATUS.lookupByValue("200") - self.assertIdentical(self.STATUS.OK, status) - - - def test_lookupDuplicateByValue(self): - """ - If more than one constant is associated with a particular value, - L{Values.lookupByValue} returns whichever of them is defined first. - """ - class TRANSPORT_MESSAGE(Values): - """ - Message types supported by an SSH transport. - """ - KEX_DH_GEX_REQUEST_OLD = ValueConstant(30) - KEXDH_INIT = ValueConstant(30) - - self.assertIdentical( - TRANSPORT_MESSAGE.lookupByValue(30), - TRANSPORT_MESSAGE.KEX_DH_GEX_REQUEST_OLD) - - - def test_notLookupMissingByValue(self): - """ - L{Values.lookupByValue} raises L{ValueError} when called with a value - with which no constant is associated. - """ - self.assertRaises(ValueError, self.STATUS.lookupByValue, "OK") - self.assertRaises(ValueError, self.STATUS.lookupByValue, 200) - self.assertRaises(ValueError, self.STATUS.lookupByValue, "200.1") - - - def test_name(self): - """ - The C{name} attribute of one of the constants gives that constant's - name. - """ - self.assertEqual("OK", self.STATUS.OK.name) - - - def test_attributeIdentity(self): - """ - Repeated access of an attribute associated with a L{ValueConstant} value - in a L{Values} subclass results in the same object. - """ - self.assertIdentical(self.STATUS.OK, self.STATUS.OK) - - - def test_iterconstants(self): - """ - L{Values.iterconstants} returns an iterator over all of the constants - defined in the class, in the order they were defined. - """ - constants = list(self.STATUS.iterconstants()) - self.assertEqual( - [self.STATUS.OK, self.STATUS.NOT_FOUND], - constants) - - - def test_attributeIterconstantsIdentity(self): - """ - The constants returned from L{Values.iterconstants} are identical to the - constants accessible using attributes. - """ - constants = list(self.STATUS.iterconstants()) - self.assertIdentical(self.STATUS.OK, constants[0]) - self.assertIdentical(self.STATUS.NOT_FOUND, constants[1]) - - - def test_iterconstantsIdentity(self): - """ - The constants returned from L{Values.iterconstants} are identical on - each call to that method. - """ - constants = list(self.STATUS.iterconstants()) - again = list(self.STATUS.iterconstants()) - self.assertIdentical(again[0], constants[0]) - self.assertIdentical(again[1], constants[1]) - - - def test_initializedOnce(self): - """ - L{Values._enumerants} is initialized once and its value re-used on - subsequent access. - """ - first = self.STATUS._enumerants - self.STATUS.OK # Side-effects! - second = self.STATUS._enumerants - self.assertIdentical(first, second) - - -class _FlagsTestsMixin(object): - """ - Mixin defining setup code for any tests for L{Flags} subclasses. - - @ivar FXF: A L{Flags} subclass created for each test method. - """ - def setUp(self): - """ - Create a fresh new L{Flags} subclass for each unit test to use. Since - L{Flags} is stateful, re-using the same subclass across test methods - makes exercising all of the implementation code paths difficult. - """ - class FXF(Flags): - # Implicitly assign three flag values based on definition order - READ = FlagConstant() - WRITE = FlagConstant() - APPEND = FlagConstant() - - # Explicitly assign one flag value by passing it in - EXCLUSIVE = FlagConstant(0x20) - - # Implicitly assign another flag value, following the previously - # specified explicit value. - TEXT = FlagConstant() - - self.FXF = FXF - - - -class FlagsTests(_FlagsTestsMixin, TestCase, _ConstantsTestsMixin): - """ - Tests for L{twisted.python.constants.Flags}, a base class for containers of - related, combinable flag or bitvector-like constants. - """ - def test_notInstantiable(self): - """ - A subclass of L{Flags} raises L{TypeError} if an attempt is made to - instantiate it. - """ - self._notInstantiableTest("FXF", self.FXF) - - - def test_symbolicAttributes(self): - """ - Each name associated with a L{FlagConstant} instance in the definition - of a L{Flags} subclass is available as an attribute on the resulting - class. - """ - self.assertTrue(hasattr(self.FXF, "READ")) - self.assertTrue(hasattr(self.FXF, "WRITE")) - self.assertTrue(hasattr(self.FXF, "APPEND")) - self.assertTrue(hasattr(self.FXF, "EXCLUSIVE")) - self.assertTrue(hasattr(self.FXF, "TEXT")) - - - def test_withoutOtherAttributes(self): - """ - As usual, names not defined in the class scope of a L{Flags} subclass - are not available as attributes on the resulting class. - """ - self.assertFalse(hasattr(self.FXF, "foo")) - - - def test_representation(self): - """ - The string representation of a constant on a L{Flags} subclass includes - the name of the L{Flags} subclass and the name of the constant itself. - """ - self.assertEqual("<FXF=READ>", repr(self.FXF.READ)) - - - def test_lookupByName(self): - """ - Constants can be looked up by name using L{Flags.lookupByName}. - """ - flag = self.FXF.lookupByName("READ") - self.assertIdentical(self.FXF.READ, flag) - - - def test_notLookupMissingByName(self): - """ - Names not defined with a L{FlagConstant} instance cannot be looked up - using L{Flags.lookupByName}. - """ - self.assertRaises(ValueError, self.FXF.lookupByName, "lookupByName") - self.assertRaises(ValueError, self.FXF.lookupByName, "__init__") - self.assertRaises(ValueError, self.FXF.lookupByName, "foo") - - - def test_lookupByValue(self): - """ - Constants can be looked up by their associated value, defined implicitly - by the position in which the constant appears in the class definition or - explicitly by the argument passed to L{FlagConstant}. - """ - flag = self.FXF.lookupByValue(0x01) - self.assertIdentical(flag, self.FXF.READ) - - flag = self.FXF.lookupByValue(0x02) - self.assertIdentical(flag, self.FXF.WRITE) - - flag = self.FXF.lookupByValue(0x04) - self.assertIdentical(flag, self.FXF.APPEND) - - flag = self.FXF.lookupByValue(0x20) - self.assertIdentical(flag, self.FXF.EXCLUSIVE) - - flag = self.FXF.lookupByValue(0x40) - self.assertIdentical(flag, self.FXF.TEXT) - - - def test_lookupDuplicateByValue(self): - """ - If more than one constant is associated with a particular value, - L{Flags.lookupByValue} returns whichever of them is defined first. - """ - class TIMEX(Flags): - # (timex.mode) - ADJ_OFFSET = FlagConstant(0x0001) # time offset - - # xntp 3.4 compatibility names - MOD_OFFSET = FlagConstant(0x0001) - - self.assertIdentical(TIMEX.lookupByValue(0x0001), TIMEX.ADJ_OFFSET) - - - def test_notLookupMissingByValue(self): - """ - L{Flags.lookupByValue} raises L{ValueError} when called with a value - with which no constant is associated. - """ - self.assertRaises(ValueError, self.FXF.lookupByValue, 0x10) - - - def test_name(self): - """ - The C{name} attribute of one of the constants gives that constant's - name. - """ - self.assertEqual("READ", self.FXF.READ.name) - - - def test_attributeIdentity(self): - """ - Repeated access of an attribute associated with a L{FlagConstant} value - in a L{Flags} subclass results in the same object. - """ - self.assertIdentical(self.FXF.READ, self.FXF.READ) - - - def test_iterconstants(self): - """ - L{Flags.iterconstants} returns an iterator over all of the constants - defined in the class, in the order they were defined. - """ - constants = list(self.FXF.iterconstants()) - self.assertEqual( - [self.FXF.READ, self.FXF.WRITE, self.FXF.APPEND, - self.FXF.EXCLUSIVE, self.FXF.TEXT], - constants) - - - def test_attributeIterconstantsIdentity(self): - """ - The constants returned from L{Flags.iterconstants} are identical to the - constants accessible using attributes. - """ - constants = list(self.FXF.iterconstants()) - self.assertIdentical(self.FXF.READ, constants[0]) - self.assertIdentical(self.FXF.WRITE, constants[1]) - self.assertIdentical(self.FXF.APPEND, constants[2]) - self.assertIdentical(self.FXF.EXCLUSIVE, constants[3]) - self.assertIdentical(self.FXF.TEXT, constants[4]) - - - def test_iterconstantsIdentity(self): - """ - The constants returned from L{Flags.iterconstants} are identical on each - call to that method. - """ - constants = list(self.FXF.iterconstants()) - again = list(self.FXF.iterconstants()) - self.assertIdentical(again[0], constants[0]) - self.assertIdentical(again[1], constants[1]) - self.assertIdentical(again[2], constants[2]) - self.assertIdentical(again[3], constants[3]) - self.assertIdentical(again[4], constants[4]) - - - def test_initializedOnce(self): - """ - L{Flags._enumerants} is initialized once and its value re-used on - subsequent access. - """ - first = self.FXF._enumerants - self.FXF.READ # Side-effects! - second = self.FXF._enumerants - self.assertIdentical(first, second) - - - -class FlagConstantSimpleOrTests(_FlagsTestsMixin, TestCase): - """ - Tests for the C{|} operator as defined for L{FlagConstant} instances, used - to create new L{FlagConstant} instances representing both of two existing - L{FlagConstant} instances from the same L{Flags} class. - """ - def test_value(self): - """ - The value of the L{FlagConstant} which results from C{|} has all of the - bits set which were set in either of the values of the two original - constants. - """ - flag = self.FXF.READ | self.FXF.WRITE - self.assertEqual(self.FXF.READ.value | self.FXF.WRITE.value, flag.value) - - - def test_name(self): - """ - The name of the L{FlagConstant} instance which results from C{|} - includes the names of both of the two original constants. - """ - flag = self.FXF.READ | self.FXF.WRITE - self.assertEqual("{READ,WRITE}", flag.name) - - - def test_representation(self): - """ - The string representation of a L{FlagConstant} instance which results - from C{|} includes the names of both of the two original constants. - """ - flag = self.FXF.READ | self.FXF.WRITE - self.assertEqual("<FXF={READ,WRITE}>", repr(flag)) - - - -class FlagConstantSimpleAndTests(_FlagsTestsMixin, TestCase): - """ - Tests for the C{&} operator as defined for L{FlagConstant} instances, used - to create new L{FlagConstant} instances representing the common parts of two - existing L{FlagConstant} instances from the same L{Flags} class. - """ - def test_value(self): - """ - The value of the L{FlagConstant} which results from C{&} has all of the - bits set which were set in both of the values of the two original - constants. - """ - readWrite = (self.FXF.READ | self.FXF.WRITE) - writeAppend = (self.FXF.WRITE | self.FXF.APPEND) - flag = readWrite & writeAppend - self.assertEqual(self.FXF.WRITE.value, flag.value) - - - def test_name(self): - """ - The name of the L{FlagConstant} instance which results from C{&} - includes the names of only the flags which were set in both of the two - original constants. - """ - readWrite = (self.FXF.READ | self.FXF.WRITE) - writeAppend = (self.FXF.WRITE | self.FXF.APPEND) - flag = readWrite & writeAppend - self.assertEqual("WRITE", flag.name) - - - def test_representation(self): - """ - The string representation of a L{FlagConstant} instance which results - from C{&} includes the names of only the flags which were set in both - both of the two original constants. - """ - readWrite = (self.FXF.READ | self.FXF.WRITE) - writeAppend = (self.FXF.WRITE | self.FXF.APPEND) - flag = readWrite & writeAppend - self.assertEqual("<FXF=WRITE>", repr(flag)) - - - -class FlagConstantSimpleExclusiveOrTests(_FlagsTestsMixin, TestCase): - """ - Tests for the C{^} operator as defined for L{FlagConstant} instances, used - to create new L{FlagConstant} instances representing the uncommon parts of - two existing L{FlagConstant} instances from the same L{Flags} class. - """ - def test_value(self): - """ - The value of the L{FlagConstant} which results from C{^} has all of the - bits set which were set in exactly one of the values of the two original - constants. - """ - readWrite = (self.FXF.READ | self.FXF.WRITE) - writeAppend = (self.FXF.WRITE | self.FXF.APPEND) - flag = readWrite ^ writeAppend - self.assertEqual(self.FXF.READ.value | self.FXF.APPEND.value, flag.value) - - - def test_name(self): - """ - The name of the L{FlagConstant} instance which results from C{^} - includes the names of only the flags which were set in exactly one of - the two original constants. - """ - readWrite = (self.FXF.READ | self.FXF.WRITE) - writeAppend = (self.FXF.WRITE | self.FXF.APPEND) - flag = readWrite ^ writeAppend - self.assertEqual("{APPEND,READ}", flag.name) - - - def test_representation(self): - """ - The string representation of a L{FlagConstant} instance which results - from C{^} includes the names of only the flags which were set in exactly - one of the two original constants. - """ - readWrite = (self.FXF.READ | self.FXF.WRITE) - writeAppend = (self.FXF.WRITE | self.FXF.APPEND) - flag = readWrite ^ writeAppend - self.assertEqual("<FXF={APPEND,READ}>", repr(flag)) - - - -class FlagConstantNegationTests(_FlagsTestsMixin, TestCase): - """ - Tests for the C{~} operator as defined for L{FlagConstant} instances, used - to create new L{FlagConstant} instances representing all the flags from a - L{Flags} class not set in a particular L{FlagConstant} instance. - """ - def test_value(self): - """ - The value of the L{FlagConstant} which results from C{~} has all of the - bits set which were not set in the original constant. - """ - flag = ~self.FXF.READ - self.assertEqual( - self.FXF.WRITE.value | - self.FXF.APPEND.value | - self.FXF.EXCLUSIVE.value | - self.FXF.TEXT.value, - flag.value) - - flag = ~self.FXF.WRITE - self.assertEqual( - self.FXF.READ.value | - self.FXF.APPEND.value | - self.FXF.EXCLUSIVE.value | - self.FXF.TEXT.value, - flag.value) - - - def test_name(self): - """ - The name of the L{FlagConstant} instance which results from C{~} - includes the names of all the flags which were not set in the original - constant. - """ - flag = ~self.FXF.WRITE - self.assertEqual("{APPEND,EXCLUSIVE,READ,TEXT}", flag.name) - - - def test_representation(self): - """ - The string representation of a L{FlagConstant} instance which results - from C{~} includes the names of all the flags which were not set in the - original constant. - """ - flag = ~self.FXF.WRITE - self.assertEqual("<FXF={APPEND,EXCLUSIVE,READ,TEXT}>", repr(flag)) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_deprecate.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_deprecate.py deleted file mode 100755 index 03498e4e..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_deprecate.py +++ /dev/null @@ -1,767 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for Twisted's deprecation framework, L{twisted.python.deprecate}. -""" - -import sys, types -import warnings -from os.path import normcase - -from twisted.trial.unittest import TestCase - -from twisted.python import deprecate -from twisted.python.deprecate import _appendToDocstring -from twisted.python.deprecate import _getDeprecationDocstring -from twisted.python.deprecate import deprecated, getDeprecationWarningString -from twisted.python.deprecate import _getDeprecationWarningString -from twisted.python.deprecate import DEPRECATION_WARNING_FORMAT -from twisted.python.reflect import fullyQualifiedName -from twisted.python.versions import Version -from twisted.python.filepath import FilePath - -from twisted.python.test import deprecatedattributes -from twisted.python.test.modules_helpers import TwistedModulesTestCase - - - -def dummyCallable(): - """ - Do nothing. - - This is used to test the deprecation decorators. - """ - - -def dummyReplacementMethod(): - """ - Do nothing. - - This is used to test the replacement parameter to L{deprecated}. - """ - - - -class TestDeprecationWarnings(TestCase): - def test_getDeprecationWarningString(self): - """ - L{getDeprecationWarningString} returns a string that tells us that a - callable was deprecated at a certain released version of Twisted. - """ - version = Version('Twisted', 8, 0, 0) - self.assertEqual( - getDeprecationWarningString(self.test_getDeprecationWarningString, - version), - "twisted.python.test.test_deprecate.TestDeprecationWarnings." - "test_getDeprecationWarningString was deprecated in " - "Twisted 8.0.0") - - - def test_getDeprecationWarningStringWithFormat(self): - """ - L{getDeprecationWarningString} returns a string that tells us that a - callable was deprecated at a certain released version of Twisted, with - a message containing additional information about the deprecation. - """ - version = Version('Twisted', 8, 0, 0) - format = deprecate.DEPRECATION_WARNING_FORMAT + ': This is a message' - self.assertEqual( - getDeprecationWarningString(self.test_getDeprecationWarningString, - version, format), - 'twisted.python.test.test_deprecate.TestDeprecationWarnings.' - 'test_getDeprecationWarningString was deprecated in ' - 'Twisted 8.0.0: This is a message') - - - def test_deprecateEmitsWarning(self): - """ - Decorating a callable with L{deprecated} emits a warning. - """ - version = Version('Twisted', 8, 0, 0) - dummy = deprecated(version)(dummyCallable) - def addStackLevel(): - dummy() - self.assertWarns( - DeprecationWarning, - getDeprecationWarningString(dummyCallable, version), - __file__, - addStackLevel) - - - def test_deprecatedPreservesName(self): - """ - The decorated function has the same name as the original. - """ - version = Version('Twisted', 8, 0, 0) - dummy = deprecated(version)(dummyCallable) - self.assertEqual(dummyCallable.__name__, dummy.__name__) - self.assertEqual(fullyQualifiedName(dummyCallable), - fullyQualifiedName(dummy)) - - - def test_getDeprecationDocstring(self): - """ - L{_getDeprecationDocstring} returns a note about the deprecation to go - into a docstring. - """ - version = Version('Twisted', 8, 0, 0) - self.assertEqual( - "Deprecated in Twisted 8.0.0.", - _getDeprecationDocstring(version, '')) - - - def test_deprecatedUpdatesDocstring(self): - """ - The docstring of the deprecated function is appended with information - about the deprecation. - """ - - version = Version('Twisted', 8, 0, 0) - dummy = deprecated(version)(dummyCallable) - - _appendToDocstring( - dummyCallable, - _getDeprecationDocstring(version, '')) - - self.assertEqual(dummyCallable.__doc__, dummy.__doc__) - - - def test_versionMetadata(self): - """ - Deprecating a function adds version information to the decorated - version of that function. - """ - version = Version('Twisted', 8, 0, 0) - dummy = deprecated(version)(dummyCallable) - self.assertEqual(version, dummy.deprecatedVersion) - - - def test_getDeprecationWarningStringReplacement(self): - """ - L{getDeprecationWarningString} takes an additional replacement parameter - that can be used to add information to the deprecation. If the - replacement parameter is a string, it will be interpolated directly into - the result. - """ - version = Version('Twisted', 8, 0, 0) - warningString = getDeprecationWarningString( - self.test_getDeprecationWarningString, version, - replacement="something.foobar") - self.assertEqual( - warningString, - "%s was deprecated in Twisted 8.0.0; please use something.foobar " - "instead" % ( - fullyQualifiedName(self.test_getDeprecationWarningString),)) - - - def test_getDeprecationWarningStringReplacementWithCallable(self): - """ - L{getDeprecationWarningString} takes an additional replacement parameter - that can be used to add information to the deprecation. If the - replacement parameter is a callable, its fully qualified name will be - interpolated into the result. - """ - version = Version('Twisted', 8, 0, 0) - warningString = getDeprecationWarningString( - self.test_getDeprecationWarningString, version, - replacement=dummyReplacementMethod) - self.assertEqual( - warningString, - "%s was deprecated in Twisted 8.0.0; please use " - "twisted.python.test.test_deprecate.dummyReplacementMethod " - "instead" % ( - fullyQualifiedName(self.test_getDeprecationWarningString),)) - - - def test_deprecatedReplacement(self): - """ - L{deprecated} takes an additional replacement parameter that can be used - to indicate the new, non-deprecated method developers should use. If - the replacement parameter is a string, it will be interpolated directly - into the warning message. - """ - version = Version('Twisted', 8, 0, 0) - dummy = deprecated(version, "something.foobar")(dummyCallable) - self.assertEqual(dummy.__doc__, - "\n" - " Do nothing.\n\n" - " This is used to test the deprecation decorators.\n\n" - " Deprecated in Twisted 8.0.0; please use " - "something.foobar" - " instead.\n" - " ") - - - def test_deprecatedReplacementWithCallable(self): - """ - L{deprecated} takes an additional replacement parameter that can be used - to indicate the new, non-deprecated method developers should use. If - the replacement parameter is a callable, its fully qualified name will - be interpolated into the warning message. - """ - version = Version('Twisted', 8, 0, 0) - decorator = deprecated(version, replacement=dummyReplacementMethod) - dummy = decorator(dummyCallable) - self.assertEqual(dummy.__doc__, - "\n" - " Do nothing.\n\n" - " This is used to test the deprecation decorators.\n\n" - " Deprecated in Twisted 8.0.0; please use " - "twisted.python.test.test_deprecate.dummyReplacementMethod" - " instead.\n" - " ") - - - -class TestAppendToDocstring(TestCase): - """ - Test the _appendToDocstring function. - - _appendToDocstring is used to add text to a docstring. - """ - - def test_appendToEmptyDocstring(self): - """ - Appending to an empty docstring simply replaces the docstring. - """ - - def noDocstring(): - pass - - _appendToDocstring(noDocstring, "Appended text.") - self.assertEqual("Appended text.", noDocstring.__doc__) - - - def test_appendToSingleLineDocstring(self): - """ - Appending to a single line docstring places the message on a new line, - with a blank line separating it from the rest of the docstring. - - The docstring ends with a newline, conforming to Twisted and PEP 8 - standards. Unfortunately, the indentation is incorrect, since the - existing docstring doesn't have enough info to help us indent - properly. - """ - - def singleLineDocstring(): - """This doesn't comply with standards, but is here for a test.""" - - _appendToDocstring(singleLineDocstring, "Appended text.") - self.assertEqual( - ["This doesn't comply with standards, but is here for a test.", - "", - "Appended text."], - singleLineDocstring.__doc__.splitlines()) - self.assertTrue(singleLineDocstring.__doc__.endswith('\n')) - - - def test_appendToMultilineDocstring(self): - """ - Appending to a multi-line docstring places the messade on a new line, - with a blank line separating it from the rest of the docstring. - - Because we have multiple lines, we have enough information to do - indentation. - """ - - def multiLineDocstring(): - """ - This is a multi-line docstring. - """ - - def expectedDocstring(): - """ - This is a multi-line docstring. - - Appended text. - """ - - _appendToDocstring(multiLineDocstring, "Appended text.") - self.assertEqual( - expectedDocstring.__doc__, multiLineDocstring.__doc__) - - - -class _MockDeprecatedAttribute(object): - """ - Mock of L{twisted.python.deprecate._DeprecatedAttribute}. - - @ivar value: The value of the attribute. - """ - def __init__(self, value): - self.value = value - - - def get(self): - """ - Get a known value. - """ - return self.value - - - -class ModuleProxyTests(TestCase): - """ - Tests for L{twisted.python.deprecate._ModuleProxy}, which proxies - access to module-level attributes, intercepting access to deprecated - attributes and passing through access to normal attributes. - """ - def _makeProxy(self, **attrs): - """ - Create a temporary module proxy object. - - @param **kw: Attributes to initialise on the temporary module object - - @rtype: L{twistd.python.deprecate._ModuleProxy} - """ - mod = types.ModuleType('foo') - for key, value in attrs.iteritems(): - setattr(mod, key, value) - return deprecate._ModuleProxy(mod) - - - def test_getattrPassthrough(self): - """ - Getting a normal attribute on a L{twisted.python.deprecate._ModuleProxy} - retrieves the underlying attribute's value, and raises C{AttributeError} - if a non-existant attribute is accessed. - """ - proxy = self._makeProxy(SOME_ATTRIBUTE='hello') - self.assertIdentical(proxy.SOME_ATTRIBUTE, 'hello') - self.assertRaises(AttributeError, getattr, proxy, 'DOES_NOT_EXIST') - - - def test_getattrIntercept(self): - """ - Getting an attribute marked as being deprecated on - L{twisted.python.deprecate._ModuleProxy} results in calling the - deprecated wrapper's C{get} method. - """ - proxy = self._makeProxy() - _deprecatedAttributes = object.__getattribute__( - proxy, '_deprecatedAttributes') - _deprecatedAttributes['foo'] = _MockDeprecatedAttribute(42) - self.assertEqual(proxy.foo, 42) - - - def test_privateAttributes(self): - """ - Private attributes of L{twisted.python.deprecate._ModuleProxy} are - inaccessible when regular attribute access is used. - """ - proxy = self._makeProxy() - self.assertRaises(AttributeError, getattr, proxy, '_module') - self.assertRaises( - AttributeError, getattr, proxy, '_deprecatedAttributes') - - - def test_setattr(self): - """ - Setting attributes on L{twisted.python.deprecate._ModuleProxy} proxies - them through to the wrapped module. - """ - proxy = self._makeProxy() - proxy._module = 1 - self.assertNotEquals(object.__getattribute__(proxy, '_module'), 1) - self.assertEqual(proxy._module, 1) - - - def test_repr(self): - """ - L{twisted.python.deprecated._ModuleProxy.__repr__} produces a string - containing the proxy type and a representation of the wrapped module - object. - """ - proxy = self._makeProxy() - realModule = object.__getattribute__(proxy, '_module') - self.assertEqual( - repr(proxy), '<%s module=%r>' % (type(proxy).__name__, realModule)) - - - -class DeprecatedAttributeTests(TestCase): - """ - Tests for L{twisted.python.deprecate._DeprecatedAttribute} and - L{twisted.python.deprecate.deprecatedModuleAttribute}, which issue - warnings for deprecated module-level attributes. - """ - def setUp(self): - self.version = deprecatedattributes.version - self.message = deprecatedattributes.message - self._testModuleName = __name__ + '.foo' - - - def _getWarningString(self, attr): - """ - Create the warning string used by deprecated attributes. - """ - return _getDeprecationWarningString( - deprecatedattributes.__name__ + '.' + attr, - deprecatedattributes.version, - DEPRECATION_WARNING_FORMAT + ': ' + deprecatedattributes.message) - - - def test_deprecatedAttributeHelper(self): - """ - L{twisted.python.deprecate._DeprecatedAttribute} correctly sets its - __name__ to match that of the deprecated attribute and emits a warning - when the original attribute value is accessed. - """ - name = 'ANOTHER_DEPRECATED_ATTRIBUTE' - setattr(deprecatedattributes, name, 42) - attr = deprecate._DeprecatedAttribute( - deprecatedattributes, name, self.version, self.message) - - self.assertEqual(attr.__name__, name) - - # Since we're accessing the value getter directly, as opposed to via - # the module proxy, we need to match the warning's stack level. - def addStackLevel(): - attr.get() - - # Access the deprecated attribute. - addStackLevel() - warningsShown = self.flushWarnings([ - self.test_deprecatedAttributeHelper]) - self.assertIdentical(warningsShown[0]['category'], DeprecationWarning) - self.assertEqual( - warningsShown[0]['message'], - self._getWarningString(name)) - self.assertEqual(len(warningsShown), 1) - - - def test_deprecatedAttribute(self): - """ - L{twisted.python.deprecate.deprecatedModuleAttribute} wraps a - module-level attribute in an object that emits a deprecation warning - when it is accessed the first time only, while leaving other unrelated - attributes alone. - """ - # Accessing non-deprecated attributes does not issue a warning. - deprecatedattributes.ANOTHER_ATTRIBUTE - warningsShown = self.flushWarnings([self.test_deprecatedAttribute]) - self.assertEqual(len(warningsShown), 0) - - name = 'DEPRECATED_ATTRIBUTE' - - # Access the deprecated attribute. This uses getattr to avoid repeating - # the attribute name. - getattr(deprecatedattributes, name) - - warningsShown = self.flushWarnings([self.test_deprecatedAttribute]) - self.assertEqual(len(warningsShown), 1) - self.assertIdentical(warningsShown[0]['category'], DeprecationWarning) - self.assertEqual( - warningsShown[0]['message'], - self._getWarningString(name)) - - - def test_wrappedModule(self): - """ - Deprecating an attribute in a module replaces and wraps that module - instance, in C{sys.modules}, with a - L{twisted.python.deprecate._ModuleProxy} instance but only if it hasn't - already been wrapped. - """ - sys.modules[self._testModuleName] = mod = types.ModuleType('foo') - self.addCleanup(sys.modules.pop, self._testModuleName) - - setattr(mod, 'first', 1) - setattr(mod, 'second', 2) - - deprecate.deprecatedModuleAttribute( - Version('Twisted', 8, 0, 0), - 'message', - self._testModuleName, - 'first') - - proxy = sys.modules[self._testModuleName] - self.assertNotEqual(proxy, mod) - - deprecate.deprecatedModuleAttribute( - Version('Twisted', 8, 0, 0), - 'message', - self._testModuleName, - 'second') - - self.assertIdentical(proxy, sys.modules[self._testModuleName]) - - - -class ImportedModuleAttributeTests(TwistedModulesTestCase): - """ - Tests for L{deprecatedModuleAttribute} which involve loading a module via - 'import'. - """ - - _packageInit = """\ -from twisted.python.deprecate import deprecatedModuleAttribute -from twisted.python.versions import Version - -deprecatedModuleAttribute( - Version('Package', 1, 2, 3), 'message', __name__, 'module') -""" - - - 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, str): - 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()) - base.makedirs() - - result = makeSomeFiles(base, tree) - self.replaceSysPath([base.path] + sys.path) - self.replaceSysModules(sys.modules.copy()) - return result - - - def simpleModuleEntry(self): - """ - Add a sample module and package to the path, returning a L{FilePath} - pointing at the module which will be loadable as C{package.module}. - """ - paths = self.pathEntryTree( - {"package": {"__init__.py": self._packageInit, - "module.py": ""}}) - return paths['package']['module.py'] - - - def checkOneWarning(self, modulePath): - """ - Verification logic for L{test_deprecatedModule}. - """ - # import package.module - from package import module - self.assertEqual(module.__file__, modulePath.path) - emitted = self.flushWarnings([self.checkOneWarning]) - self.assertEqual(len(emitted), 1) - self.assertEqual(emitted[0]['message'], - 'package.module was deprecated in Package 1.2.3: ' - 'message') - self.assertEqual(emitted[0]['category'], DeprecationWarning) - - - def test_deprecatedModule(self): - """ - If L{deprecatedModuleAttribute} is used to deprecate a module attribute - of a package, only one deprecation warning is emitted when the - deprecated module is imported. - """ - self.checkOneWarning(self.simpleModuleEntry()) - - - def test_deprecatedModuleMultipleTimes(self): - """ - If L{deprecatedModuleAttribute} is used to deprecate a module attribute - of a package, only one deprecation warning is emitted when the - deprecated module is subsequently imported. - """ - mp = self.simpleModuleEntry() - # The first time, the code needs to be loaded. - self.checkOneWarning(mp) - # The second time, things are slightly different; the object's already - # in the namespace. - self.checkOneWarning(mp) - # The third and fourth times, things things should all be exactly the - # same, but this is a sanity check to make sure the implementation isn't - # special casing the second time. Also, putting these cases into a loop - # means that the stack will be identical, to make sure that the - # implementation doesn't rely too much on stack-crawling. - for x in range(2): - self.checkOneWarning(mp) - - - -class WarnAboutFunctionTests(TestCase): - """ - 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()).child('twisted_private_helper') - self.package.makedirs() - self.package.child('__init__.py').setContent('') - self.package.child('module.py').setContent(''' -"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") -''') - sys.path.insert(0, self.package.parent().path) - self.addCleanup(sys.path.remove, self.package.parent().path) - - modules = sys.modules.copy() - self.addCleanup( - lambda: (sys.modules.clear(), sys.modules.update(modules))) - - - 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"]), - self.package.sibling('twisted_private_helper').child('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 - the deprecated function. - """ - 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__] - - # Rename the source directory - self.package.moveTo(self.package.sibling('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__) - - module.callTestFunction() - warningsShown = self.flushWarnings() - warnedPath = FilePath(warningsShown[0]["filename"]) - expectedPath = self.package.sibling( - 'twisted_renamed_helper').child('module.py') - self.assertSamePath(warnedPath, expectedPath) - self.assertEqual(warningsShown[0]["lineno"], 9) - self.assertEqual(warningsShown[0]["message"], "A Warning String") - self.assertEqual(len(warningsShown), 1) - - - def test_filteredWarning(self): - """ - L{deprecate.warnAboutFunction} emits a warning that will be filtered if - L{warnings.filterwarning} is called with the module name of the - deprecated function. - """ - # Clean up anything *else* that might spuriously filter out the warning, - # such as the "always" simplefilter set up by unittest._collectWarnings. - # We'll also rely on trial to restore the original filters afterwards. - del warnings.filters[:] - - warnings.filterwarnings( - action="ignore", module="twisted_private_helper") - - from twisted_private_helper import module - module.callTestFunction() - - warningsShown = self.flushWarnings() - self.assertEqual(len(warningsShown), 0) - - - def test_filteredOnceWarning(self): - """ - L{deprecate.warnAboutFunction} emits a warning that will be filtered - once if L{warnings.filterwarning} is called with the module name of the - deprecated function and an action of once. - """ - # Clean up anything *else* that might spuriously filter out the warning, - # such as the "always" simplefilter set up by unittest._collectWarnings. - # We'll also rely on trial to restore the original filters afterwards. - del warnings.filters[:] - - warnings.filterwarnings( - action="module", module="twisted_private_helper") - - from twisted_private_helper import module - module.callTestFunction() - module.callTestFunction() - - warningsShown = self.flushWarnings() - self.assertEqual(len(warningsShown), 1) - message = warningsShown[0]['message'] - category = warningsShown[0]['category'] - filename = warningsShown[0]['filename'] - lineno = warningsShown[0]['lineno'] - msg = warnings.formatwarning(message, category, filename, lineno) - self.assertTrue( - msg.endswith("module.py:9: DeprecationWarning: A Warning String\n" - " return a\n"), - "Unexpected warning string: %r" % (msg,)) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_dist.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_dist.py deleted file mode 100755 index 34c67896..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_dist.py +++ /dev/null @@ -1,526 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for parts of our release automation system. -""" - - -import os -import sys - -from distutils.core import Distribution - -from twisted.trial.unittest import TestCase - -from twisted.python import dist -from twisted.python.dist import (get_setup_args, ConditionalExtension, - build_scripts_twisted) -from twisted.python.filepath import FilePath - - - -class SetupTest(TestCase): - """ - Tests for L{get_setup_args}. - """ - def test_conditionalExtensions(self): - """ - Passing C{conditionalExtensions} as a list of L{ConditionalExtension} - objects to get_setup_args inserts a custom build_ext into the result - which knows how to check whether they should be built. - """ - good_ext = ConditionalExtension("whatever", ["whatever.c"], - condition=lambda b: True) - bad_ext = ConditionalExtension("whatever", ["whatever.c"], - condition=lambda b: False) - args = get_setup_args(conditionalExtensions=[good_ext, bad_ext]) - # ext_modules should be set even though it's not used. See comment - # in get_setup_args - self.assertEqual(args["ext_modules"], [good_ext, bad_ext]) - cmdclass = args["cmdclass"] - build_ext = cmdclass["build_ext"] - builder = build_ext(Distribution()) - builder.prepare_extensions() - self.assertEqual(builder.extensions, [good_ext]) - - - def test_win32Definition(self): - """ - When building on Windows NT, the WIN32 macro will be defined as 1. - """ - ext = ConditionalExtension("whatever", ["whatever.c"], - define_macros=[("whatever", 2)]) - args = get_setup_args(conditionalExtensions=[ext]) - builder = args["cmdclass"]["build_ext"](Distribution()) - self.patch(os, "name", "nt") - builder.prepare_extensions() - self.assertEqual(ext.define_macros, [("whatever", 2), ("WIN32", 1)]) - - - -class GetExtensionsTest(TestCase): - """ - Tests for L{dist.getExtensions}. - """ - - setupTemplate = ( - "from twisted.python.dist import ConditionalExtension\n" - "extensions = [\n" - " ConditionalExtension(\n" - " '%s', ['twisted/some/thing.c'],\n" - " condition=lambda builder: True)\n" - " ]\n") - - def setUp(self): - self.basedir = FilePath(self.mktemp()).child("twisted") - self.basedir.makedirs() - self.addCleanup(os.chdir, os.getcwd()) - os.chdir(self.basedir.parent().path) - - - def writeSetup(self, name, *path): - """ - Write out a C{setup.py} file to a location determined by - L{self.basedir} and L{path}. L{self.setupTemplate} is used to - generate its contents. - """ - outdir = self.basedir.descendant(path) - outdir.makedirs() - setup = outdir.child("setup.py") - setup.setContent(self.setupTemplate % (name,)) - - - def writeEmptySetup(self, *path): - """ - Write out an empty C{setup.py} file to a location determined by - L{self.basedir} and L{path}. - """ - outdir = self.basedir.descendant(path) - outdir.makedirs() - outdir.child("setup.py").setContent("") - - - def assertExtensions(self, expected): - """ - Assert that the given names match the (sorted) names of discovered - extensions. - """ - extensions = dist.getExtensions() - names = [extension.name for extension in extensions] - self.assertEqual(sorted(names), expected) - - - def test_getExtensions(self): - """ - Files named I{setup.py} in I{twisted/topfiles} and I{twisted/*/topfiles} - are executed with L{execfile} in order to discover the extensions they - declare. - """ - self.writeSetup("twisted.transmutate", "topfiles") - self.writeSetup("twisted.tele.port", "tele", "topfiles") - self.assertExtensions(["twisted.tele.port", "twisted.transmutate"]) - - - def test_getExtensionsTooDeep(self): - """ - Files named I{setup.py} in I{topfiles} directories are not considered if - they are too deep in the directory hierarchy. - """ - self.writeSetup("twisted.trans.mog.rify", "trans", "mog", "topfiles") - self.assertExtensions([]) - - - def test_getExtensionsNotTopfiles(self): - """ - The folder in which I{setup.py} is discovered must be called I{topfiles} - otherwise it is ignored. - """ - self.writeSetup("twisted.metamorphosis", "notfiles") - self.assertExtensions([]) - - - def test_getExtensionsNotSupportedOnJava(self): - """ - Extensions are not supported on Java-based platforms. - """ - self.addCleanup(setattr, sys, "platform", sys.platform) - sys.platform = "java" - self.writeSetup("twisted.sorcery", "topfiles") - self.assertExtensions([]) - - - def test_getExtensionsExtensionsLocalIsOptional(self): - """ - It is acceptable for extensions to not define the C{extensions} local - variable. - """ - self.writeEmptySetup("twisted.necromancy", "topfiles") - self.assertExtensions([]) - - - -class GetVersionTest(TestCase): - """ - Tests for L{dist.getVersion}. - """ - - def setUp(self): - self.dirname = self.mktemp() - os.mkdir(self.dirname) - - def test_getVersionCore(self): - """ - Test that getting the version of core reads from the - [base]/_version.py file. - """ - f = open(os.path.join(self.dirname, "_version.py"), "w") - f.write(""" -from twisted.python import versions -version = versions.Version("twisted", 0, 1, 2) -""") - f.close() - self.assertEqual(dist.getVersion("core", base=self.dirname), "0.1.2") - - def test_getVersionOther(self): - """ - Test that getting the version of a non-core project reads from - the [base]/[projname]/_version.py file. - """ - os.mkdir(os.path.join(self.dirname, "blat")) - f = open(os.path.join(self.dirname, "blat", "_version.py"), "w") - f.write(""" -from twisted.python import versions -version = versions.Version("twisted.blat", 9, 8, 10) -""") - f.close() - self.assertEqual(dist.getVersion("blat", base=self.dirname), "9.8.10") - - - -class GetScriptsTest(TestCase): - """ - Tests for L{dist.getScripts} which returns the scripts which should be - included in the distribution of a project. - """ - - def test_scriptsInSVN(self): - """ - getScripts should return the scripts associated with a project - in the context of Twisted SVN. - """ - basedir = self.mktemp() - os.mkdir(basedir) - os.mkdir(os.path.join(basedir, 'bin')) - os.mkdir(os.path.join(basedir, 'bin', 'proj')) - f = open(os.path.join(basedir, 'bin', 'proj', 'exy'), 'w') - f.write('yay') - f.close() - scripts = dist.getScripts('proj', basedir=basedir) - self.assertEqual(len(scripts), 1) - self.assertEqual(os.path.basename(scripts[0]), 'exy') - - - def test_excludedPreamble(self): - """ - L{dist.getScripts} includes neither C{"_preamble.py"} nor - C{"_preamble.pyc"}. - """ - basedir = FilePath(self.mktemp()) - bin = basedir.child('bin') - bin.makedirs() - bin.child('_preamble.py').setContent('some preamble code\n') - bin.child('_preamble.pyc').setContent('some preamble byte code\n') - bin.child('program').setContent('good program code\n') - scripts = dist.getScripts("", basedir=basedir.path) - self.assertEqual(scripts, [bin.child('program').path]) - - - def test_scriptsInRelease(self): - """ - getScripts should return the scripts associated with a project - in the context of a released subproject tarball. - """ - basedir = self.mktemp() - os.mkdir(basedir) - os.mkdir(os.path.join(basedir, 'bin')) - f = open(os.path.join(basedir, 'bin', 'exy'), 'w') - f.write('yay') - f.close() - scripts = dist.getScripts('proj', basedir=basedir) - self.assertEqual(len(scripts), 1) - self.assertEqual(os.path.basename(scripts[0]), 'exy') - - - def test_noScriptsInSVN(self): - """ - When calling getScripts for a project which doesn't actually - have any scripts, in the context of an SVN checkout, an - empty list should be returned. - """ - basedir = self.mktemp() - os.mkdir(basedir) - os.mkdir(os.path.join(basedir, 'bin')) - os.mkdir(os.path.join(basedir, 'bin', 'otherproj')) - scripts = dist.getScripts('noscripts', basedir=basedir) - self.assertEqual(scripts, []) - - - def test_getScriptsTopLevel(self): - """ - Passing the empty string to getScripts returns scripts that are (only) - in the top level bin directory. - """ - basedir = FilePath(self.mktemp()) - basedir.createDirectory() - bindir = basedir.child("bin") - bindir.createDirectory() - included = bindir.child("included") - included.setContent("yay included") - subdir = bindir.child("subdir") - subdir.createDirectory() - subdir.child("not-included").setContent("not included") - - scripts = dist.getScripts("", basedir=basedir.path) - self.assertEqual(scripts, [included.path]) - - - def test_noScriptsInSubproject(self): - """ - When calling getScripts for a project which doesn't actually - have any scripts in the context of that project's individual - project structure, an empty list should be returned. - """ - basedir = self.mktemp() - os.mkdir(basedir) - scripts = dist.getScripts('noscripts', basedir=basedir) - self.assertEqual(scripts, []) - - - -class DummyCommand: - """ - A fake Command. - """ - def __init__(self, **kwargs): - for kw, val in kwargs.items(): - setattr(self, kw, val) - - def ensure_finalized(self): - pass - - - -class BuildScriptsTest(TestCase): - """ - Tests for L{dist.build_scripts_twisted}. - """ - - def setUp(self): - self.source = FilePath(self.mktemp()) - self.target = FilePath(self.mktemp()) - self.source.makedirs() - self.addCleanup(os.chdir, os.getcwd()) - os.chdir(self.source.path) - - - def buildScripts(self): - """ - Write 3 types of scripts and run the L{build_scripts_twisted} - command. - """ - self.writeScript(self.source, "script1", - ("#! /usr/bin/env python2.7\n" - "# bogus script w/ Python sh-bang\n" - "pass\n")) - - self.writeScript(self.source, "script2.py", - ("#!/usr/bin/python\n" - "# bogus script w/ Python sh-bang\n" - "pass\n")) - - self.writeScript(self.source, "shell.sh", - ("#!/bin/sh\n" - "# bogus shell script w/ sh-bang\n" - "exit 0\n")) - - expected = ['script1', 'script2.py', 'shell.sh'] - cmd = self.getBuildScriptsCmd(self.target, - [self.source.child(fn).path - for fn in expected]) - cmd.finalize_options() - cmd.run() - - return self.target.listdir() - - - def getBuildScriptsCmd(self, target, scripts): - """ - Create a distutils L{Distribution} with a L{DummyCommand} and wrap it - in L{build_scripts_twisted}. - - @type target: L{FilePath} - """ - dist = Distribution() - dist.scripts = scripts - dist.command_obj["build"] = DummyCommand( - build_scripts = target.path, - force = 1, - executable = sys.executable - ) - return build_scripts_twisted(dist) - - - def writeScript(self, dir, name, text): - """ - Write the script to disk. - """ - with open(dir.child(name).path, "w") as f: - f.write(text) - - - def test_notWindows(self): - """ - L{build_scripts_twisted} does not rename scripts on non-Windows - platforms. - """ - self.patch(os, "name", "twisted") - built = self.buildScripts() - for name in ['script1', 'script2.py', 'shell.sh']: - self.assertTrue(name in built) - - - def test_windows(self): - """ - L{build_scripts_twisted} renames scripts so they end with '.py' on - the Windows platform. - """ - self.patch(os, "name", "nt") - built = self.buildScripts() - for name in ['script1.py', 'script2.py', 'shell.sh.py']: - self.assertTrue(name in built) - - - -class FakeModule(object): - """ - A fake module, suitable for dependency injection in testing. - """ - def __init__(self, attrs): - """ - Initializes a fake module. - - @param attrs: The attrs that will be accessible on the module. - @type attrs: C{dict} of C{str} (Python names) to objects - """ - self._attrs = attrs - - - def __getattr__(self, name): - """ - Gets an attribute of this fake module from its attrs. - - @raise AttributeError: When the requested attribute is missing. - """ - try: - return self._attrs[name] - except KeyError: - raise AttributeError() - - - -fakeCPythonPlatform = FakeModule({"python_implementation": lambda: "CPython"}) -fakeOtherPlatform = FakeModule({"python_implementation": lambda: "lvhpy"}) -emptyPlatform = FakeModule({}) - - - -class WithPlatformTests(TestCase): - """ - Tests for L{_checkCPython} when used with a (fake) recent C{platform} - module. - """ - def test_cpython(self): - """ - L{_checkCPython} returns C{True} when C{platform.python_implementation} - says we're running on CPython. - """ - self.assertTrue(dist._checkCPython(platform=fakeCPythonPlatform)) - - - def test_other(self): - """ - L{_checkCPython} returns C{False} when C{platform.python_implementation} - says we're not running on CPython. - """ - self.assertFalse(dist._checkCPython(platform=fakeOtherPlatform)) - - - -fakeCPythonSys = FakeModule({"subversion": ("CPython", None, None)}) -fakeOtherSys = FakeModule({"subversion": ("lvhpy", None, None)}) - - -def _checkCPythonWithEmptyPlatform(sys): - """ - A partially applied L{_checkCPython} that uses an empty C{platform} - module (otherwise the code this test case is supposed to test won't - even be called). - """ - return dist._checkCPython(platform=emptyPlatform, sys=sys) - - - -class WithSubversionTest(TestCase): - """ - Tests for L{_checkCPython} when used with a (fake) recent (2.5+) - C{sys.subversion}. This is effectively only relevant for 2.5, since 2.6 and - beyond have L{platform.python_implementation}, which is tried first. - """ - def test_cpython(self): - """ - L{_checkCPython} returns C{True} when C{platform.python_implementation} - is unavailable and C{sys.subversion} says we're running on CPython. - """ - isCPython = _checkCPythonWithEmptyPlatform(fakeCPythonSys) - self.assertTrue(isCPython) - - - def test_other(self): - """ - L{_checkCPython} returns C{False} when C{platform.python_implementation} - is unavailable and C{sys.subversion} says we're not running on CPython. - """ - isCPython = _checkCPythonWithEmptyPlatform(fakeOtherSys) - self.assertFalse(isCPython) - - - -oldCPythonSys = FakeModule({"modules": {}}) -oldPypySys = FakeModule({"modules": {"__pypy__": None}}) - - -class OldPythonsFallbackTest(TestCase): - """ - Tests for L{_checkCPython} when used on a Python 2.4-like platform, when - neither C{platform.python_implementation} nor C{sys.subversion} is - available. - """ - def test_cpython(self): - """ - L{_checkCPython} returns C{True} when both - C{platform.python_implementation} and C{sys.subversion} are unavailable - and there is no C{__pypy__} module in C{sys.modules}. - """ - isCPython = _checkCPythonWithEmptyPlatform(oldCPythonSys) - self.assertTrue(isCPython) - - - def test_pypy(self): - """ - L{_checkCPython} returns C{False} when both - C{platform.python_implementation} and C{sys.subversion} are unavailable - and there is a C{__pypy__} module in C{sys.modules}. - """ - isCPython = _checkCPythonWithEmptyPlatform(oldPypySys) - self.assertFalse(isCPython) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_fakepwd.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_fakepwd.py deleted file mode 100755 index 6c101056..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_fakepwd.py +++ /dev/null @@ -1,386 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for L{twisted.python.fakepwd}. -""" - -try: - import pwd -except ImportError: - pwd = None - -try: - import spwd -except ImportError: - spwd = None - -import os -from operator import getitem - -from twisted.trial.unittest import TestCase -from twisted.python.fakepwd import UserDatabase, ShadowDatabase -from twisted.python.compat import set - - -class UserDatabaseTestsMixin: - """ - L{UserDatabaseTestsMixin} defines tests which apply to any user database - implementation. Subclasses should mix it in, implement C{setUp} to create - C{self.database} bound to a user database instance, and implement - C{getExistingUserInfo} to return information about a user (such information - should be unique per test method). - """ - def test_getpwuid(self): - """ - I{getpwuid} accepts a uid and returns the user record associated with - it. - """ - for i in range(2): - # Get some user which exists in the database. - username, password, uid, gid, gecos, dir, shell = self.getExistingUserInfo() - - # Now try to look it up and make sure the result is correct. - entry = self.database.getpwuid(uid) - self.assertEqual(entry.pw_name, username) - self.assertEqual(entry.pw_passwd, password) - self.assertEqual(entry.pw_uid, uid) - self.assertEqual(entry.pw_gid, gid) - self.assertEqual(entry.pw_gecos, gecos) - self.assertEqual(entry.pw_dir, dir) - self.assertEqual(entry.pw_shell, shell) - - - def test_noSuchUID(self): - """ - I{getpwuid} raises L{KeyError} when passed a uid which does not exist - in the user database. - """ - self.assertRaises(KeyError, self.database.getpwuid, -13) - - - def test_getpwnam(self): - """ - I{getpwnam} accepts a username and returns the user record associated - with it. - """ - for i in range(2): - # Get some user which exists in the database. - username, password, uid, gid, gecos, dir, shell = self.getExistingUserInfo() - - # Now try to look it up and make sure the result is correct. - entry = self.database.getpwnam(username) - self.assertEqual(entry.pw_name, username) - self.assertEqual(entry.pw_passwd, password) - self.assertEqual(entry.pw_uid, uid) - self.assertEqual(entry.pw_gid, gid) - self.assertEqual(entry.pw_gecos, gecos) - self.assertEqual(entry.pw_dir, dir) - self.assertEqual(entry.pw_shell, shell) - - - def test_noSuchName(self): - """ - I{getpwnam} raises L{KeyError} when passed a username which does not - exist in the user database. - """ - self.assertRaises( - KeyError, self.database.getpwnam, - 'no' 'such' 'user' 'exists' 'the' 'name' 'is' 'too' 'long' 'and' 'has' - '\1' 'in' 'it' 'too') - - - def test_recordLength(self): - """ - The user record returned by I{getpwuid}, I{getpwnam}, and I{getpwall} - has a length. - """ - db = self.database - username, password, uid, gid, gecos, dir, shell = self.getExistingUserInfo() - for entry in [db.getpwuid(uid), db.getpwnam(username), db.getpwall()[0]]: - self.assertIsInstance(len(entry), int) - self.assertEqual(len(entry), 7) - - - def test_recordIndexable(self): - """ - The user record returned by I{getpwuid}, I{getpwnam}, and I{getpwall} - is indexable, with successive indexes starting from 0 corresponding to - the values of the C{pw_name}, C{pw_passwd}, C{pw_uid}, C{pw_gid}, - C{pw_gecos}, C{pw_dir}, and C{pw_shell} attributes, respectively. - """ - db = self.database - username, password, uid, gid, gecos, dir, shell = self.getExistingUserInfo() - for entry in [db.getpwuid(uid), db.getpwnam(username), db.getpwall()[0]]: - self.assertEqual(entry[0], username) - self.assertEqual(entry[1], password) - self.assertEqual(entry[2], uid) - self.assertEqual(entry[3], gid) - self.assertEqual(entry[4], gecos) - self.assertEqual(entry[5], dir) - self.assertEqual(entry[6], shell) - - self.assertEqual(len(entry), len(list(entry))) - self.assertRaises(IndexError, getitem, entry, 7) - - - -class UserDatabaseTests(TestCase, UserDatabaseTestsMixin): - """ - Tests for L{UserDatabase}. - """ - def setUp(self): - """ - Create a L{UserDatabase} with no user data in it. - """ - self.database = UserDatabase() - self._counter = 0 - - - def getExistingUserInfo(self): - """ - Add a new user to C{self.database} and return its information. - """ - self._counter += 1 - suffix = '_' + str(self._counter) - username = 'username' + suffix - password = 'password' + suffix - uid = self._counter - gid = self._counter + 1000 - gecos = 'gecos' + suffix - dir = 'dir' + suffix - shell = 'shell' + suffix - - self.database.addUser(username, password, uid, gid, gecos, dir, shell) - return (username, password, uid, gid, gecos, dir, shell) - - - def test_addUser(self): - """ - L{UserDatabase.addUser} accepts seven arguments, one for each field of - a L{pwd.struct_passwd}, and makes the new record available via - L{UserDatabase.getpwuid}, L{UserDatabase.getpwnam}, and - L{UserDatabase.getpwall}. - """ - username = 'alice' - password = 'secr3t' - uid = 123 - gid = 456 - gecos = 'Alice,,,' - home = '/users/alice' - shell = '/usr/bin/foosh' - - db = self.database - db.addUser(username, password, uid, gid, gecos, home, shell) - - for [entry] in [[db.getpwuid(uid)], [db.getpwnam(username)], - db.getpwall()]: - self.assertEqual(entry.pw_name, username) - self.assertEqual(entry.pw_passwd, password) - self.assertEqual(entry.pw_uid, uid) - self.assertEqual(entry.pw_gid, gid) - self.assertEqual(entry.pw_gecos, gecos) - self.assertEqual(entry.pw_dir, home) - self.assertEqual(entry.pw_shell, shell) - - - -class PwdModuleTests(TestCase, UserDatabaseTestsMixin): - """ - L{PwdModuleTests} runs the tests defined by L{UserDatabaseTestsMixin} - against the built-in C{pwd} module. This serves to verify that - L{UserDatabase} is really a fake of that API. - """ - if pwd is None: - skip = "Cannot verify UserDatabase against pwd without pwd" - else: - database = pwd - - def setUp(self): - self._users = iter(self.database.getpwall()) - self._uids = set() - - - def getExistingUserInfo(self): - """ - Read and return the next record from C{self._users}, filtering out - any records with previously seen uid values (as these cannot be - found with C{getpwuid} and only cause trouble). - """ - while True: - entry = next(self._users) - uid = entry.pw_uid - if uid not in self._uids: - self._uids.add(uid) - return entry - - - -class ShadowDatabaseTestsMixin: - """ - L{ShadowDatabaseTestsMixin} defines tests which apply to any shadow user - database implementation. Subclasses should mix it in, implement C{setUp} to - create C{self.database} bound to a shadow user database instance, and - implement C{getExistingUserInfo} to return information about a user (such - information should be unique per test method). - """ - def test_getspnam(self): - """ - L{getspnam} accepts a username and returns the user record associated - with it. - """ - for i in range(2): - # Get some user which exists in the database. - (username, password, lastChange, min, max, warn, inact, expire, - flag) = self.getExistingUserInfo() - - entry = self.database.getspnam(username) - self.assertEqual(entry.sp_nam, username) - self.assertEqual(entry.sp_pwd, password) - self.assertEqual(entry.sp_lstchg, lastChange) - self.assertEqual(entry.sp_min, min) - self.assertEqual(entry.sp_max, max) - self.assertEqual(entry.sp_warn, warn) - self.assertEqual(entry.sp_inact, inact) - self.assertEqual(entry.sp_expire, expire) - self.assertEqual(entry.sp_flag, flag) - - - def test_noSuchName(self): - """ - I{getspnam} raises L{KeyError} when passed a username which does not - exist in the user database. - """ - self.assertRaises(KeyError, self.database.getspnam, "alice") - - - def test_recordLength(self): - """ - The shadow user record returned by I{getspnam} and I{getspall} has a - length. - """ - db = self.database - username = self.getExistingUserInfo()[0] - for entry in [db.getspnam(username), db.getspall()[0]]: - self.assertIsInstance(len(entry), int) - self.assertEqual(len(entry), 9) - - - def test_recordIndexable(self): - """ - The shadow user record returned by I{getpwnam} and I{getspall} is - indexable, with successive indexes starting from 0 corresponding to the - values of the C{sp_nam}, C{sp_pwd}, C{sp_lstchg}, C{sp_min}, C{sp_max}, - C{sp_warn}, C{sp_inact}, C{sp_expire}, and C{sp_flag} attributes, - respectively. - """ - db = self.database - (username, password, lastChange, min, max, warn, inact, expire, - flag) = self.getExistingUserInfo() - for entry in [db.getspnam(username), db.getspall()[0]]: - self.assertEqual(entry[0], username) - self.assertEqual(entry[1], password) - self.assertEqual(entry[2], lastChange) - self.assertEqual(entry[3], min) - self.assertEqual(entry[4], max) - self.assertEqual(entry[5], warn) - self.assertEqual(entry[6], inact) - self.assertEqual(entry[7], expire) - self.assertEqual(entry[8], flag) - - self.assertEqual(len(entry), len(list(entry))) - self.assertRaises(IndexError, getitem, entry, 9) - - - -class ShadowDatabaseTests(TestCase, ShadowDatabaseTestsMixin): - """ - Tests for L{ShadowDatabase}. - """ - def setUp(self): - """ - Create a L{ShadowDatabase} with no user data in it. - """ - self.database = ShadowDatabase() - self._counter = 0 - - - def getExistingUserInfo(self): - """ - Add a new user to C{self.database} and return its information. - """ - self._counter += 1 - suffix = '_' + str(self._counter) - username = 'username' + suffix - password = 'password' + suffix - lastChange = self._counter + 1 - min = self._counter + 2 - max = self._counter + 3 - warn = self._counter + 4 - inact = self._counter + 5 - expire = self._counter + 6 - flag = self._counter + 7 - - self.database.addUser(username, password, lastChange, min, max, warn, - inact, expire, flag) - return (username, password, lastChange, min, max, warn, inact, - expire, flag) - - - def test_addUser(self): - """ - L{UserDatabase.addUser} accepts seven arguments, one for each field of - a L{pwd.struct_passwd}, and makes the new record available via - L{UserDatabase.getpwuid}, L{UserDatabase.getpwnam}, and - L{UserDatabase.getpwall}. - """ - username = 'alice' - password = 'secr3t' - lastChange = 17 - min = 42 - max = 105 - warn = 12 - inact = 3 - expire = 400 - flag = 3 - - db = self.database - db.addUser(username, password, lastChange, min, max, warn, inact, - expire, flag) - - for [entry] in [[db.getspnam(username)], db.getspall()]: - self.assertEqual(entry.sp_nam, username) - self.assertEqual(entry.sp_pwd, password) - self.assertEqual(entry.sp_lstchg, lastChange) - self.assertEqual(entry.sp_min, min) - self.assertEqual(entry.sp_max, max) - self.assertEqual(entry.sp_warn, warn) - self.assertEqual(entry.sp_inact, inact) - self.assertEqual(entry.sp_expire, expire) - self.assertEqual(entry.sp_flag, flag) - - - -class SPwdModuleTests(TestCase, ShadowDatabaseTestsMixin): - """ - L{SPwdModuleTests} runs the tests defined by L{ShadowDatabaseTestsMixin} - against the built-in C{spwd} module. This serves to verify that - L{ShadowDatabase} is really a fake of that API. - """ - if spwd is None: - skip = "Cannot verify ShadowDatabase against spwd without spwd" - elif os.getuid() != 0: - skip = "Cannot access shadow user database except as root" - else: - database = spwd - - def setUp(self): - self._users = iter(self.database.getspall()) - - - def getExistingUserInfo(self): - """ - Read and return the next record from C{self._users}. - """ - return next(self._users) - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_hashlib.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_hashlib.py deleted file mode 100755 index b50997c2..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_hashlib.py +++ /dev/null @@ -1,90 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for L{twisted.python.hashlib} -""" - -from twisted.trial.unittest import TestCase - -from twisted.python.hashlib import md5, sha1 - - -class HashObjectTests(TestCase): - """ - Tests for the hash object APIs presented by L{hashlib}, C{md5} and C{sha1}. - """ - def test_md5(self): - """ - L{hashlib.md5} returns an object which can be used to compute an MD5 - hash as defined by U{RFC 1321<http://www.ietf.org/rfc/rfc1321.txt>}. - """ - # Test the result using values from section A.5 of the RFC. - self.assertEqual( - md5().hexdigest(), "d41d8cd98f00b204e9800998ecf8427e") - self.assertEqual( - md5("a").hexdigest(), "0cc175b9c0f1b6a831c399e269772661") - self.assertEqual( - md5("abc").hexdigest(), "900150983cd24fb0d6963f7d28e17f72") - self.assertEqual( - md5("message digest").hexdigest(), - "f96b697d7cb7938d525a2f31aaf161d0") - self.assertEqual( - md5("abcdefghijklmnopqrstuvwxyz").hexdigest(), - "c3fcd3d76192e4007dfb496cca67e13b") - self.assertEqual( - md5("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" - "0123456789").hexdigest(), - "d174ab98d277d9f5a5611c2c9f419d9f") - self.assertEqual( - md5("1234567890123456789012345678901234567890123456789012345678901" - "2345678901234567890").hexdigest(), - "57edf4a22be3c955ac49da2e2107b67a") - - # It should have digest and update methods, too. - self.assertEqual( - md5().digest().encode('hex'), - "d41d8cd98f00b204e9800998ecf8427e") - hash = md5() - hash.update("a") - self.assertEqual( - hash.digest().encode('hex'), - "0cc175b9c0f1b6a831c399e269772661") - - # Instances of it should have a digest_size attribute - self.assertEqual(md5().digest_size, 16) - - - def test_sha1(self): - """ - L{hashlib.sha1} returns an object which can be used to compute a SHA1 - hash as defined by U{RFC 3174<http://tools.ietf.org/rfc/rfc3174.txt>}. - """ - def format(s): - return ''.join(s.split()).lower() - # Test the result using values from section 7.3 of the RFC. - self.assertEqual( - sha1("abc").hexdigest(), - format( - "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D")) - self.assertEqual( - sha1("abcdbcdecdefdefgefghfghighijhi" - "jkijkljklmklmnlmnomnopnopq").hexdigest(), - format( - "84 98 3E 44 1C 3B D2 6E BA AE 4A A1 F9 51 29 E5 E5 46 70 F1")) - - # It should have digest and update methods, too. - self.assertEqual( - sha1("abc").digest().encode('hex'), - format( - "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D")) - hash = sha1() - hash.update("abc") - self.assertEqual( - hash.digest().encode('hex'), - format( - "A9 99 3E 36 47 06 81 6A BA 3E 25 71 78 50 C2 6C 9C D0 D8 9D")) - - # Instances of it should have a digest_size attribute. - self.assertEqual( - sha1().digest_size, 20) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_htmlizer.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_htmlizer.py deleted file mode 100755 index 38e607a7..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_htmlizer.py +++ /dev/null @@ -1,41 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for L{twisted.python.htmlizer}. -""" - -from StringIO import StringIO - -from twisted.trial.unittest import TestCase -from twisted.python.htmlizer import filter - - -class FilterTests(TestCase): - """ - Tests for L{twisted.python.htmlizer.filter}. - """ - def test_empty(self): - """ - If passed an empty input file, L{filter} writes a I{pre} tag containing - only an end marker to the output file. - """ - input = StringIO("") - output = StringIO() - filter(input, output) - self.assertEqual(output.getvalue(), '<pre><span class="py-src-endmarker"></span></pre>\n') - - - def test_variable(self): - """ - If passed an input file containing a variable access, L{filter} writes - a I{pre} tag containing a I{py-src-variable} span containing the - variable. - """ - input = StringIO("foo\n") - output = StringIO() - filter(input, output) - self.assertEqual( - output.getvalue(), - '<pre><span class="py-src-variable">foo</span><span class="py-src-newline">\n' - '</span><span class="py-src-endmarker"></span></pre>\n') diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_inotify.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_inotify.py deleted file mode 100755 index a6cea65e..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_inotify.py +++ /dev/null @@ -1,120 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for L{twisted.python._inotify}. -""" - -from twisted.trial.unittest import TestCase -from twisted.python.runtime import platform - -if platform.supportsINotify(): - from ctypes import c_int, c_uint32, c_char_p - from twisted.python import _inotify - from twisted.python._inotify import ( - INotifyError, initializeModule, init, add) -else: - _inotify = None - - - -class INotifyTests(TestCase): - """ - Tests for L{twisted.python._inotify}. - """ - if _inotify is None: - skip = "This platform doesn't support INotify." - - def test_missingInit(self): - """ - If the I{libc} object passed to L{initializeModule} has no - C{inotify_init} attribute, L{ImportError} is raised. - """ - class libc: - def inotify_add_watch(self): - pass - def inotify_rm_watch(self): - pass - self.assertRaises(ImportError, initializeModule, libc()) - - - def test_missingAdd(self): - """ - If the I{libc} object passed to L{initializeModule} has no - C{inotify_add_watch} attribute, L{ImportError} is raised. - """ - class libc: - def inotify_init(self): - pass - def inotify_rm_watch(self): - pass - self.assertRaises(ImportError, initializeModule, libc()) - - - def test_missingRemove(self): - """ - If the I{libc} object passed to L{initializeModule} has no - C{inotify_rm_watch} attribute, L{ImportError} is raised. - """ - class libc: - def inotify_init(self): - pass - def inotify_add_watch(self): - pass - self.assertRaises(ImportError, initializeModule, libc()) - - - def test_setTypes(self): - """ - If the I{libc} object passed to L{initializeModule} has all of the - necessary attributes, it sets the C{argtypes} and C{restype} attributes - of the three ctypes methods used from libc. - """ - class libc: - def inotify_init(self): - pass - inotify_init = staticmethod(inotify_init) - - def inotify_rm_watch(self): - pass - inotify_rm_watch = staticmethod(inotify_rm_watch) - - def inotify_add_watch(self): - pass - inotify_add_watch = staticmethod(inotify_add_watch) - - c = libc() - initializeModule(c) - self.assertEqual(c.inotify_init.argtypes, []) - self.assertEqual(c.inotify_init.restype, c_int) - - self.assertEqual(c.inotify_rm_watch.argtypes, [c_int, c_int]) - self.assertEqual(c.inotify_rm_watch.restype, c_int) - - self.assertEqual( - c.inotify_add_watch.argtypes, [c_int, c_char_p, c_uint32]) - self.assertEqual(c.inotify_add_watch.restype, c_int) - - - def test_failedInit(self): - """ - If C{inotify_init} returns a negative number, L{init} raises - L{INotifyError}. - """ - class libc: - def inotify_init(self): - return -1 - self.patch(_inotify, 'libc', libc()) - self.assertRaises(INotifyError, init) - - - def test_failedAddWatch(self): - """ - If C{inotify_add_watch} returns a negative number, L{add} - raises L{INotifyError}. - """ - class libc: - def inotify_add_watch(self, fd, path, mask): - return -1 - self.patch(_inotify, 'libc', libc()) - self.assertRaises(INotifyError, add, 3, '/foo', 0) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_release.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_release.py deleted file mode 100755 index a4f868c7..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_release.py +++ /dev/null @@ -1,2598 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for L{twisted.python.release} and L{twisted.python._release}. - -All of these tests are skipped on platforms other than Linux, as the release is -only ever performed on Linux. -""" - - -import warnings -import operator -import os, sys, signal -from StringIO import StringIO -import tarfile -from xml.dom import minidom as dom - -from datetime import date - -from twisted.trial.unittest import TestCase - -from twisted.python.compat import execfile, set -from twisted.python.procutils import which -from twisted.python import release -from twisted.python.filepath import FilePath -from twisted.python.versions import Version -from twisted.python._release import _changeVersionInFile, getNextVersion -from twisted.python._release import findTwistedProjects, replaceInFile -from twisted.python._release import replaceProjectVersion -from twisted.python._release import updateTwistedVersionInformation, Project -from twisted.python._release import generateVersionFileData -from twisted.python._release import changeAllProjectVersions -from twisted.python._release import VERSION_OFFSET, DocBuilder, ManBuilder -from twisted.python._release import NoDocumentsFound, filePathDelta -from twisted.python._release import CommandFailed, BookBuilder -from twisted.python._release import DistributionBuilder, APIBuilder -from twisted.python._release import BuildAPIDocsScript -from twisted.python._release import buildAllTarballs, runCommand -from twisted.python._release import UncleanWorkingDirectory, NotWorkingDirectory -from twisted.python._release import ChangeVersionsScript, BuildTarballsScript -from twisted.python._release import NewsBuilder - -if os.name != 'posix': - skip = "Release toolchain only supported on POSIX." -else: - skip = None - - -# Check a bunch of dependencies to skip tests if necessary. -try: - from twisted.lore.scripts import lore -except ImportError: - loreSkip = "Lore is not present." -else: - loreSkip = skip - - -try: - import pydoctor.driver - # it might not be installed, or it might use syntax not available in - # this version of Python. -except (ImportError, SyntaxError): - pydoctorSkip = "Pydoctor is not present." -else: - if getattr(pydoctor, "version_info", (0,)) < (0, 1): - pydoctorSkip = "Pydoctor is too old." - else: - pydoctorSkip = skip - - -if which("latex") and which("dvips") and which("ps2pdf13"): - latexSkip = skip -else: - latexSkip = "LaTeX is not available." - - -if which("svn") and which("svnadmin"): - svnSkip = skip -else: - svnSkip = "svn or svnadmin is not present." - - -def genVersion(*args, **kwargs): - """ - A convenience for generating _version.py data. - - @param args: Arguments to pass to L{Version}. - @param kwargs: Keyword arguments to pass to L{Version}. - """ - return generateVersionFileData(Version(*args, **kwargs)) - - - -class StructureAssertingMixin(object): - """ - A mixin for L{TestCase} subclasses which provides some methods for asserting - the structure and contents of directories and files on the filesystem. - """ - def createStructure(self, root, dirDict): - """ - Create a set of directories and files given a dict defining their - structure. - - @param root: The directory in which to create the structure. It must - already exist. - @type root: L{FilePath} - - @param dirDict: The dict defining the structure. Keys should be strings - naming files, values should be strings describing file contents OR - dicts describing subdirectories. All files are written in binary - mode. Any string values are assumed to describe text files and - will have their newlines replaced with the platform-native newline - convention. For example:: - - {"foofile": "foocontents", - "bardir": {"barfile": "bar\ncontents"}} - @type dirDict: C{dict} - """ - for x in dirDict: - child = root.child(x) - if isinstance(dirDict[x], dict): - child.createDirectory() - self.createStructure(child, dirDict[x]) - else: - child.setContent(dirDict[x].replace('\n', os.linesep)) - - def assertStructure(self, root, dirDict): - """ - Assert that a directory is equivalent to one described by a dict. - - @param root: The filesystem directory to compare. - @type root: L{FilePath} - @param dirDict: The dict that should describe the contents of the - directory. It should be the same structure as the C{dirDict} - parameter to L{createStructure}. - @type dirDict: C{dict} - """ - children = [x.basename() for x in root.children()] - for x in dirDict: - child = root.child(x) - if isinstance(dirDict[x], dict): - self.assertTrue(child.isdir(), "%s is not a dir!" - % (child.path,)) - self.assertStructure(child, dirDict[x]) - else: - a = child.getContent().replace(os.linesep, '\n') - self.assertEqual(a, dirDict[x], child.path) - children.remove(x) - if children: - self.fail("There were extra children in %s: %s" - % (root.path, children)) - - - def assertExtractedStructure(self, outputFile, dirDict): - """ - Assert that a tarfile content is equivalent to one described by a dict. - - @param outputFile: The tar file built by L{DistributionBuilder}. - @type outputFile: L{FilePath}. - @param dirDict: The dict that should describe the contents of the - directory. It should be the same structure as the C{dirDict} - parameter to L{createStructure}. - @type dirDict: C{dict} - """ - tarFile = tarfile.TarFile.open(outputFile.path, "r:bz2") - extracted = FilePath(self.mktemp()) - extracted.createDirectory() - for info in tarFile: - tarFile.extract(info, path=extracted.path) - self.assertStructure(extracted.children()[0], dirDict) - - - -class ChangeVersionTest(TestCase, StructureAssertingMixin): - """ - Twisted has the ability to change versions. - """ - - def makeFile(self, relativePath, content): - """ - Create a file with the given content relative to a temporary directory. - - @param relativePath: The basename of the file to create. - @param content: The content that the file will have. - @return: The filename. - """ - baseDirectory = FilePath(self.mktemp()) - directory, filename = os.path.split(relativePath) - directory = baseDirectory.preauthChild(directory) - directory.makedirs() - file = directory.child(filename) - directory.child(filename).setContent(content) - return file - - - def test_getNextVersion(self): - """ - When calculating the next version to release when a release is - happening in the same year as the last release, the minor version - number is incremented. - """ - now = date.today() - major = now.year - VERSION_OFFSET - version = Version("twisted", major, 9, 0) - self.assertEqual(getNextVersion(version, now=now), - Version("twisted", major, 10, 0)) - - - def test_getNextVersionAfterYearChange(self): - """ - When calculating the next version to release when a release is - happening in a later year, the minor version number is reset to 0. - """ - now = date.today() - major = now.year - VERSION_OFFSET - version = Version("twisted", major - 1, 9, 0) - self.assertEqual(getNextVersion(version, now=now), - Version("twisted", major, 0, 0)) - - - def test_changeVersionInFile(self): - """ - _changeVersionInFile replaces the old version information in a file - with the given new version information. - """ - # The version numbers are arbitrary, the name is only kind of - # arbitrary. - packageName = 'foo' - oldVersion = Version(packageName, 2, 5, 0) - file = self.makeFile('README', - "Hello and welcome to %s." % oldVersion.base()) - - newVersion = Version(packageName, 7, 6, 0) - _changeVersionInFile(oldVersion, newVersion, file.path) - - self.assertEqual(file.getContent(), - "Hello and welcome to %s." % newVersion.base()) - - - def test_changeAllProjectVersions(self): - """ - L{changeAllProjectVersions} changes all version numbers in _version.py - and README files for all projects as well as in the the top-level - README file. - """ - root = FilePath(self.mktemp()) - root.createDirectory() - structure = { - "README": "Hi this is 1.0.0.", - "twisted": { - "topfiles": { - "README": "Hi this is 1.0.0"}, - "_version.py": - genVersion("twisted", 1, 0, 0), - "web": { - "topfiles": { - "README": "Hi this is 1.0.0"}, - "_version.py": genVersion("twisted.web", 1, 0, 0) - }}} - self.createStructure(root, structure) - changeAllProjectVersions(root, Version("lol", 1, 0, 2)) - outStructure = { - "README": "Hi this is 1.0.2.", - "twisted": { - "topfiles": { - "README": "Hi this is 1.0.2"}, - "_version.py": - genVersion("twisted", 1, 0, 2), - "web": { - "topfiles": { - "README": "Hi this is 1.0.2"}, - "_version.py": genVersion("twisted.web", 1, 0, 2), - }}} - self.assertStructure(root, outStructure) - - - def test_changeAllProjectVersionsPreRelease(self): - """ - L{changeAllProjectVersions} changes all version numbers in _version.py - and README files for all projects as well as in the the top-level - README file. If the old version was a pre-release, it will change the - version in NEWS files as well. - """ - root = FilePath(self.mktemp()) - root.createDirectory() - coreNews = ("Twisted Core 1.0.0 (2009-12-25)\n" - "===============================\n" - "\n") - webNews = ("Twisted Web 1.0.0pre1 (2009-12-25)\n" - "==================================\n" - "\n") - structure = { - "README": "Hi this is 1.0.0.", - "NEWS": coreNews + webNews, - "twisted": { - "topfiles": { - "README": "Hi this is 1.0.0", - "NEWS": coreNews}, - "_version.py": - genVersion("twisted", 1, 0, 0), - "web": { - "topfiles": { - "README": "Hi this is 1.0.0pre1", - "NEWS": webNews}, - "_version.py": genVersion("twisted.web", 1, 0, 0, 1) - }}} - self.createStructure(root, structure) - changeAllProjectVersions(root, Version("lol", 1, 0, 2), '2010-01-01') - coreNews = ( - "Twisted Core 1.0.0 (2009-12-25)\n" - "===============================\n" - "\n") - webNews = ("Twisted Web 1.0.2 (2010-01-01)\n" - "==============================\n" - "\n") - outStructure = { - "README": "Hi this is 1.0.2.", - "NEWS": coreNews + webNews, - "twisted": { - "topfiles": { - "README": "Hi this is 1.0.2", - "NEWS": coreNews}, - "_version.py": - genVersion("twisted", 1, 0, 2), - "web": { - "topfiles": { - "README": "Hi this is 1.0.2", - "NEWS": webNews}, - "_version.py": genVersion("twisted.web", 1, 0, 2), - }}} - self.assertStructure(root, outStructure) - - - -class ProjectTest(TestCase): - """ - There is a first-class representation of a project. - """ - - def assertProjectsEqual(self, observedProjects, expectedProjects): - """ - Assert that two lists of L{Project}s are equal. - """ - self.assertEqual(len(observedProjects), len(expectedProjects)) - observedProjects = sorted(observedProjects, - key=operator.attrgetter('directory')) - expectedProjects = sorted(expectedProjects, - key=operator.attrgetter('directory')) - for observed, expected in zip(observedProjects, expectedProjects): - self.assertEqual(observed.directory, expected.directory) - - - def makeProject(self, version, baseDirectory=None): - """ - Make a Twisted-style project in the given base directory. - - @param baseDirectory: The directory to create files in - (as a L{FilePath). - @param version: The version information for the project. - @return: L{Project} pointing to the created project. - """ - if baseDirectory is None: - baseDirectory = FilePath(self.mktemp()) - baseDirectory.createDirectory() - segments = version.package.split('.') - directory = baseDirectory - for segment in segments: - directory = directory.child(segment) - if not directory.exists(): - directory.createDirectory() - directory.child('__init__.py').setContent('') - directory.child('topfiles').createDirectory() - directory.child('topfiles').child('README').setContent(version.base()) - replaceProjectVersion( - directory.child('_version.py').path, version) - return Project(directory) - - - def makeProjects(self, *versions): - """ - Create a series of projects underneath a temporary base directory. - - @return: A L{FilePath} for the base directory. - """ - baseDirectory = FilePath(self.mktemp()) - baseDirectory.createDirectory() - for version in versions: - self.makeProject(version, baseDirectory) - return baseDirectory - - - def test_getVersion(self): - """ - Project objects know their version. - """ - version = Version('foo', 2, 1, 0) - project = self.makeProject(version) - self.assertEqual(project.getVersion(), version) - - - def test_updateVersion(self): - """ - Project objects know how to update the version numbers in those - projects. - """ - project = self.makeProject(Version("bar", 2, 1, 0)) - newVersion = Version("bar", 3, 2, 9) - project.updateVersion(newVersion) - self.assertEqual(project.getVersion(), newVersion) - self.assertEqual( - project.directory.child("topfiles").child("README").getContent(), - "3.2.9") - - - def test_repr(self): - """ - The representation of a Project is Project(directory). - """ - foo = Project(FilePath('bar')) - self.assertEqual( - repr(foo), 'Project(%r)' % (foo.directory)) - - - def test_findTwistedStyleProjects(self): - """ - findTwistedStyleProjects finds all projects underneath a particular - directory. A 'project' is defined by the existence of a 'topfiles' - directory and is returned as a Project object. - """ - baseDirectory = self.makeProjects( - Version('foo', 2, 3, 0), Version('foo.bar', 0, 7, 4)) - projects = findTwistedProjects(baseDirectory) - self.assertProjectsEqual( - projects, - [Project(baseDirectory.child('foo')), - Project(baseDirectory.child('foo').child('bar'))]) - - - def test_updateTwistedVersionInformation(self): - """ - Update Twisted version information in the top-level project and all of - the subprojects. - """ - baseDirectory = FilePath(self.mktemp()) - baseDirectory.createDirectory() - now = date.today() - - projectName = 'foo' - oldVersion = Version(projectName, 2, 5, 0) - newVersion = getNextVersion(oldVersion, now=now) - - project = self.makeProject(oldVersion, baseDirectory) - - updateTwistedVersionInformation(baseDirectory, now=now) - - self.assertEqual(project.getVersion(), newVersion) - self.assertEqual( - project.directory.child('topfiles').child('README').getContent(), - newVersion.base()) - - - -class UtilityTest(TestCase): - """ - Tests for various utility functions for releasing. - """ - - def test_chdir(self): - """ - Test that the runChdirSafe is actually safe, i.e., it still - changes back to the original directory even if an error is - raised. - """ - cwd = os.getcwd() - def chAndBreak(): - os.mkdir('releaseCh') - os.chdir('releaseCh') - 1//0 - self.assertRaises(ZeroDivisionError, - release.runChdirSafe, chAndBreak) - self.assertEqual(cwd, os.getcwd()) - - - - def test_replaceInFile(self): - """ - L{replaceInFile} replaces data in a file based on a dict. A key from - the dict that is found in the file is replaced with the corresponding - value. - """ - in_ = 'foo\nhey hey $VER\nbar\n' - outf = open('release.replace', 'w') - outf.write(in_) - outf.close() - - expected = in_.replace('$VER', '2.0.0') - replaceInFile('release.replace', {'$VER': '2.0.0'}) - self.assertEqual(open('release.replace').read(), expected) - - - expected = expected.replace('2.0.0', '3.0.0') - replaceInFile('release.replace', {'2.0.0': '3.0.0'}) - self.assertEqual(open('release.replace').read(), expected) - - - -class VersionWritingTest(TestCase): - """ - Tests for L{replaceProjectVersion}. - """ - - def test_replaceProjectVersion(self): - """ - L{replaceProjectVersion} writes a Python file that defines a - C{version} variable that corresponds to the given name and version - number. - """ - replaceProjectVersion("test_project", - Version("twisted.test_project", 0, 82, 7)) - ns = {'__name___': 'twisted.test_project'} - execfile("test_project", ns) - self.assertEqual(ns["version"].base(), "0.82.7") - - - def test_replaceProjectVersionWithPrerelease(self): - """ - L{replaceProjectVersion} will write a Version instantiation that - includes a prerelease parameter if necessary. - """ - replaceProjectVersion("test_project", - Version("twisted.test_project", 0, 82, 7, - prerelease=8)) - ns = {'__name___': 'twisted.test_project'} - execfile("test_project", ns) - self.assertEqual(ns["version"].base(), "0.82.7pre8") - - - -class BuilderTestsMixin(object): - """ - A mixin class which provides various methods for creating sample Lore input - and output. - - @cvar template: The lore template that will be used to prepare sample - output. - @type template: C{str} - - @ivar docCounter: A counter which is incremented every time input is - generated and which is included in the documents. - @type docCounter: C{int} - """ - template = ''' - <html> - <head><title>Yo:</title></head> - <body> - <div class="body" /> - <a href="index.html">Index</a> - <span class="version">Version: </span> - </body> - </html> - ''' - - def setUp(self): - """ - Initialize the doc counter which ensures documents are unique. - """ - self.docCounter = 0 - - - def assertXMLEqual(self, first, second): - """ - Verify that two strings represent the same XML document. - """ - self.assertEqual( - dom.parseString(first).toxml(), - dom.parseString(second).toxml()) - - - def getArbitraryOutput(self, version, counter, prefix="", apiBaseURL="%s"): - """ - Get the correct HTML output for the arbitrary input returned by - L{getArbitraryLoreInput} for the given parameters. - - @param version: The version string to include in the output. - @type version: C{str} - @param counter: A counter to include in the output. - @type counter: C{int} - """ - document = """\ -<?xml version="1.0"?><html> - <head><title>Yo:Hi! Title: %(count)d</title></head> - <body> - <div class="content">Hi! %(count)d<div class="API"><a href="%(foobarLink)s" title="foobar">foobar</a></div></div> - <a href="%(prefix)sindex.html">Index</a> - <span class="version">Version: %(version)s</span> - </body> - </html>""" - # Try to normalize irrelevant whitespace. - return dom.parseString( - document % {"count": counter, "prefix": prefix, - "version": version, - "foobarLink": apiBaseURL % ("foobar",)}).toxml('utf-8') - - - def getArbitraryLoreInput(self, counter): - """ - Get an arbitrary, unique (for this test case) string of lore input. - - @param counter: A counter to include in the input. - @type counter: C{int} - """ - template = ( - '<html>' - '<head><title>Hi! Title: %(count)s</title></head>' - '<body>' - 'Hi! %(count)s' - '<div class="API">foobar</div>' - '</body>' - '</html>') - return template % {"count": counter} - - - def getArbitraryLoreInputAndOutput(self, version, prefix="", - apiBaseURL="%s"): - """ - Get an input document along with expected output for lore run on that - output document, assuming an appropriately-specified C{self.template}. - - @param version: A version string to include in the input and output. - @type version: C{str} - @param prefix: The prefix to include in the link to the index. - @type prefix: C{str} - - @return: A two-tuple of input and expected output. - @rtype: C{(str, str)}. - """ - self.docCounter += 1 - return (self.getArbitraryLoreInput(self.docCounter), - self.getArbitraryOutput(version, self.docCounter, - prefix=prefix, apiBaseURL=apiBaseURL)) - - - def getArbitraryManInput(self): - """ - Get an arbitrary man page content. - """ - return """.TH MANHOLE "1" "August 2001" "" "" -.SH NAME -manhole \- Connect to a Twisted Manhole service -.SH SYNOPSIS -.B manhole -.SH DESCRIPTION -manhole is a GTK interface to Twisted Manhole services. You can execute python -code as if at an interactive Python console inside a running Twisted process -with this.""" - - - def getArbitraryManLoreOutput(self): - """ - Get an arbitrary lore input document which represents man-to-lore - output based on the man page returned from L{getArbitraryManInput} - """ - return """\ -<?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><head> -<title>MANHOLE.1</title></head> -<body> - -<h1>MANHOLE.1</h1> - -<h2>NAME</h2> - -<p>manhole - Connect to a Twisted Manhole service -</p> - -<h2>SYNOPSIS</h2> - -<p><strong>manhole</strong> </p> - -<h2>DESCRIPTION</h2> - -<p>manhole is a GTK interface to Twisted Manhole services. You can execute python -code as if at an interactive Python console inside a running Twisted process -with this.</p> - -</body> -</html> -""" - - def getArbitraryManHTMLOutput(self, version, prefix=""): - """ - Get an arbitrary lore output document which represents the lore HTML - output based on the input document returned from - L{getArbitraryManLoreOutput}. - - @param version: A version string to include in the document. - @type version: C{str} - @param prefix: The prefix to include in the link to the index. - @type prefix: C{str} - """ - # Try to normalize the XML a little bit. - return dom.parseString("""\ -<?xml version="1.0" ?><html> - <head><title>Yo:MANHOLE.1</title></head> - <body> - <div class="content"> - -<span/> - -<h2>NAME<a name="auto0"/></h2> - -<p>manhole - Connect to a Twisted Manhole service -</p> - -<h2>SYNOPSIS<a name="auto1"/></h2> - -<p><strong>manhole</strong> </p> - -<h2>DESCRIPTION<a name="auto2"/></h2> - -<p>manhole is a GTK interface to Twisted Manhole services. You can execute python -code as if at an interactive Python console inside a running Twisted process -with this.</p> - -</div> - <a href="%(prefix)sindex.html">Index</a> - <span class="version">Version: %(version)s</span> - </body> - </html>""" % { - 'prefix': prefix, 'version': version}).toxml("utf-8") - - - -class DocBuilderTestCase(TestCase, BuilderTestsMixin): - """ - Tests for L{DocBuilder}. - - Note for future maintainers: The exact byte equality assertions throughout - this suite may need to be updated due to minor differences in lore. They - should not be taken to mean that Lore must maintain the same byte format - forever. Feel free to update the tests when Lore changes, but please be - careful. - """ - skip = loreSkip - - def setUp(self): - """ - Set up a few instance variables that will be useful. - - @ivar builder: A plain L{DocBuilder}. - @ivar docCounter: An integer to be used as a counter by the - C{getArbitrary...} methods. - @ivar howtoDir: A L{FilePath} representing a directory to be used for - containing Lore documents. - @ivar templateFile: A L{FilePath} representing a file with - C{self.template} as its content. - """ - BuilderTestsMixin.setUp(self) - self.builder = DocBuilder() - self.howtoDir = FilePath(self.mktemp()) - self.howtoDir.createDirectory() - self.templateFile = self.howtoDir.child("template.tpl") - self.templateFile.setContent(self.template) - - - def test_build(self): - """ - The L{DocBuilder} runs lore on all .xhtml files within a directory. - """ - version = "1.2.3" - input1, output1 = self.getArbitraryLoreInputAndOutput(version) - input2, output2 = self.getArbitraryLoreInputAndOutput(version) - - self.howtoDir.child("one.xhtml").setContent(input1) - self.howtoDir.child("two.xhtml").setContent(input2) - - self.builder.build(version, self.howtoDir, self.howtoDir, - self.templateFile) - out1 = self.howtoDir.child('one.html') - out2 = self.howtoDir.child('two.html') - self.assertXMLEqual(out1.getContent(), output1) - self.assertXMLEqual(out2.getContent(), output2) - - - def test_noDocumentsFound(self): - """ - The C{build} method raises L{NoDocumentsFound} if there are no - .xhtml files in the given directory. - """ - self.assertRaises( - NoDocumentsFound, - self.builder.build, "1.2.3", self.howtoDir, self.howtoDir, - self.templateFile) - - - def test_parentDocumentLinking(self): - """ - The L{DocBuilder} generates correct links from documents to - template-generated links like stylesheets and index backreferences. - """ - input = self.getArbitraryLoreInput(0) - tutoDir = self.howtoDir.child("tutorial") - tutoDir.createDirectory() - tutoDir.child("child.xhtml").setContent(input) - self.builder.build("1.2.3", self.howtoDir, tutoDir, self.templateFile) - outFile = tutoDir.child('child.html') - self.assertIn('<a href="../index.html">Index</a>', - outFile.getContent()) - - - def test_siblingDirectoryDocumentLinking(self): - """ - It is necessary to generate documentation in a directory foo/bar where - stylesheet and indexes are located in foo/baz. Such resources should be - appropriately linked to. - """ - input = self.getArbitraryLoreInput(0) - resourceDir = self.howtoDir.child("resources") - docDir = self.howtoDir.child("docs") - docDir.createDirectory() - docDir.child("child.xhtml").setContent(input) - self.builder.build("1.2.3", resourceDir, docDir, self.templateFile) - outFile = docDir.child('child.html') - self.assertIn('<a href="../resources/index.html">Index</a>', - outFile.getContent()) - - - def test_apiLinking(self): - """ - The L{DocBuilder} generates correct links from documents to API - documentation. - """ - version = "1.2.3" - input, output = self.getArbitraryLoreInputAndOutput(version) - self.howtoDir.child("one.xhtml").setContent(input) - - self.builder.build(version, self.howtoDir, self.howtoDir, - self.templateFile, "scheme:apilinks/%s.ext") - out = self.howtoDir.child('one.html') - self.assertIn( - '<a href="scheme:apilinks/foobar.ext" title="foobar">foobar</a>', - out.getContent()) - - - def test_deleteInput(self): - """ - L{DocBuilder.build} can be instructed to delete the input files after - generating the output based on them. - """ - input1 = self.getArbitraryLoreInput(0) - self.howtoDir.child("one.xhtml").setContent(input1) - self.builder.build("whatever", self.howtoDir, self.howtoDir, - self.templateFile, deleteInput=True) - self.assertTrue(self.howtoDir.child('one.html').exists()) - self.assertFalse(self.howtoDir.child('one.xhtml').exists()) - - - def test_doNotDeleteInput(self): - """ - Input will not be deleted by default. - """ - input1 = self.getArbitraryLoreInput(0) - self.howtoDir.child("one.xhtml").setContent(input1) - self.builder.build("whatever", self.howtoDir, self.howtoDir, - self.templateFile) - self.assertTrue(self.howtoDir.child('one.html').exists()) - self.assertTrue(self.howtoDir.child('one.xhtml').exists()) - - - def test_getLinkrelToSameDirectory(self): - """ - If the doc and resource directories are the same, the linkrel should be - an empty string. - """ - linkrel = self.builder.getLinkrel(FilePath("/foo/bar"), - FilePath("/foo/bar")) - self.assertEqual(linkrel, "") - - - def test_getLinkrelToParentDirectory(self): - """ - If the doc directory is a child of the resource directory, the linkrel - should make use of '..'. - """ - linkrel = self.builder.getLinkrel(FilePath("/foo"), - FilePath("/foo/bar")) - self.assertEqual(linkrel, "../") - - - def test_getLinkrelToSibling(self): - """ - If the doc directory is a sibling of the resource directory, the - linkrel should make use of '..' and a named segment. - """ - linkrel = self.builder.getLinkrel(FilePath("/foo/howto"), - FilePath("/foo/examples")) - self.assertEqual(linkrel, "../howto/") - - - def test_getLinkrelToUncle(self): - """ - If the doc directory is a sibling of the parent of the resource - directory, the linkrel should make use of multiple '..'s and a named - segment. - """ - linkrel = self.builder.getLinkrel(FilePath("/foo/howto"), - FilePath("/foo/examples/quotes")) - self.assertEqual(linkrel, "../../howto/") - - - -class APIBuilderTestCase(TestCase): - """ - Tests for L{APIBuilder}. - """ - skip = pydoctorSkip - - def test_build(self): - """ - L{APIBuilder.build} writes an index file which includes the name of the - project specified. - """ - stdout = StringIO() - self.patch(sys, 'stdout', stdout) - - projectName = "Foobar" - packageName = "quux" - projectURL = "scheme:project" - sourceURL = "scheme:source" - docstring = "text in docstring" - privateDocstring = "should also appear in output" - - inputPath = FilePath(self.mktemp()).child(packageName) - inputPath.makedirs() - inputPath.child("__init__.py").setContent( - "def foo():\n" - " '%s'\n" - "def _bar():\n" - " '%s'" % (docstring, privateDocstring)) - - outputPath = FilePath(self.mktemp()) - outputPath.makedirs() - - builder = APIBuilder() - builder.build(projectName, projectURL, sourceURL, inputPath, outputPath) - - indexPath = outputPath.child("index.html") - self.assertTrue( - indexPath.exists(), - "API index %r did not exist." % (outputPath.path,)) - self.assertIn( - '<a href="%s">%s</a>' % (projectURL, projectName), - indexPath.getContent(), - "Project name/location not in file contents.") - - quuxPath = outputPath.child("quux.html") - self.assertTrue( - quuxPath.exists(), - "Package documentation file %r did not exist." % (quuxPath.path,)) - self.assertIn( - docstring, quuxPath.getContent(), - "Docstring not in package documentation file.") - self.assertIn( - '<a href="%s/%s">View Source</a>' % (sourceURL, packageName), - quuxPath.getContent()) - self.assertIn( - '<a href="%s/%s/__init__.py#L1" class="functionSourceLink">' % ( - sourceURL, packageName), - quuxPath.getContent()) - self.assertIn(privateDocstring, quuxPath.getContent()) - - # There should also be a page for the foo function in quux. - self.assertTrue(quuxPath.sibling('quux.foo.html').exists()) - - self.assertEqual(stdout.getvalue(), '') - - - def test_buildWithPolicy(self): - """ - L{BuildAPIDocsScript.buildAPIDocs} builds the API docs with values - appropriate for the Twisted project. - """ - stdout = StringIO() - self.patch(sys, 'stdout', stdout) - docstring = "text in docstring" - - projectRoot = FilePath(self.mktemp()) - packagePath = projectRoot.child("twisted") - packagePath.makedirs() - packagePath.child("__init__.py").setContent( - "def foo():\n" - " '%s'\n" % (docstring,)) - packagePath.child("_version.py").setContent( - genVersion("twisted", 1, 0, 0)) - outputPath = FilePath(self.mktemp()) - - script = BuildAPIDocsScript() - script.buildAPIDocs(projectRoot, outputPath) - - indexPath = outputPath.child("index.html") - self.assertTrue( - indexPath.exists(), - "API index %r did not exist." % (outputPath.path,)) - self.assertIn( - '<a href="http://twistedmatrix.com/">Twisted</a>', - indexPath.getContent(), - "Project name/location not in file contents.") - - twistedPath = outputPath.child("twisted.html") - self.assertTrue( - twistedPath.exists(), - "Package documentation file %r did not exist." - % (twistedPath.path,)) - self.assertIn( - docstring, twistedPath.getContent(), - "Docstring not in package documentation file.") - #Here we check that it figured out the correct version based on the - #source code. - self.assertIn( - '<a href="http://twistedmatrix.com/trac/browser/tags/releases/' - 'twisted-1.0.0/twisted">View Source</a>', - twistedPath.getContent()) - - self.assertEqual(stdout.getvalue(), '') - - - def test_apiBuilderScriptMainRequiresTwoArguments(self): - """ - SystemExit is raised when the incorrect number of command line - arguments are passed to the API building script. - """ - script = BuildAPIDocsScript() - self.assertRaises(SystemExit, script.main, []) - self.assertRaises(SystemExit, script.main, ["foo"]) - self.assertRaises(SystemExit, script.main, ["foo", "bar", "baz"]) - - - def test_apiBuilderScriptMain(self): - """ - The API building script invokes the same code that - L{test_buildWithPolicy} tests. - """ - script = BuildAPIDocsScript() - calls = [] - script.buildAPIDocs = lambda a, b: calls.append((a, b)) - script.main(["hello", "there"]) - self.assertEqual(calls, [(FilePath("hello"), FilePath("there"))]) - - - -class ManBuilderTestCase(TestCase, BuilderTestsMixin): - """ - Tests for L{ManBuilder}. - """ - skip = loreSkip - - def setUp(self): - """ - Set up a few instance variables that will be useful. - - @ivar builder: A plain L{ManBuilder}. - @ivar manDir: A L{FilePath} representing a directory to be used for - containing man pages. - """ - BuilderTestsMixin.setUp(self) - self.builder = ManBuilder() - self.manDir = FilePath(self.mktemp()) - self.manDir.createDirectory() - - - def test_noDocumentsFound(self): - """ - L{ManBuilder.build} raises L{NoDocumentsFound} if there are no - .1 files in the given directory. - """ - self.assertRaises(NoDocumentsFound, self.builder.build, self.manDir) - - - def test_build(self): - """ - Check that L{ManBuilder.build} find the man page in the directory, and - successfully produce a Lore content. - """ - manContent = self.getArbitraryManInput() - self.manDir.child('test1.1').setContent(manContent) - self.builder.build(self.manDir) - output = self.manDir.child('test1-man.xhtml').getContent() - expected = self.getArbitraryManLoreOutput() - # No-op on *nix, fix for windows - expected = expected.replace('\n', os.linesep) - self.assertEqual(output, expected) - - - def test_toHTML(self): - """ - Check that the content output by C{build} is compatible as input of - L{DocBuilder.build}. - """ - manContent = self.getArbitraryManInput() - self.manDir.child('test1.1').setContent(manContent) - self.builder.build(self.manDir) - - templateFile = self.manDir.child("template.tpl") - templateFile.setContent(DocBuilderTestCase.template) - docBuilder = DocBuilder() - docBuilder.build("1.2.3", self.manDir, self.manDir, - templateFile) - output = self.manDir.child('test1-man.html').getContent() - - self.assertXMLEqual( - output, - """\ -<?xml version="1.0" ?><html> - <head><title>Yo:MANHOLE.1</title></head> - <body> - <div class="content"> - -<span/> - -<h2>NAME<a name="auto0"/></h2> - -<p>manhole - Connect to a Twisted Manhole service -</p> - -<h2>SYNOPSIS<a name="auto1"/></h2> - -<p><strong>manhole</strong> </p> - -<h2>DESCRIPTION<a name="auto2"/></h2> - -<p>manhole is a GTK interface to Twisted Manhole services. You can execute python -code as if at an interactive Python console inside a running Twisted process -with this.</p> - -</div> - <a href="index.html">Index</a> - <span class="version">Version: 1.2.3</span> - </body> - </html>""") - - - -class BookBuilderTests(TestCase, BuilderTestsMixin): - """ - Tests for L{BookBuilder}. - """ - skip = latexSkip or loreSkip - - def setUp(self): - """ - Make a directory into which to place temporary files. - """ - self.docCounter = 0 - self.howtoDir = FilePath(self.mktemp()) - self.howtoDir.makedirs() - self.oldHandler = signal.signal(signal.SIGCHLD, signal.SIG_DFL) - - - def tearDown(self): - signal.signal(signal.SIGCHLD, self.oldHandler) - - - def getArbitraryOutput(self, version, counter, prefix="", apiBaseURL=None): - """ - Create and return a C{str} containing the LaTeX document which is - expected as the output for processing the result of the document - returned by C{self.getArbitraryLoreInput(counter)}. - """ - path = self.howtoDir.child("%d.xhtml" % (counter,)).path - return ( - r'\section{Hi! Title: %(count)s\label{%(path)s}}' - '\n' - r'Hi! %(count)sfoobar') % {'count': counter, 'path': path} - - - def test_runSuccess(self): - """ - L{BookBuilder.run} executes the command it is passed and returns a - string giving the stdout and stderr of the command if it completes - successfully. - """ - builder = BookBuilder() - self.assertEqual( - builder.run([ - sys.executable, '-c', - 'import sys; ' - 'sys.stdout.write("hi\\n"); ' - 'sys.stdout.flush(); ' - 'sys.stderr.write("bye\\n"); ' - 'sys.stderr.flush()']), - "hi\nbye\n") - - - def test_runFailed(self): - """ - L{BookBuilder.run} executes the command it is passed and raises - L{CommandFailed} if it completes unsuccessfully. - """ - builder = BookBuilder() - exc = self.assertRaises( - CommandFailed, builder.run, - [sys.executable, '-c', 'print "hi"; raise SystemExit(1)']) - self.assertEqual(exc.exitStatus, 1) - self.assertEqual(exc.exitSignal, None) - self.assertEqual(exc.output, "hi\n") - - - def test_runSignaled(self): - """ - L{BookBuilder.run} executes the command it is passed and raises - L{CommandFailed} if it exits due to a signal. - """ - builder = BookBuilder() - exc = self.assertRaises( - CommandFailed, builder.run, - [sys.executable, '-c', - 'import sys; print "hi"; sys.stdout.flush(); ' - 'import os; os.kill(os.getpid(), 9)']) - self.assertEqual(exc.exitSignal, 9) - self.assertEqual(exc.exitStatus, None) - self.assertEqual(exc.output, "hi\n") - - - def test_buildTeX(self): - """ - L{BookBuilder.buildTeX} writes intermediate TeX files for all lore - input files in a directory. - """ - version = "3.2.1" - input1, output1 = self.getArbitraryLoreInputAndOutput(version) - input2, output2 = self.getArbitraryLoreInputAndOutput(version) - - # Filenames are chosen by getArbitraryOutput to match the counter used - # by getArbitraryLoreInputAndOutput. - self.howtoDir.child("1.xhtml").setContent(input1) - self.howtoDir.child("2.xhtml").setContent(input2) - - builder = BookBuilder() - builder.buildTeX(self.howtoDir) - self.assertEqual(self.howtoDir.child("1.tex").getContent(), output1) - self.assertEqual(self.howtoDir.child("2.tex").getContent(), output2) - - - def test_buildTeXRejectsInvalidDirectory(self): - """ - L{BookBuilder.buildTeX} raises L{ValueError} if passed a directory - which does not exist. - """ - builder = BookBuilder() - self.assertRaises( - ValueError, builder.buildTeX, self.howtoDir.temporarySibling()) - - - def test_buildTeXOnlyBuildsXHTML(self): - """ - L{BookBuilder.buildTeX} ignores files which which don't end with - ".xhtml". - """ - # Hopefully ">" is always a parse error from microdom! - self.howtoDir.child("not-input.dat").setContent(">") - self.test_buildTeX() - - - def test_stdout(self): - """ - L{BookBuilder.buildTeX} does not write to stdout. - """ - stdout = StringIO() - self.patch(sys, 'stdout', stdout) - - # Suppress warnings so that if there are any old-style plugins that - # lore queries for don't confuse the assertion below. See #3070. - self.patch(warnings, 'warn', lambda *a, **kw: None) - self.test_buildTeX() - self.assertEqual(stdout.getvalue(), '') - - - def test_buildPDFRejectsInvalidBookFilename(self): - """ - L{BookBuilder.buildPDF} raises L{ValueError} if the book filename does - not end with ".tex". - """ - builder = BookBuilder() - self.assertRaises( - ValueError, - builder.buildPDF, - FilePath(self.mktemp()).child("foo"), - None, - None) - - - def _setupTeXFiles(self): - sections = range(3) - self._setupTeXSections(sections) - return self._setupTeXBook(sections) - - - def _setupTeXSections(self, sections): - for texSectionNumber in sections: - texPath = self.howtoDir.child("%d.tex" % (texSectionNumber,)) - texPath.setContent(self.getArbitraryOutput( - "1.2.3", texSectionNumber)) - - - def _setupTeXBook(self, sections): - bookTeX = self.howtoDir.child("book.tex") - bookTeX.setContent( - r"\documentclass{book}" "\n" - r"\begin{document}" "\n" + - "\n".join([r"\input{%d.tex}" % (n,) for n in sections]) + - r"\end{document}" "\n") - return bookTeX - - - def test_buildPDF(self): - """ - L{BookBuilder.buildPDF} creates a PDF given an index tex file and a - directory containing .tex files. - """ - bookPath = self._setupTeXFiles() - outputPath = FilePath(self.mktemp()) - - builder = BookBuilder() - builder.buildPDF(bookPath, self.howtoDir, outputPath) - - self.assertTrue(outputPath.exists()) - - - def test_buildPDFLongPath(self): - """ - L{BookBuilder.buildPDF} succeeds even if the paths it is operating on - are very long. - - C{ps2pdf13} seems to have problems when path names are long. This test - verifies that even if inputs have long paths, generation still - succeeds. - """ - # Make it long. - self.howtoDir = self.howtoDir.child("x" * 128).child("x" * 128).child("x" * 128) - self.howtoDir.makedirs() - - # This will use the above long path. - bookPath = self._setupTeXFiles() - outputPath = FilePath(self.mktemp()) - - builder = BookBuilder() - builder.buildPDF(bookPath, self.howtoDir, outputPath) - - self.assertTrue(outputPath.exists()) - - - def test_buildPDFRunsLaTeXThreeTimes(self): - """ - L{BookBuilder.buildPDF} runs C{latex} three times. - """ - class InspectableBookBuilder(BookBuilder): - def __init__(self): - BookBuilder.__init__(self) - self.commands = [] - - def run(self, command): - """ - Record the command and then execute it. - """ - self.commands.append(command) - return BookBuilder.run(self, command) - - bookPath = self._setupTeXFiles() - outputPath = FilePath(self.mktemp()) - - builder = InspectableBookBuilder() - builder.buildPDF(bookPath, self.howtoDir, outputPath) - - # These string comparisons are very fragile. It would be better to - # have a test which asserted the correctness of the contents of the - # output files. I don't know how one could do that, though. -exarkun - latex1, latex2, latex3, dvips, ps2pdf13 = builder.commands - self.assertEqual(latex1, latex2) - self.assertEqual(latex2, latex3) - self.assertEqual( - latex1[:1], ["latex"], - "LaTeX command %r does not seem right." % (latex1,)) - self.assertEqual( - latex1[-1:], [bookPath.path], - "LaTeX command %r does not end with the book path (%r)." % ( - latex1, bookPath.path)) - - self.assertEqual( - dvips[:1], ["dvips"], - "dvips command %r does not seem right." % (dvips,)) - self.assertEqual( - ps2pdf13[:1], ["ps2pdf13"], - "ps2pdf13 command %r does not seem right." % (ps2pdf13,)) - - - def test_noSideEffects(self): - """ - The working directory is the same before and after a call to - L{BookBuilder.buildPDF}. Also the contents of the directory containing - the input book are the same before and after the call. - """ - startDir = os.getcwd() - bookTeX = self._setupTeXFiles() - startTeXSiblings = bookTeX.parent().children() - startHowtoChildren = self.howtoDir.children() - - builder = BookBuilder() - builder.buildPDF(bookTeX, self.howtoDir, FilePath(self.mktemp())) - - self.assertEqual(startDir, os.getcwd()) - self.assertEqual(startTeXSiblings, bookTeX.parent().children()) - self.assertEqual(startHowtoChildren, self.howtoDir.children()) - - - def test_failedCommandProvidesOutput(self): - """ - If a subprocess fails, L{BookBuilder.buildPDF} raises L{CommandFailed} - with the subprocess's output and leaves the temporary directory as a - sibling of the book path. - """ - bookTeX = FilePath(self.mktemp() + ".tex") - builder = BookBuilder() - inputState = bookTeX.parent().children() - exc = self.assertRaises( - CommandFailed, - builder.buildPDF, - bookTeX, self.howtoDir, FilePath(self.mktemp())) - self.assertTrue(exc.output) - newOutputState = set(bookTeX.parent().children()) - set(inputState) - self.assertEqual(len(newOutputState), 1) - workPath = newOutputState.pop() - self.assertTrue( - workPath.isdir(), - "Expected work path %r was not a directory." % (workPath.path,)) - - - def test_build(self): - """ - L{BookBuilder.build} generates a pdf book file from some lore input - files. - """ - sections = range(1, 4) - for sectionNumber in sections: - self.howtoDir.child("%d.xhtml" % (sectionNumber,)).setContent( - self.getArbitraryLoreInput(sectionNumber)) - bookTeX = self._setupTeXBook(sections) - bookPDF = FilePath(self.mktemp()) - - builder = BookBuilder() - builder.build(self.howtoDir, [self.howtoDir], bookTeX, bookPDF) - - self.assertTrue(bookPDF.exists()) - - - def test_buildRemovesTemporaryLaTeXFiles(self): - """ - L{BookBuilder.build} removes the intermediate LaTeX files it creates. - """ - sections = range(1, 4) - for sectionNumber in sections: - self.howtoDir.child("%d.xhtml" % (sectionNumber,)).setContent( - self.getArbitraryLoreInput(sectionNumber)) - bookTeX = self._setupTeXBook(sections) - bookPDF = FilePath(self.mktemp()) - - builder = BookBuilder() - builder.build(self.howtoDir, [self.howtoDir], bookTeX, bookPDF) - - self.assertEqual( - set(self.howtoDir.listdir()), - set([bookTeX.basename()] + ["%d.xhtml" % (n,) for n in sections])) - - - -class FilePathDeltaTest(TestCase): - """ - Tests for L{filePathDelta}. - """ - - def test_filePathDeltaSubdir(self): - """ - L{filePathDelta} can create a simple relative path to a child path. - """ - self.assertEqual(filePathDelta(FilePath("/foo/bar"), - FilePath("/foo/bar/baz")), - ["baz"]) - - - def test_filePathDeltaSiblingDir(self): - """ - L{filePathDelta} can traverse upwards to create relative paths to - siblings. - """ - self.assertEqual(filePathDelta(FilePath("/foo/bar"), - FilePath("/foo/baz")), - ["..", "baz"]) - - - def test_filePathNoCommonElements(self): - """ - L{filePathDelta} can create relative paths to totally unrelated paths - for maximum portability. - """ - self.assertEqual(filePathDelta(FilePath("/foo/bar"), - FilePath("/baz/quux")), - ["..", "..", "baz", "quux"]) - - - def test_filePathDeltaSimilarEndElements(self): - """ - L{filePathDelta} doesn't take into account final elements when - comparing 2 paths, but stops at the first difference. - """ - self.assertEqual(filePathDelta(FilePath("/foo/bar/bar/spam"), - FilePath("/foo/bar/baz/spam")), - ["..", "..", "baz", "spam"]) - - - -class NewsBuilderTests(TestCase, StructureAssertingMixin): - """ - Tests for L{NewsBuilder}. - """ - def setUp(self): - """ - Create a fake project and stuff some basic structure and content into - it. - """ - self.builder = NewsBuilder() - self.project = FilePath(self.mktemp()) - self.project.createDirectory() - self.existingText = 'Here is stuff which was present previously.\n' - self.createStructure(self.project, { - 'NEWS': self.existingText, - '5.feature': 'We now support the web.\n', - '12.feature': 'The widget is more robust.\n', - '15.feature': ( - 'A very long feature which takes many words to ' - 'describe with any accuracy was introduced so that ' - 'the line wrapping behavior of the news generating ' - 'code could be verified.\n'), - '16.feature': ( - 'A simpler feature\ndescribed on multiple lines\n' - 'was added.\n'), - '23.bugfix': 'Broken stuff was fixed.\n', - '25.removal': 'Stupid stuff was deprecated.\n', - '30.misc': '', - '35.misc': '', - '40.doc': 'foo.bar.Baz.quux', - '41.doc': 'writing Foo servers'}) - - - def test_today(self): - """ - L{NewsBuilder._today} returns today's date in YYYY-MM-DD form. - """ - self.assertEqual( - self.builder._today(), date.today().strftime('%Y-%m-%d')) - - - def test_findFeatures(self): - """ - When called with L{NewsBuilder._FEATURE}, L{NewsBuilder._findChanges} - returns a list of bugfix ticket numbers and descriptions as a list of - two-tuples. - """ - features = self.builder._findChanges( - self.project, self.builder._FEATURE) - self.assertEqual( - features, - [(5, "We now support the web."), - (12, "The widget is more robust."), - (15, - "A very long feature which takes many words to describe with " - "any accuracy was introduced so that the line wrapping behavior " - "of the news generating code could be verified."), - (16, "A simpler feature described on multiple lines was added.")]) - - - def test_findBugfixes(self): - """ - When called with L{NewsBuilder._BUGFIX}, L{NewsBuilder._findChanges} - returns a list of bugfix ticket numbers and descriptions as a list of - two-tuples. - """ - bugfixes = self.builder._findChanges( - self.project, self.builder._BUGFIX) - self.assertEqual( - bugfixes, - [(23, 'Broken stuff was fixed.')]) - - - def test_findRemovals(self): - """ - When called with L{NewsBuilder._REMOVAL}, L{NewsBuilder._findChanges} - returns a list of removal/deprecation ticket numbers and descriptions - as a list of two-tuples. - """ - removals = self.builder._findChanges( - self.project, self.builder._REMOVAL) - self.assertEqual( - removals, - [(25, 'Stupid stuff was deprecated.')]) - - - def test_findDocumentation(self): - """ - When called with L{NewsBuilder._DOC}, L{NewsBuilder._findChanges} - returns a list of documentation ticket numbers and descriptions as a - list of two-tuples. - """ - doc = self.builder._findChanges( - self.project, self.builder._DOC) - self.assertEqual( - doc, - [(40, 'foo.bar.Baz.quux'), - (41, 'writing Foo servers')]) - - - def test_findMiscellaneous(self): - """ - When called with L{NewsBuilder._MISC}, L{NewsBuilder._findChanges} - returns a list of removal/deprecation ticket numbers and descriptions - as a list of two-tuples. - """ - misc = self.builder._findChanges( - self.project, self.builder._MISC) - self.assertEqual( - misc, - [(30, ''), - (35, '')]) - - - def test_writeHeader(self): - """ - L{NewsBuilder._writeHeader} accepts a file-like object opened for - writing and a header string and writes out a news file header to it. - """ - output = StringIO() - self.builder._writeHeader(output, "Super Awesometastic 32.16") - self.assertEqual( - output.getvalue(), - "Super Awesometastic 32.16\n" - "=========================\n" - "\n") - - - def test_writeSection(self): - """ - L{NewsBuilder._writeSection} accepts a file-like object opened for - writing, a section name, and a list of ticket information (as returned - by L{NewsBuilder._findChanges}) and writes out a section header and all - of the given ticket information. - """ - output = StringIO() - self.builder._writeSection( - output, "Features", - [(3, "Great stuff."), - (17, "Very long line which goes on and on and on, seemingly " - "without end until suddenly without warning it does end.")]) - self.assertEqual( - output.getvalue(), - "Features\n" - "--------\n" - " - Great stuff. (#3)\n" - " - Very long line which goes on and on and on, seemingly without end\n" - " until suddenly without warning it does end. (#17)\n" - "\n") - - - def test_writeMisc(self): - """ - L{NewsBuilder._writeMisc} accepts a file-like object opened for - writing, a section name, and a list of ticket information (as returned - by L{NewsBuilder._findChanges} and writes out a section header and all - of the ticket numbers, but excludes any descriptions. - """ - output = StringIO() - self.builder._writeMisc( - output, "Other", - [(x, "") for x in range(2, 50, 3)]) - self.assertEqual( - output.getvalue(), - "Other\n" - "-----\n" - " - #2, #5, #8, #11, #14, #17, #20, #23, #26, #29, #32, #35, #38, #41,\n" - " #44, #47\n" - "\n") - - - def test_build(self): - """ - L{NewsBuilder.build} updates a NEWS file with new features based on the - I{<ticket>.feature} files found in the directory specified. - """ - self.builder.build( - self.project, self.project.child('NEWS'), - "Super Awesometastic 32.16") - - results = self.project.child('NEWS').getContent() - self.assertEqual( - results, - 'Super Awesometastic 32.16\n' - '=========================\n' - '\n' - 'Features\n' - '--------\n' - ' - We now support the web. (#5)\n' - ' - The widget is more robust. (#12)\n' - ' - A very long feature which takes many words to describe with any\n' - ' accuracy was introduced so that the line wrapping behavior of the\n' - ' news generating code could be verified. (#15)\n' - ' - A simpler feature described on multiple lines was added. (#16)\n' - '\n' - 'Bugfixes\n' - '--------\n' - ' - Broken stuff was fixed. (#23)\n' - '\n' - 'Improved Documentation\n' - '----------------------\n' - ' - foo.bar.Baz.quux (#40)\n' - ' - writing Foo servers (#41)\n' - '\n' - 'Deprecations and Removals\n' - '-------------------------\n' - ' - Stupid stuff was deprecated. (#25)\n' - '\n' - 'Other\n' - '-----\n' - ' - #30, #35\n' - '\n\n' + self.existingText) - - - def test_emptyProjectCalledOut(self): - """ - If no changes exist for a project, I{NEWS} gains a new section for - that project that includes some helpful text about how there were no - interesting changes. - """ - project = FilePath(self.mktemp()).child("twisted") - project.makedirs() - self.createStructure(project, { - 'NEWS': self.existingText }) - - self.builder.build( - project, project.child('NEWS'), - "Super Awesometastic 32.16") - results = project.child('NEWS').getContent() - self.assertEqual( - results, - 'Super Awesometastic 32.16\n' - '=========================\n' - '\n' + - self.builder._NO_CHANGES + - '\n\n' + self.existingText) - - - def test_preserveTicketHint(self): - """ - If a I{NEWS} file begins with the two magic lines which point readers - at the issue tracker, those lines are kept at the top of the new file. - """ - news = self.project.child('NEWS') - news.setContent( - 'Ticket numbers in this file can be looked up by visiting\n' - 'http://twistedmatrix.com/trac/ticket/<number>\n' - '\n' - 'Blah blah other stuff.\n') - - self.builder.build(self.project, news, "Super Awesometastic 32.16") - - self.assertEqual( - news.getContent(), - 'Ticket numbers in this file can be looked up by visiting\n' - 'http://twistedmatrix.com/trac/ticket/<number>\n' - '\n' - 'Super Awesometastic 32.16\n' - '=========================\n' - '\n' - 'Features\n' - '--------\n' - ' - We now support the web. (#5)\n' - ' - The widget is more robust. (#12)\n' - ' - A very long feature which takes many words to describe with any\n' - ' accuracy was introduced so that the line wrapping behavior of the\n' - ' news generating code could be verified. (#15)\n' - ' - A simpler feature described on multiple lines was added. (#16)\n' - '\n' - 'Bugfixes\n' - '--------\n' - ' - Broken stuff was fixed. (#23)\n' - '\n' - 'Improved Documentation\n' - '----------------------\n' - ' - foo.bar.Baz.quux (#40)\n' - ' - writing Foo servers (#41)\n' - '\n' - 'Deprecations and Removals\n' - '-------------------------\n' - ' - Stupid stuff was deprecated. (#25)\n' - '\n' - 'Other\n' - '-----\n' - ' - #30, #35\n' - '\n\n' - 'Blah blah other stuff.\n') - - - def test_emptySectionsOmitted(self): - """ - If there are no changes of a particular type (feature, bugfix, etc), no - section for that type is written by L{NewsBuilder.build}. - """ - for ticket in self.project.children(): - if ticket.splitext()[1] in ('.feature', '.misc', '.doc'): - ticket.remove() - - self.builder.build( - self.project, self.project.child('NEWS'), - 'Some Thing 1.2') - - self.assertEqual( - self.project.child('NEWS').getContent(), - 'Some Thing 1.2\n' - '==============\n' - '\n' - 'Bugfixes\n' - '--------\n' - ' - Broken stuff was fixed. (#23)\n' - '\n' - 'Deprecations and Removals\n' - '-------------------------\n' - ' - Stupid stuff was deprecated. (#25)\n' - '\n\n' - 'Here is stuff which was present previously.\n') - - - def test_duplicatesMerged(self): - """ - If two change files have the same contents, they are merged in the - generated news entry. - """ - def feature(s): - return self.project.child(s + '.feature') - feature('5').copyTo(feature('15')) - feature('5').copyTo(feature('16')) - - self.builder.build( - self.project, self.project.child('NEWS'), - 'Project Name 5.0') - - self.assertEqual( - self.project.child('NEWS').getContent(), - 'Project Name 5.0\n' - '================\n' - '\n' - 'Features\n' - '--------\n' - ' - We now support the web. (#5, #15, #16)\n' - ' - The widget is more robust. (#12)\n' - '\n' - 'Bugfixes\n' - '--------\n' - ' - Broken stuff was fixed. (#23)\n' - '\n' - 'Improved Documentation\n' - '----------------------\n' - ' - foo.bar.Baz.quux (#40)\n' - ' - writing Foo servers (#41)\n' - '\n' - 'Deprecations and Removals\n' - '-------------------------\n' - ' - Stupid stuff was deprecated. (#25)\n' - '\n' - 'Other\n' - '-----\n' - ' - #30, #35\n' - '\n\n' - 'Here is stuff which was present previously.\n') - - - def createFakeTwistedProject(self): - """ - Create a fake-looking Twisted project to build from. - """ - project = FilePath(self.mktemp()).child("twisted") - project.makedirs() - self.createStructure(project, { - 'NEWS': 'Old boring stuff from the past.\n', - '_version.py': genVersion("twisted", 1, 2, 3), - 'topfiles': { - 'NEWS': 'Old core news.\n', - '3.feature': 'Third feature addition.\n', - '5.misc': ''}, - 'conch': { - '_version.py': genVersion("twisted.conch", 3, 4, 5), - 'topfiles': { - 'NEWS': 'Old conch news.\n', - '7.bugfix': 'Fixed that bug.\n'}}, - }) - return project - - - def test_buildAll(self): - """ - L{NewsBuilder.buildAll} calls L{NewsBuilder.build} once for each - subproject, passing that subproject's I{topfiles} directory as C{path}, - the I{NEWS} file in that directory as C{output}, and the subproject's - name as C{header}, and then again for each subproject with the - top-level I{NEWS} file for C{output}. Blacklisted subprojects are - skipped. - """ - builds = [] - builder = NewsBuilder() - builder.build = lambda path, output, header: builds.append(( - path, output, header)) - builder._today = lambda: '2009-12-01' - - project = self.createFakeTwistedProject() - builder.buildAll(project) - - coreTopfiles = project.child("topfiles") - coreNews = coreTopfiles.child("NEWS") - coreHeader = "Twisted Core 1.2.3 (2009-12-01)" - - conchTopfiles = project.child("conch").child("topfiles") - conchNews = conchTopfiles.child("NEWS") - conchHeader = "Twisted Conch 3.4.5 (2009-12-01)" - - aggregateNews = project.child("NEWS") - - self.assertEqual( - builds, - [(conchTopfiles, conchNews, conchHeader), - (coreTopfiles, coreNews, coreHeader), - (conchTopfiles, aggregateNews, conchHeader), - (coreTopfiles, aggregateNews, coreHeader)]) - - - def test_changeVersionInNews(self): - """ - L{NewsBuilder._changeVersions} gets the release date for a given - version of a project as a string. - """ - builder = NewsBuilder() - builder._today = lambda: '2009-12-01' - project = self.createFakeTwistedProject() - builder.buildAll(project) - newVersion = Version('TEMPLATE', 7, 7, 14) - coreNews = project.child('topfiles').child('NEWS') - # twisted 1.2.3 is the old version. - builder._changeNewsVersion( - coreNews, "Core", Version("twisted", 1, 2, 3), - newVersion, '2010-01-01') - expectedCore = ( - 'Twisted Core 7.7.14 (2010-01-01)\n' - '================================\n' - '\n' - 'Features\n' - '--------\n' - ' - Third feature addition. (#3)\n' - '\n' - 'Other\n' - '-----\n' - ' - #5\n\n\n') - self.assertEqual( - expectedCore + 'Old core news.\n', coreNews.getContent()) - - - -class DistributionBuilderTestBase(BuilderTestsMixin, StructureAssertingMixin, - TestCase): - """ - Base for tests of L{DistributionBuilder}. - """ - skip = loreSkip - - def setUp(self): - BuilderTestsMixin.setUp(self) - - self.rootDir = FilePath(self.mktemp()) - self.rootDir.createDirectory() - - self.outputDir = FilePath(self.mktemp()) - self.outputDir.createDirectory() - self.builder = DistributionBuilder(self.rootDir, self.outputDir) - - - -class DistributionBuilderTest(DistributionBuilderTestBase): - - def test_twistedDistribution(self): - """ - The Twisted tarball contains everything in the source checkout, with - built documentation. - """ - loreInput, loreOutput = self.getArbitraryLoreInputAndOutput("10.0.0") - manInput1 = self.getArbitraryManInput() - manOutput1 = self.getArbitraryManHTMLOutput("10.0.0", "../howto/") - manInput2 = self.getArbitraryManInput() - manOutput2 = self.getArbitraryManHTMLOutput("10.0.0", "../howto/") - coreIndexInput, coreIndexOutput = self.getArbitraryLoreInputAndOutput( - "10.0.0", prefix="howto/") - - structure = { - "README": "Twisted", - "unrelated": "x", - "LICENSE": "copyright!", - "setup.py": "import toplevel", - "bin": {"web": {"websetroot": "SET ROOT"}, - "twistd": "TWISTD"}, - "twisted": - {"web": - {"__init__.py": "import WEB", - "topfiles": {"setup.py": "import WEBINSTALL", - "README": "WEB!"}}, - "words": {"__init__.py": "import WORDS"}, - "plugins": {"twisted_web.py": "import WEBPLUG", - "twisted_words.py": "import WORDPLUG"}}, - "doc": {"web": {"howto": {"index.xhtml": loreInput}, - "man": {"websetroot.1": manInput2}}, - "core": {"howto": {"template.tpl": self.template}, - "man": {"twistd.1": manInput1}, - "index.xhtml": coreIndexInput}}} - - outStructure = { - "README": "Twisted", - "unrelated": "x", - "LICENSE": "copyright!", - "setup.py": "import toplevel", - "bin": {"web": {"websetroot": "SET ROOT"}, - "twistd": "TWISTD"}, - "twisted": - {"web": {"__init__.py": "import WEB", - "topfiles": {"setup.py": "import WEBINSTALL", - "README": "WEB!"}}, - "words": {"__init__.py": "import WORDS"}, - "plugins": {"twisted_web.py": "import WEBPLUG", - "twisted_words.py": "import WORDPLUG"}}, - "doc": {"web": {"howto": {"index.html": loreOutput}, - "man": {"websetroot.1": manInput2, - "websetroot-man.html": manOutput2}}, - "core": {"howto": {"template.tpl": self.template}, - "man": {"twistd.1": manInput1, - "twistd-man.html": manOutput1}, - "index.html": coreIndexOutput}}} - - self.createStructure(self.rootDir, structure) - - outputFile = self.builder.buildTwisted("10.0.0") - - self.assertExtractedStructure(outputFile, outStructure) - - - def test_excluded(self): - """ - bin/admin and doc/historic are excluded from the Twisted tarball. - """ - structure = { - "bin": {"admin": {"blah": "ADMIN"}, - "twistd": "TWISTD"}, - "twisted": - {"web": - {"__init__.py": "import WEB", - "topfiles": {"setup.py": "import WEBINSTALL", - "README": "WEB!"}}, - }, - "doc": {"historic": {"hello": "there"}, - "other": "contents", - }, - } - - outStructure = { - "bin": {"twistd": "TWISTD"}, - "twisted": - {"web": - {"__init__.py": "import WEB", - "topfiles": {"setup.py": "import WEBINSTALL", - "README": "WEB!"}}, - }, - "doc": {"other": "contents"}, - } - - self.createStructure(self.rootDir, structure) - outputFile = self.builder.buildTwisted("10.0.0") - self.assertExtractedStructure(outputFile, outStructure) - - - def test_subProjectLayout(self): - """ - The subproject tarball includes files like so: - - 1. twisted/<subproject>/topfiles defines the files that will be in the - top level in the tarball, except LICENSE, which comes from the real - top-level directory. - 2. twisted/<subproject> is included, but without the topfiles entry - in that directory. No other twisted subpackages are included. - 3. twisted/plugins/twisted_<subproject>.py is included, but nothing - else in plugins is. - """ - structure = { - "README": "HI!@", - "unrelated": "x", - "LICENSE": "copyright!", - "setup.py": "import toplevel", - "bin": {"web": {"websetroot": "SET ROOT"}, - "words": {"im": "#!im"}}, - "twisted": - {"web": - {"__init__.py": "import WEB", - "topfiles": {"setup.py": "import WEBINSTALL", - "README": "WEB!"}}, - "words": {"__init__.py": "import WORDS"}, - "plugins": {"twisted_web.py": "import WEBPLUG", - "twisted_words.py": "import WORDPLUG"}}} - - outStructure = { - "README": "WEB!", - "LICENSE": "copyright!", - "setup.py": "import WEBINSTALL", - "bin": {"websetroot": "SET ROOT"}, - "twisted": {"web": {"__init__.py": "import WEB"}, - "plugins": {"twisted_web.py": "import WEBPLUG"}}} - - self.createStructure(self.rootDir, structure) - - outputFile = self.builder.buildSubProject("web", "0.3.0") - - self.assertExtractedStructure(outputFile, outStructure) - - - def test_minimalSubProjectLayout(self): - """ - buildSubProject should work with minimal subprojects. - """ - structure = { - "LICENSE": "copyright!", - "bin": {}, - "twisted": - {"web": {"__init__.py": "import WEB", - "topfiles": {"setup.py": "import WEBINSTALL"}}, - "plugins": {}}} - - outStructure = { - "setup.py": "import WEBINSTALL", - "LICENSE": "copyright!", - "twisted": {"web": {"__init__.py": "import WEB"}}} - - self.createStructure(self.rootDir, structure) - - outputFile = self.builder.buildSubProject("web", "0.3.0") - - self.assertExtractedStructure(outputFile, outStructure) - - - def test_subProjectDocBuilding(self): - """ - When building a subproject release, documentation should be built with - lore. - """ - loreInput, loreOutput = self.getArbitraryLoreInputAndOutput("0.3.0") - manInput = self.getArbitraryManInput() - manOutput = self.getArbitraryManHTMLOutput("0.3.0", "../howto/") - structure = { - "LICENSE": "copyright!", - "twisted": {"web": {"__init__.py": "import WEB", - "topfiles": {"setup.py": "import WEBINST"}}}, - "doc": {"web": {"howto": {"index.xhtml": loreInput}, - "man": {"twistd.1": manInput}}, - "core": {"howto": {"template.tpl": self.template}} - } - } - - outStructure = { - "LICENSE": "copyright!", - "setup.py": "import WEBINST", - "twisted": {"web": {"__init__.py": "import WEB"}}, - "doc": {"howto": {"index.html": loreOutput}, - "man": {"twistd.1": manInput, - "twistd-man.html": manOutput}}} - - self.createStructure(self.rootDir, structure) - - outputFile = self.builder.buildSubProject("web", "0.3.0") - - self.assertExtractedStructure(outputFile, outStructure) - - - def test_coreProjectLayout(self): - """ - The core tarball looks a lot like a subproject tarball, except it - doesn't include: - - - Python packages from other subprojects - - plugins from other subprojects - - scripts from other subprojects - """ - indexInput, indexOutput = self.getArbitraryLoreInputAndOutput( - "8.0.0", prefix="howto/") - howtoInput, howtoOutput = self.getArbitraryLoreInputAndOutput("8.0.0") - specInput, specOutput = self.getArbitraryLoreInputAndOutput( - "8.0.0", prefix="../howto/") - tutorialInput, tutorialOutput = self.getArbitraryLoreInputAndOutput( - "8.0.0", prefix="../") - - structure = { - "LICENSE": "copyright!", - "twisted": {"__init__.py": "twisted", - "python": {"__init__.py": "python", - "roots.py": "roots!"}, - "conch": {"__init__.py": "conch", - "unrelated.py": "import conch"}, - "plugin.py": "plugin", - "plugins": {"twisted_web.py": "webplug", - "twisted_whatever.py": "include!", - "cred.py": "include!"}, - "topfiles": {"setup.py": "import CORE", - "README": "core readme"}}, - "doc": {"core": {"howto": {"template.tpl": self.template, - "index.xhtml": howtoInput, - "tutorial": - {"index.xhtml": tutorialInput}}, - "specifications": {"index.xhtml": specInput}, - "examples": {"foo.py": "foo.py"}, - "index.xhtml": indexInput}, - "web": {"howto": {"index.xhtml": "webindex"}}}, - "bin": {"twistd": "TWISTD", - "web": {"websetroot": "websetroot"}} - } - - outStructure = { - "LICENSE": "copyright!", - "setup.py": "import CORE", - "README": "core readme", - "twisted": {"__init__.py": "twisted", - "python": {"__init__.py": "python", - "roots.py": "roots!"}, - "plugin.py": "plugin", - "plugins": {"twisted_whatever.py": "include!", - "cred.py": "include!"}}, - "doc": {"howto": {"template.tpl": self.template, - "index.html": howtoOutput, - "tutorial": {"index.html": tutorialOutput}}, - "specifications": {"index.html": specOutput}, - "examples": {"foo.py": "foo.py"}, - "index.html": indexOutput}, - "bin": {"twistd": "TWISTD"}, - } - - self.createStructure(self.rootDir, structure) - outputFile = self.builder.buildCore("8.0.0") - self.assertExtractedStructure(outputFile, outStructure) - - - def test_apiBaseURL(self): - """ - DistributionBuilder builds documentation with the specified - API base URL. - """ - apiBaseURL = "http://%s" - builder = DistributionBuilder(self.rootDir, self.outputDir, - apiBaseURL=apiBaseURL) - loreInput, loreOutput = self.getArbitraryLoreInputAndOutput( - "0.3.0", apiBaseURL=apiBaseURL) - structure = { - "LICENSE": "copyright!", - "twisted": {"web": {"__init__.py": "import WEB", - "topfiles": {"setup.py": "import WEBINST"}}}, - "doc": {"web": {"howto": {"index.xhtml": loreInput}}, - "core": {"howto": {"template.tpl": self.template}} - } - } - - outStructure = { - "LICENSE": "copyright!", - "setup.py": "import WEBINST", - "twisted": {"web": {"__init__.py": "import WEB"}}, - "doc": {"howto": {"index.html": loreOutput}}} - - self.createStructure(self.rootDir, structure) - outputFile = builder.buildSubProject("web", "0.3.0") - self.assertExtractedStructure(outputFile, outStructure) - - - -class BuildAllTarballsTest(DistributionBuilderTestBase): - """ - Tests for L{DistributionBuilder.buildAllTarballs}. - """ - skip = svnSkip - - def setUp(self): - self.oldHandler = signal.signal(signal.SIGCHLD, signal.SIG_DFL) - DistributionBuilderTestBase.setUp(self) - - - def tearDown(self): - signal.signal(signal.SIGCHLD, self.oldHandler) - DistributionBuilderTestBase.tearDown(self) - - - def test_buildAllTarballs(self): - """ - L{buildAllTarballs} builds tarballs for Twisted and all of its - subprojects based on an SVN checkout; the resulting tarballs contain - no SVN metadata. This involves building documentation, which it will - build with the correct API documentation reference base URL. - """ - repositoryPath = self.mktemp() - repository = FilePath(repositoryPath) - checkoutPath = self.mktemp() - checkout = FilePath(checkoutPath) - self.outputDir.remove() - - runCommand(["svnadmin", "create", repositoryPath]) - runCommand(["svn", "checkout", "file://" + repository.path, - checkout.path]) - coreIndexInput, coreIndexOutput = self.getArbitraryLoreInputAndOutput( - "1.2.0", prefix="howto/", - apiBaseURL="http://twistedmatrix.com/documents/1.2.0/api/%s.html") - - structure = { - "README": "Twisted", - "unrelated": "x", - "LICENSE": "copyright!", - "setup.py": "import toplevel", - "bin": {"words": {"im": "import im"}, - "twistd": "TWISTD"}, - "twisted": - { - "topfiles": {"setup.py": "import TOPINSTALL", - "README": "CORE!"}, - "_version.py": genVersion("twisted", 1, 2, 0), - "words": {"__init__.py": "import WORDS", - "_version.py": - genVersion("twisted.words", 1, 2, 0), - "topfiles": {"setup.py": "import WORDSINSTALL", - "README": "WORDS!"}, - }, - "plugins": {"twisted_web.py": "import WEBPLUG", - "twisted_words.py": "import WORDPLUG", - "twisted_yay.py": "import YAY"}}, - "doc": {"core": {"howto": {"template.tpl": self.template}, - "index.xhtml": coreIndexInput}}} - - twistedStructure = { - "README": "Twisted", - "unrelated": "x", - "LICENSE": "copyright!", - "setup.py": "import toplevel", - "bin": {"twistd": "TWISTD", - "words": {"im": "import im"}}, - "twisted": - { - "topfiles": {"setup.py": "import TOPINSTALL", - "README": "CORE!"}, - "_version.py": genVersion("twisted", 1, 2, 0), - "words": {"__init__.py": "import WORDS", - "_version.py": - genVersion("twisted.words", 1, 2, 0), - "topfiles": {"setup.py": "import WORDSINSTALL", - "README": "WORDS!"}, - }, - "plugins": {"twisted_web.py": "import WEBPLUG", - "twisted_words.py": "import WORDPLUG", - "twisted_yay.py": "import YAY"}}, - "doc": {"core": {"howto": {"template.tpl": self.template}, - "index.html": coreIndexOutput}}} - - coreStructure = { - "setup.py": "import TOPINSTALL", - "README": "CORE!", - "LICENSE": "copyright!", - "bin": {"twistd": "TWISTD"}, - "twisted": { - "_version.py": genVersion("twisted", 1, 2, 0), - "plugins": {"twisted_yay.py": "import YAY"}}, - "doc": {"howto": {"template.tpl": self.template}, - "index.html": coreIndexOutput}} - - wordsStructure = { - "README": "WORDS!", - "LICENSE": "copyright!", - "setup.py": "import WORDSINSTALL", - "bin": {"im": "import im"}, - "twisted": - { - "words": {"__init__.py": "import WORDS", - "_version.py": - genVersion("twisted.words", 1, 2, 0), - }, - "plugins": {"twisted_words.py": "import WORDPLUG"}}} - - self.createStructure(checkout, structure) - childs = [x.path for x in checkout.children()] - runCommand(["svn", "add"] + childs) - runCommand(["svn", "commit", checkout.path, "-m", "yay"]) - - buildAllTarballs(checkout, self.outputDir) - self.assertEqual( - set(self.outputDir.children()), - set([self.outputDir.child("Twisted-1.2.0.tar.bz2"), - self.outputDir.child("TwistedCore-1.2.0.tar.bz2"), - self.outputDir.child("TwistedWords-1.2.0.tar.bz2")])) - - self.assertExtractedStructure( - self.outputDir.child("Twisted-1.2.0.tar.bz2"), - twistedStructure) - self.assertExtractedStructure( - self.outputDir.child("TwistedCore-1.2.0.tar.bz2"), - coreStructure) - self.assertExtractedStructure( - self.outputDir.child("TwistedWords-1.2.0.tar.bz2"), - wordsStructure) - - - def test_buildAllTarballsEnsuresCleanCheckout(self): - """ - L{UncleanWorkingDirectory} is raised by L{buildAllTarballs} when the - SVN checkout provided has uncommitted changes. - """ - repositoryPath = self.mktemp() - repository = FilePath(repositoryPath) - checkoutPath = self.mktemp() - checkout = FilePath(checkoutPath) - - runCommand(["svnadmin", "create", repositoryPath]) - runCommand(["svn", "checkout", "file://" + repository.path, - checkout.path]) - - checkout.child("foo").setContent("whatever") - self.assertRaises(UncleanWorkingDirectory, - buildAllTarballs, checkout, FilePath(self.mktemp())) - - - def test_buildAllTarballsEnsuresExistingCheckout(self): - """ - L{NotWorkingDirectory} is raised by L{buildAllTarballs} when the - checkout passed does not exist or is not an SVN checkout. - """ - checkout = FilePath(self.mktemp()) - self.assertRaises(NotWorkingDirectory, - buildAllTarballs, - checkout, FilePath(self.mktemp())) - checkout.createDirectory() - self.assertRaises(NotWorkingDirectory, - buildAllTarballs, - checkout, FilePath(self.mktemp())) - - - -class ScriptTests(BuilderTestsMixin, StructureAssertingMixin, TestCase): - """ - Tests for the release script functionality. - """ - - def _testVersionChanging(self, major, minor, micro, prerelease=None): - """ - Check that L{ChangeVersionsScript.main} calls the version-changing - function with the appropriate version data and filesystem path. - """ - versionUpdates = [] - def myVersionChanger(sourceTree, versionTemplate): - versionUpdates.append((sourceTree, versionTemplate)) - versionChanger = ChangeVersionsScript() - versionChanger.changeAllProjectVersions = myVersionChanger - version = "%d.%d.%d" % (major, minor, micro) - if prerelease is not None: - version += "pre%d" % (prerelease,) - versionChanger.main([version]) - self.assertEqual(len(versionUpdates), 1) - self.assertEqual(versionUpdates[0][0], FilePath(".")) - self.assertEqual(versionUpdates[0][1].major, major) - self.assertEqual(versionUpdates[0][1].minor, minor) - self.assertEqual(versionUpdates[0][1].micro, micro) - self.assertEqual(versionUpdates[0][1].prerelease, prerelease) - - - def test_changeVersions(self): - """ - L{ChangeVersionsScript.main} changes version numbers for all Twisted - projects. - """ - self._testVersionChanging(8, 2, 3) - - - def test_changeVersionsWithPrerelease(self): - """ - A prerelease can be specified to L{changeVersionsScript}. - """ - self._testVersionChanging(9, 2, 7, 38) - - - def test_defaultChangeVersionsVersionChanger(self): - """ - The default implementation of C{changeAllProjectVersions} is - L{changeAllProjectVersions}. - """ - versionChanger = ChangeVersionsScript() - self.assertEqual(versionChanger.changeAllProjectVersions, - changeAllProjectVersions) - - - def test_badNumberOfArgumentsToChangeVersionsScript(self): - """ - L{changeVersionsScript} raises SystemExit when the wrong number of - arguments are passed. - """ - versionChanger = ChangeVersionsScript() - self.assertRaises(SystemExit, versionChanger.main, []) - - - def test_tooManyDotsToChangeVersionsScript(self): - """ - L{changeVersionsScript} raises SystemExit when there are the wrong - number of segments in the version number passed. - """ - versionChanger = ChangeVersionsScript() - self.assertRaises(SystemExit, versionChanger.main, - ["3.2.1.0"]) - - - def test_nonIntPartsToChangeVersionsScript(self): - """ - L{changeVersionsScript} raises SystemExit when the version number isn't - made out of numbers. - """ - versionChanger = ChangeVersionsScript() - self.assertRaises(SystemExit, versionChanger.main, - ["my united.states.of prewhatever"]) - - - def test_buildTarballsScript(self): - """ - L{BuildTarballsScript.main} invokes L{buildAllTarballs} with - 2 or 3 L{FilePath} instances representing the paths passed to it. - """ - builds = [] - def myBuilder(checkout, destination, template=None): - builds.append((checkout, destination, template)) - tarballBuilder = BuildTarballsScript() - tarballBuilder.buildAllTarballs = myBuilder - - tarballBuilder.main(["checkoutDir", "destinationDir"]) - self.assertEqual( - builds, - [(FilePath("checkoutDir"), FilePath("destinationDir"), None)]) - - builds = [] - tarballBuilder.main(["checkoutDir", "destinationDir", "templatePath"]) - self.assertEqual( - builds, - [(FilePath("checkoutDir"), FilePath("destinationDir"), - FilePath("templatePath"))]) - - - def test_defaultBuildTarballsScriptBuilder(self): - """ - The default implementation of L{BuildTarballsScript.buildAllTarballs} - is L{buildAllTarballs}. - """ - tarballBuilder = BuildTarballsScript() - self.assertEqual(tarballBuilder.buildAllTarballs, buildAllTarballs) - - - def test_badNumberOfArgumentsToBuildTarballs(self): - """ - L{BuildTarballsScript.main} raises SystemExit when the wrong number of - arguments are passed. - """ - tarballBuilder = BuildTarballsScript() - self.assertRaises(SystemExit, tarballBuilder.main, []) - self.assertRaises(SystemExit, tarballBuilder.main, ["a", "b", "c", "d"]) - - - def test_badNumberOfArgumentsToBuildNews(self): - """ - L{NewsBuilder.main} raises L{SystemExit} when other than 1 argument is - passed to it. - """ - newsBuilder = NewsBuilder() - self.assertRaises(SystemExit, newsBuilder.main, []) - self.assertRaises(SystemExit, newsBuilder.main, ["hello", "world"]) - - - def test_buildNews(self): - """ - L{NewsBuilder.main} calls L{NewsBuilder.buildAll} with a L{FilePath} - instance constructed from the path passed to it. - """ - builds = [] - newsBuilder = NewsBuilder() - newsBuilder.buildAll = builds.append - newsBuilder.main(["/foo/bar/baz"]) - self.assertEqual(builds, [FilePath("/foo/bar/baz")]) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_runtime.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_runtime.py deleted file mode 100755 index 4c94fb5e..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_runtime.py +++ /dev/null @@ -1,106 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for runtime checks. -""" - -import sys - -from twisted.python.runtime import Platform, shortPythonVersion -from twisted.trial.unittest import TestCase - - - -class PythonVersionTests(TestCase): - """ - Tests the shortPythonVersion method. - """ - - def test_shortPythonVersion(self): - """ - Verify if the Python version is returned correctly. - """ - ver = shortPythonVersion().split('.') - for i in range(3): - self.assertEqual(int(ver[i]), sys.version_info[i]) - - - -class PlatformTests(TestCase): - """ - Tests for the default L{Platform} initializer. - """ - - def test_isVistaConsistency(self): - """ - Verify consistency of L{Platform.isVista}: it can only be C{True} if - L{Platform.isWinNT} and L{Platform.isWindows} are C{True}. - """ - platform = Platform() - if platform.isVista(): - self.assertTrue(platform.isWinNT()) - self.assertTrue(platform.isWindows()) - self.assertFalse(platform.isMacOSX()) - - - def test_isMacOSXConsistency(self): - """ - L{Platform.isMacOSX} can only return C{True} if L{Platform.getType} - returns C{'posix'}. - """ - platform = Platform() - if platform.isMacOSX(): - self.assertEqual(platform.getType(), 'posix') - - - def test_isLinuxConsistency(self): - """ - L{Platform.isLinux} can only return C{True} if L{Platform.getType} - returns C{'posix'} and L{sys.platform} starts with C{"linux"}. - """ - platform = Platform() - if platform.isLinux(): - self.assertTrue(sys.platform.startswith("linux")) - - - -class ForeignPlatformTests(TestCase): - """ - Tests for L{Platform} based overridden initializer values. - """ - - def test_getType(self): - """ - If an operating system name is supplied to L{Platform}'s initializer, - L{Platform.getType} returns the platform type which corresponds to that - name. - """ - self.assertEqual(Platform('nt').getType(), 'win32') - self.assertEqual(Platform('ce').getType(), 'win32') - self.assertEqual(Platform('posix').getType(), 'posix') - self.assertEqual(Platform('java').getType(), 'java') - - - def test_isMacOSX(self): - """ - If a system platform name is supplied to L{Platform}'s initializer, it - is used to determine the result of L{Platform.isMacOSX}, which returns - C{True} for C{"darwin"}, C{False} otherwise. - """ - self.assertTrue(Platform(None, 'darwin').isMacOSX()) - self.assertFalse(Platform(None, 'linux2').isMacOSX()) - self.assertFalse(Platform(None, 'win32').isMacOSX()) - - - def test_isLinux(self): - """ - If a system platform name is supplied to L{Platform}'s initializer, it - is used to determine the result of L{Platform.isLinux}, which returns - C{True} for values beginning with C{"linux"}, C{False} otherwise. - """ - self.assertFalse(Platform(None, 'darwin').isLinux()) - self.assertTrue(Platform(None, 'linux').isLinux()) - self.assertTrue(Platform(None, 'linux2').isLinux()) - self.assertTrue(Platform(None, 'linux3').isLinux()) - self.assertFalse(Platform(None, 'win32').isLinux()) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_sendmsg.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_sendmsg.py deleted file mode 100755 index 48301f5e..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_sendmsg.py +++ /dev/null @@ -1,543 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for L{twisted.python.sendmsg}. -""" - -import sys -import errno - -from socket import SOL_SOCKET, AF_INET, AF_INET6, socket, error - -try: - from socket import AF_UNIX, socketpair -except ImportError: - nonUNIXSkip = "Platform does not support AF_UNIX sockets" -else: - nonUNIXSkip = None - -from struct import pack -from os import devnull, pipe, read, close, environ - -from twisted.internet.defer import Deferred -from twisted.internet.error import ProcessDone -from twisted.trial.unittest import TestCase -from twisted.internet.defer import inlineCallbacks -from twisted.internet import reactor -from twisted.python.filepath import FilePath -from twisted.python.runtime import platform - -from twisted.internet.protocol import ProcessProtocol - -if platform.isLinux(): - from socket import MSG_DONTWAIT - dontWaitSkip = None -else: - # It would be nice to be able to test flags on more platforms, but finding a - # flag that works *at all* is somewhat challenging. - dontWaitSkip = "MSG_DONTWAIT is only known to work as intended on Linux" - -try: - from twisted.python.sendmsg import SCM_RIGHTS, send1msg, recv1msg, getsockfam -except ImportError: - importSkip = "Cannot import twisted.python.sendmsg" -else: - importSkip = None - - -class ExitedWithStderr(Exception): - """ - A process exited with some stderr. - """ - - def __str__(self): - """ - Dump the errors in a pretty way in the event of a subprocess traceback. - """ - return '\n'.join([''] + list(self.args)) - - -class StartStopProcessProtocol(ProcessProtocol): - """ - An L{IProcessProtocol} with a Deferred for events where the subprocess - starts and stops. - - @ivar started: A L{Deferred} which fires with this protocol's - L{IProcessTransport} provider when it is connected to one. - - @ivar stopped: A L{Deferred} which fires with the process output or a - failure if the process produces output on standard error. - - @ivar output: A C{str} used to accumulate standard output. - - @ivar errors: A C{str} used to accumulate standard error. - """ - def __init__(self): - self.started = Deferred() - self.stopped = Deferred() - self.output = '' - self.errors = '' - - - def connectionMade(self): - self.started.callback(self.transport) - - - def outReceived(self, data): - self.output += data - - - def errReceived(self, data): - self.errors += data - - - def processEnded(self, reason): - if reason.check(ProcessDone): - self.stopped.callback(self.output) - else: - self.stopped.errback(ExitedWithStderr( - self.errors, self.output)) - - - -class BadList(list): - """ - A list which cannot be iterated sometimes. - - This is a C{list} subclass to get past the type check in L{send1msg}, not as - an example of how real programs might want to interact with L{send1msg} (or - anything else). A custom C{list} subclass makes it easier to trigger - certain error cases in the implementation. - - @ivar iterate: A flag which indicates whether an instance of L{BadList} will - allow iteration over itself or not. If C{False}, an attempt to iterate - over the instance will raise an exception. - """ - iterate = True - - def __iter__(self): - """ - Allow normal list iteration, or raise an exception. - - If C{self.iterate} is C{True}, it will be flipped to C{False} and then - normal iteration will proceed. If C{self.iterate} is C{False}, - L{RuntimeError} is raised instead. - """ - if self.iterate: - self.iterate = False - return super(BadList, self).__iter__() - raise RuntimeError("Something bad happened") - - - -class WorseList(list): - """ - A list which at first gives the appearance of being iterable, but then - raises an exception. - - See L{BadList} for a warning about not writing code like this. - """ - def __iter__(self): - """ - Return an iterator which will raise an exception as soon as C{next} is - called on it. - """ - class BadIterator(object): - def next(self): - raise RuntimeError("This is a really bad case.") - return BadIterator() - - - -class SendmsgTestCase(TestCase): - """ - Tests for sendmsg extension module and associated file-descriptor sending - functionality. - """ - if nonUNIXSkip is not None: - skip = nonUNIXSkip - elif importSkip is not None: - skip = importSkip - - def setUp(self): - """ - Create a pair of UNIX sockets. - """ - self.input, self.output = socketpair(AF_UNIX) - - - def tearDown(self): - """ - Close the sockets opened by setUp. - """ - self.input.close() - self.output.close() - - - def test_sendmsgBadArguments(self): - """ - The argument types accepted by L{send1msg} are: - - 1. C{int} - 2. read-only character buffer - 3. C{int} - 4. sequence - - The 3rd and 4th arguments are optional. If fewer than two arguments or - more than four arguments are passed, or if any of the arguments passed - are not compatible with these types, L{TypeError} is raised. - """ - # Exercise the wrong number of arguments cases - self.assertRaises(TypeError, send1msg) - self.assertRaises(TypeError, send1msg, 1) - self.assertRaises(TypeError, send1msg, 1, "hello world", 2, [], object()) - - # Exercise the wrong type of arguments cases - self.assertRaises(TypeError, send1msg, object(), "hello world", 2, []) - self.assertRaises(TypeError, send1msg, 1, object(), 2, []) - self.assertRaises(TypeError, send1msg, 1, "hello world", object(), []) - self.assertRaises(TypeError, send1msg, 1, "hello world", 2, object()) - - - def test_badAncillaryIter(self): - """ - If iteration over the ancillary data list fails (at the point of the - C{__iter__} call), the exception with which it fails is propagated to - the caller of L{send1msg}. - """ - badList = BadList() - badList.append((1, 2, "hello world")) - badList.iterate = False - - self.assertRaises(RuntimeError, send1msg, 1, "hello world", 2, badList) - - # Hit the second iteration - badList.iterate = True - self.assertRaises(RuntimeError, send1msg, 1, "hello world", 2, badList) - - - def test_badAncillaryNext(self): - """ - If iteration over the ancillary data list fails (at the point of a - C{next} call), the exception with which it fails is propagated to the - caller of L{send1msg}. - """ - worseList = WorseList() - self.assertRaises(RuntimeError, send1msg, 1, "hello world", 2, worseList) - - - def test_sendmsgBadAncillaryItem(self): - """ - The ancillary data list contains three-tuples with element types of: - - 1. C{int} - 2. C{int} - 3. read-only character buffer - - If a tuple in the ancillary data list does not elements of these types, - L{TypeError} is raised. - """ - # Exercise the wrong number of arguments cases - self.assertRaises(TypeError, send1msg, 1, "hello world", 2, [()]) - self.assertRaises(TypeError, send1msg, 1, "hello world", 2, [(1,)]) - self.assertRaises(TypeError, send1msg, 1, "hello world", 2, [(1, 2)]) - self.assertRaises( - TypeError, - send1msg, 1, "hello world", 2, [(1, 2, "goodbye", object())]) - - # Exercise the wrong type of arguments cases - exc = self.assertRaises( - TypeError, send1msg, 1, "hello world", 2, [object()]) - self.assertEqual( - "send1msg argument 3 expected list of tuple, " - "got list containing object", - str(exc)) - self.assertRaises( - TypeError, - send1msg, 1, "hello world", 2, [(object(), 1, "goodbye")]) - self.assertRaises( - TypeError, - send1msg, 1, "hello world", 2, [(1, object(), "goodbye")]) - self.assertRaises( - TypeError, - send1msg, 1, "hello world", 2, [(1, 1, object())]) - - - def test_syscallError(self): - """ - If the underlying C{sendmsg} call fails, L{send1msg} raises - L{socket.error} with its errno set to the underlying errno value. - """ - probe = file(devnull) - fd = probe.fileno() - probe.close() - exc = self.assertRaises(error, send1msg, fd, "hello, world") - self.assertEqual(exc.args[0], errno.EBADF) - - - def test_syscallErrorWithControlMessage(self): - """ - The behavior when the underlying C{sendmsg} call fails is the same - whether L{send1msg} is passed ancillary data or not. - """ - probe = file(devnull) - fd = probe.fileno() - probe.close() - exc = self.assertRaises( - error, send1msg, fd, "hello, world", 0, [(0, 0, "0123")]) - self.assertEqual(exc.args[0], errno.EBADF) - - - def test_roundtrip(self): - """ - L{recv1msg} will retrieve a message sent via L{send1msg}. - """ - message = "hello, world!" - self.assertEqual( - len(message), - send1msg(self.input.fileno(), message, 0)) - - result = recv1msg(fd=self.output.fileno()) - self.assertEquals(result, (message, 0, [])) - - - def test_shortsend(self): - """ - L{send1msg} returns the number of bytes which it was able to send. - """ - message = "x" * 1024 * 1024 - self.input.setblocking(False) - sent = send1msg(self.input.fileno(), message) - # Sanity check - make sure we did fill the send buffer and then some - self.assertTrue(sent < len(message)) - received = recv1msg(self.output.fileno(), 0, len(message)) - self.assertEqual(len(received[0]), sent) - - - def test_roundtripEmptyAncillary(self): - """ - L{send1msg} treats an empty ancillary data list the same way it treats - receiving no argument for the ancillary parameter at all. - """ - send1msg(self.input.fileno(), "hello, world!", 0, []) - - result = recv1msg(fd=self.output.fileno()) - self.assertEquals(result, ("hello, world!", 0, [])) - - - def test_flags(self): - """ - The C{flags} argument to L{send1msg} is passed on to the underlying - C{sendmsg} call, to affect it in whatever way is defined by those flags. - """ - # Just exercise one flag with simple, well-known behavior. MSG_DONTWAIT - # makes the send a non-blocking call, even if the socket is in blocking - # mode. See also test_flags in RecvmsgTestCase - for i in range(1024): - try: - send1msg(self.input.fileno(), "x" * 1024, MSG_DONTWAIT) - except error, e: - self.assertEqual(e.args[0], errno.EAGAIN) - break - else: - self.fail( - "Failed to fill up the send buffer, " - "or maybe send1msg blocked for a while") - if dontWaitSkip is not None: - test_flags.skip = dontWaitSkip - - - def test_wrongTypeAncillary(self): - """ - L{send1msg} will show a helpful exception message when given the wrong - type of object for the 'ancillary' argument. - """ - error = self.assertRaises(TypeError, - send1msg, self.input.fileno(), - "hello, world!", 0, 4321) - self.assertEquals(str(error), - "send1msg argument 3 expected list, got int") - - - def spawn(self, script): - """ - Start a script that is a peer of this test as a subprocess. - - @param script: the module name of the script in this directory (no - package prefix, no '.py') - @type script: C{str} - - @rtype: L{StartStopProcessProtocol} - """ - sspp = StartStopProcessProtocol() - reactor.spawnProcess( - sspp, sys.executable, [ - sys.executable, - FilePath(__file__).sibling(script + ".py").path, - str(self.output.fileno()), - ], - environ, - childFDs={0: "w", 1: "r", 2: "r", - self.output.fileno(): self.output.fileno()} - ) - return sspp - - - @inlineCallbacks - def test_sendSubProcessFD(self): - """ - Calling L{sendsmsg} with SOL_SOCKET, SCM_RIGHTS, and a platform-endian - packed file descriptor number should send that file descriptor to a - different process, where it can be retrieved by using L{recv1msg}. - """ - sspp = self.spawn("pullpipe") - yield sspp.started - pipeOut, pipeIn = pipe() - self.addCleanup(close, pipeOut) - - send1msg( - self.input.fileno(), "blonk", 0, - [(SOL_SOCKET, SCM_RIGHTS, pack("i", pipeIn))]) - - close(pipeIn) - yield sspp.stopped - self.assertEquals(read(pipeOut, 1024), "Test fixture data: blonk.\n") - # Make sure that the pipe is actually closed now. - self.assertEquals(read(pipeOut, 1024), "") - - - -class RecvmsgTestCase(TestCase): - """ - Tests for L{recv1msg} (primarily error handling cases). - """ - if importSkip is not None: - skip = importSkip - - def test_badArguments(self): - """ - The argument types accepted by L{recv1msg} are: - - 1. C{int} - 2. C{int} - 3. C{int} - 4. C{int} - - The 2nd, 3rd, and 4th arguments are optional. If fewer than one - argument or more than four arguments are passed, or if any of the - arguments passed are not compatible with these types, L{TypeError} is - raised. - """ - # Exercise the wrong number of arguments cases - self.assertRaises(TypeError, recv1msg) - self.assertRaises(TypeError, recv1msg, 1, 2, 3, 4, object()) - - # Exercise the wrong type of arguments cases - self.assertRaises(TypeError, recv1msg, object(), 2, 3, 4) - self.assertRaises(TypeError, recv1msg, 1, object(), 3, 4) - self.assertRaises(TypeError, recv1msg, 1, 2, object(), 4) - self.assertRaises(TypeError, recv1msg, 1, 2, 3, object()) - - - def test_cmsgSpaceOverflow(self): - """ - L{recv1msg} raises L{OverflowError} if passed a value for the - C{cmsg_size} argument which exceeds C{SOCKLEN_MAX}. - """ - self.assertRaises(OverflowError, recv1msg, 0, 0, 0, 0x7FFFFFFF) - - - def test_syscallError(self): - """ - If the underlying C{recvmsg} call fails, L{recv1msg} raises - L{socket.error} with its errno set to the underlying errno value. - """ - probe = file(devnull) - fd = probe.fileno() - probe.close() - exc = self.assertRaises(error, recv1msg, fd) - self.assertEqual(exc.args[0], errno.EBADF) - - - def test_flags(self): - """ - The C{flags} argument to L{recv1msg} is passed on to the underlying - C{recvmsg} call, to affect it in whatever way is defined by those flags. - """ - # See test_flags in SendmsgTestCase - reader, writer = socketpair(AF_UNIX) - exc = self.assertRaises( - error, recv1msg, reader.fileno(), MSG_DONTWAIT) - self.assertEqual(exc.args[0], errno.EAGAIN) - if dontWaitSkip is not None: - test_flags.skip = dontWaitSkip - - - -class GetSocketFamilyTests(TestCase): - """ - Tests for L{getsockfam}, a helper which reveals the address family of an - arbitrary socket. - """ - if importSkip is not None: - skip = importSkip - - def _socket(self, addressFamily): - """ - Create a new socket using the given address family and return that - socket's file descriptor. The socket will automatically be closed when - the test is torn down. - """ - s = socket(addressFamily) - self.addCleanup(s.close) - return s.fileno() - - - def test_badArguments(self): - """ - L{getsockfam} accepts a single C{int} argument. If it is called in some - other way, L{TypeError} is raised. - """ - self.assertRaises(TypeError, getsockfam) - self.assertRaises(TypeError, getsockfam, 1, 2) - - self.assertRaises(TypeError, getsockfam, object()) - - - def test_syscallError(self): - """ - If the underlying C{getsockname} call fails, L{getsockfam} raises - L{socket.error} with its errno set to the underlying errno value. - """ - probe = file(devnull) - fd = probe.fileno() - probe.close() - exc = self.assertRaises(error, getsockfam, fd) - self.assertEqual(errno.EBADF, exc.args[0]) - - - def test_inet(self): - """ - When passed the file descriptor of a socket created with the C{AF_INET} - address family, L{getsockfam} returns C{AF_INET}. - """ - self.assertEqual(AF_INET, getsockfam(self._socket(AF_INET))) - - - def test_inet6(self): - """ - When passed the file descriptor of a socket created with the C{AF_INET6} - address family, L{getsockfam} returns C{AF_INET6}. - """ - self.assertEqual(AF_INET6, getsockfam(self._socket(AF_INET6))) - - - def test_unix(self): - """ - When passed the file descriptor of a socket created with the C{AF_UNIX} - address family, L{getsockfam} returns C{AF_UNIX}. - """ - self.assertEqual(AF_UNIX, getsockfam(self._socket(AF_UNIX))) - if nonUNIXSkip is not None: - test_unix.skip = nonUNIXSkip diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_shellcomp.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_shellcomp.py deleted file mode 100755 index 7f9cc833..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_shellcomp.py +++ /dev/null @@ -1,623 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Test cases for twisted.python._shellcomp -""" - -import sys -from cStringIO import StringIO - -from twisted.trial import unittest -from twisted.python import _shellcomp, usage, reflect -from twisted.python.usage import Completions, Completer, CompleteFiles -from twisted.python.usage import CompleteList - - - -class ZshScriptTestMeta(type): - """ - Metaclass of ZshScriptTestMixin. - """ - def __new__(cls, name, bases, attrs): - def makeTest(cmdName, optionsFQPN): - def runTest(self): - return test_genZshFunction(self, cmdName, optionsFQPN) - return runTest - - # add test_ methods to the class for each script - # we are testing. - if 'generateFor' in attrs: - for cmdName, optionsFQPN in attrs['generateFor']: - test = makeTest(cmdName, optionsFQPN) - attrs['test_genZshFunction_' + cmdName] = test - - return type.__new__(cls, name, bases, attrs) - - - -class ZshScriptTestMixin(object): - """ - Integration test helper to show that C{usage.Options} classes can have zsh - completion functions generated for them without raising errors. - - In your subclasses set a class variable like so: - - # | cmd name | Fully Qualified Python Name of Options class | - # - generateFor = [('conch', 'twisted.conch.scripts.conch.ClientOptions'), - ('twistd', 'twisted.scripts.twistd.ServerOptions'), - ] - - Each package that contains Twisted scripts should contain one TestCase - subclass which also inherits from this mixin, and contains a C{generateFor} - list appropriate for the scripts in that package. - """ - __metaclass__ = ZshScriptTestMeta - - - -def test_genZshFunction(self, cmdName, optionsFQPN): - """ - Generate completion functions for given twisted command - no errors - should be raised - - @type cmdName: C{str} - @param cmdName: The name of the command-line utility e.g. 'twistd' - - @type optionsFQPN: C{str} - @param optionsFQPN: The Fully Qualified Python Name of the C{Options} - class to be tested. - """ - outputFile = StringIO() - self.patch(usage.Options, '_shellCompFile', outputFile) - - # some scripts won't import or instantiate because of missing - # dependencies (PyCrypto, etc) so we have to skip them. - try: - o = reflect.namedAny(optionsFQPN)() - except Exception, e: - raise unittest.SkipTest("Couldn't import or instantiate " - "Options class: %s" % (e,)) - - try: - o.parseOptions(["", "--_shell-completion", "zsh:2"]) - except ImportError, e: - # this can happen for commands which don't have all - # the necessary dependencies installed. skip test. - # skip - raise unittest.SkipTest("ImportError calling parseOptions(): %s", (e,)) - except SystemExit: - pass # expected - else: - self.fail('SystemExit not raised') - outputFile.seek(0) - # test that we got some output - self.assertEqual(1, len(outputFile.read(1))) - outputFile.seek(0) - outputFile.truncate() - - # now, if it has sub commands, we have to test those too - if hasattr(o, 'subCommands'): - for (cmd, short, parser, doc) in o.subCommands: - try: - o.parseOptions([cmd, "", "--_shell-completion", - "zsh:3"]) - except ImportError, e: - # this can happen for commands which don't have all - # the necessary dependencies installed. skip test. - raise unittest.SkipTest("ImportError calling parseOptions() " - "on subcommand: %s", (e,)) - except SystemExit: - pass # expected - else: - self.fail('SystemExit not raised') - - outputFile.seek(0) - # test that we got some output - self.assertEqual(1, len(outputFile.read(1))) - outputFile.seek(0) - outputFile.truncate() - - # flushed because we don't want DeprecationWarnings to be printed when - # running these test cases. - self.flushWarnings() - - - -class ZshTestCase(unittest.TestCase): - """ - Tests for zsh completion code - """ - def test_accumulateMetadata(self): - """ - Are `compData' attributes you can place on Options classes - picked up correctly? - """ - opts = FighterAceExtendedOptions() - ag = _shellcomp.ZshArgumentsGenerator(opts, 'ace', 'dummy_value') - - descriptions = FighterAceOptions.compData.descriptions.copy() - descriptions.update(FighterAceExtendedOptions.compData.descriptions) - - self.assertEqual(ag.descriptions, descriptions) - self.assertEqual(ag.multiUse, - set(FighterAceOptions.compData.multiUse)) - self.assertEqual(ag.mutuallyExclusive, - FighterAceOptions.compData.mutuallyExclusive) - - optActions = FighterAceOptions.compData.optActions.copy() - optActions.update(FighterAceExtendedOptions.compData.optActions) - self.assertEqual(ag.optActions, optActions) - - self.assertEqual(ag.extraActions, - FighterAceOptions.compData.extraActions) - - - def test_mutuallyExclusiveCornerCase(self): - """ - Exercise a corner-case of ZshArgumentsGenerator.makeExcludesDict() - where the long option name already exists in the `excludes` dict being - built. - """ - class OddFighterAceOptions(FighterAceExtendedOptions): - # since "fokker", etc, are already defined as mutually- - # exclusive on the super-class, defining them again here forces - # the corner-case to be exercised. - optFlags = [['anatra', None, - 'Select the Anatra DS as your dogfighter aircraft']] - compData = Completions( - mutuallyExclusive=[['anatra', 'fokker', 'albatros', - 'spad', 'bristol']]) - - opts = OddFighterAceOptions() - ag = _shellcomp.ZshArgumentsGenerator(opts, 'ace', 'dummy_value') - - expected = { - 'albatros': set(['anatra', 'b', 'bristol', 'f', - 'fokker', 's', 'spad']), - 'anatra': set(['a', 'albatros', 'b', 'bristol', - 'f', 'fokker', 's', 'spad']), - 'bristol': set(['a', 'albatros', 'anatra', 'f', - 'fokker', 's', 'spad']), - 'fokker': set(['a', 'albatros', 'anatra', 'b', - 'bristol', 's', 'spad']), - 'spad': set(['a', 'albatros', 'anatra', 'b', - 'bristol', 'f', 'fokker'])} - - self.assertEqual(ag.excludes, expected) - - - def test_accumulateAdditionalOptions(self): - """ - We pick up options that are only defined by having an - appropriately named method on your Options class, - e.g. def opt_foo(self, foo) - """ - opts = FighterAceExtendedOptions() - ag = _shellcomp.ZshArgumentsGenerator(opts, 'ace', 'dummy_value') - - self.assertIn('nocrash', ag.flagNameToDefinition) - self.assertIn('nocrash', ag.allOptionsNameToDefinition) - - self.assertIn('difficulty', ag.paramNameToDefinition) - self.assertIn('difficulty', ag.allOptionsNameToDefinition) - - - def test_verifyZshNames(self): - """ - Using a parameter/flag name that doesn't exist - will raise an error - """ - class TmpOptions(FighterAceExtendedOptions): - # Note typo of detail - compData = Completions(optActions={'detaill' : None}) - - self.assertRaises(ValueError, _shellcomp.ZshArgumentsGenerator, - TmpOptions(), 'ace', 'dummy_value') - - class TmpOptions2(FighterAceExtendedOptions): - # Note that 'foo' and 'bar' are not real option - # names defined in this class - compData = Completions( - mutuallyExclusive=[("foo", "bar")]) - - self.assertRaises(ValueError, _shellcomp.ZshArgumentsGenerator, - TmpOptions2(), 'ace', 'dummy_value') - - - def test_zshCode(self): - """ - Generate a completion function, and test the textual output - against a known correct output - """ - outputFile = StringIO() - self.patch(usage.Options, '_shellCompFile', outputFile) - self.patch(sys, 'argv', ["silly", "", "--_shell-completion", "zsh:2"]) - opts = SimpleProgOptions() - self.assertRaises(SystemExit, opts.parseOptions) - self.assertEqual(testOutput1, outputFile.getvalue()) - - - def test_zshCodeWithSubs(self): - """ - Generate a completion function with subcommands, - and test the textual output against a known correct output - """ - outputFile = StringIO() - self.patch(usage.Options, '_shellCompFile', outputFile) - self.patch(sys, 'argv', ["silly2", "", "--_shell-completion", "zsh:2"]) - opts = SimpleProgWithSubcommands() - self.assertRaises(SystemExit, opts.parseOptions) - self.assertEqual(testOutput2, outputFile.getvalue()) - - - def test_incompleteCommandLine(self): - """ - Completion still happens even if a command-line is given - that would normally throw UsageError. - """ - outputFile = StringIO() - self.patch(usage.Options, '_shellCompFile', outputFile) - opts = FighterAceOptions() - - self.assertRaises(SystemExit, opts.parseOptions, - ["--fokker", "server", "--unknown-option", - "--unknown-option2", - "--_shell-completion", "zsh:5"]) - outputFile.seek(0) - # test that we got some output - self.assertEqual(1, len(outputFile.read(1))) - - - def test_incompleteCommandLine_case2(self): - """ - Completion still happens even if a command-line is given - that would normally throw UsageError. - - The existance of --unknown-option prior to the subcommand - will break subcommand detection... but we complete anyway - """ - outputFile = StringIO() - self.patch(usage.Options, '_shellCompFile', outputFile) - opts = FighterAceOptions() - - self.assertRaises(SystemExit, opts.parseOptions, - ["--fokker", "--unknown-option", "server", - "--list-server", "--_shell-completion", "zsh:5"]) - outputFile.seek(0) - # test that we got some output - self.assertEqual(1, len(outputFile.read(1))) - - outputFile.seek(0) - outputFile.truncate() - - - def test_incompleteCommandLine_case3(self): - """ - Completion still happens even if a command-line is given - that would normally throw UsageError. - - Break subcommand detection in a different way by providing - an invalid subcommand name. - """ - outputFile = StringIO() - self.patch(usage.Options, '_shellCompFile', outputFile) - opts = FighterAceOptions() - - self.assertRaises(SystemExit, opts.parseOptions, - ["--fokker", "unknown-subcommand", - "--list-server", "--_shell-completion", "zsh:4"]) - outputFile.seek(0) - # test that we got some output - self.assertEqual(1, len(outputFile.read(1))) - - - def test_skipSubcommandList(self): - """ - Ensure the optimization which skips building the subcommand list - under certain conditions isn't broken. - """ - outputFile = StringIO() - self.patch(usage.Options, '_shellCompFile', outputFile) - opts = FighterAceOptions() - - self.assertRaises(SystemExit, opts.parseOptions, - ["--alba", "--_shell-completion", "zsh:2"]) - outputFile.seek(0) - # test that we got some output - self.assertEqual(1, len(outputFile.read(1))) - - - def test_poorlyDescribedOptMethod(self): - """ - Test corner case fetching an option description from a method docstring - """ - opts = FighterAceOptions() - argGen = _shellcomp.ZshArgumentsGenerator(opts, 'ace', None) - - descr = argGen.getDescription('silly') - - # docstring for opt_silly is useless so it should just use the - # option name as the description - self.assertEqual(descr, 'silly') - - - def test_brokenActions(self): - """ - A C{Completer} with repeat=True may only be used as the - last item in the extraActions list. - """ - class BrokenActions(usage.Options): - compData = usage.Completions( - extraActions=[usage.Completer(repeat=True), - usage.Completer()] - ) - - outputFile = StringIO() - opts = BrokenActions() - self.patch(opts, '_shellCompFile', outputFile) - self.assertRaises(ValueError, opts.parseOptions, - ["", "--_shell-completion", "zsh:2"]) - - - def test_optMethodsDontOverride(self): - """ - opt_* methods on Options classes should not override the - data provided in optFlags or optParameters. - """ - class Options(usage.Options): - optFlags = [['flag', 'f', 'A flag']] - optParameters = [['param', 'p', None, 'A param']] - - def opt_flag(self): - """ junk description """ - - def opt_param(self, param): - """ junk description """ - - opts = Options() - argGen = _shellcomp.ZshArgumentsGenerator(opts, 'ace', None) - - self.assertEqual(argGen.getDescription('flag'), 'A flag') - self.assertEqual(argGen.getDescription('param'), 'A param') - - - -class EscapeTestCase(unittest.TestCase): - def test_escape(self): - """ - Verify _shellcomp.escape() function - """ - esc = _shellcomp.escape - - test = "$" - self.assertEqual(esc(test), "'$'") - - test = 'A--\'$"\\`--B' - self.assertEqual(esc(test), '"A--\'\\$\\"\\\\\\`--B"') - - - -class CompleterNotImplementedTestCase(unittest.TestCase): - """ - Test that using an unknown shell constant with SubcommandAction - raises NotImplementedError - - The other Completer() subclasses are tested in test_usage.py - """ - def test_unknownShell(self): - """ - Using an unknown shellType should raise NotImplementedError - """ - action = _shellcomp.SubcommandAction() - - self.assertRaises(NotImplementedError, action._shellCode, - None, "bad_shell_type") - - - -class FighterAceServerOptions(usage.Options): - """ - Options for FighterAce 'server' subcommand - """ - optFlags = [['list-server', None, - 'List this server with the online FighterAce network']] - optParameters = [['packets-per-second', None, - 'Number of update packets to send per second', '20']] - - - -class FighterAceOptions(usage.Options): - """ - Command-line options for an imaginary `Fighter Ace` game - """ - optFlags = [['fokker', 'f', - 'Select the Fokker Dr.I as your dogfighter aircraft'], - ['albatros', 'a', - 'Select the Albatros D-III as your dogfighter aircraft'], - ['spad', 's', - 'Select the SPAD S.VII as your dogfighter aircraft'], - ['bristol', 'b', - 'Select the Bristol Scout as your dogfighter aircraft'], - ['physics', 'p', - 'Enable secret Twisted physics engine'], - ['jam', 'j', - 'Enable a small chance that your machine guns will jam!'], - ['verbose', 'v', - 'Verbose logging (may be specified more than once)'], - ] - - optParameters = [['pilot-name', None, "What's your name, Ace?", - 'Manfred von Richthofen'], - ['detail', 'd', - 'Select the level of rendering detail (1-5)', '3'], - ] - - subCommands = [['server', None, FighterAceServerOptions, - 'Start FighterAce game-server.'], - ] - - compData = Completions( - descriptions={'physics' : 'Twisted-Physics', - 'detail' : 'Rendering detail level'}, - multiUse=['verbose'], - mutuallyExclusive=[['fokker', 'albatros', 'spad', - 'bristol']], - optActions={'detail' : CompleteList(['1' '2' '3' - '4' '5'])}, - extraActions=[CompleteFiles(descr='saved game file to load')] - ) - - def opt_silly(self): - # A silly option which nobody can explain - """ """ - - - -class FighterAceExtendedOptions(FighterAceOptions): - """ - Extend the options and zsh metadata provided by FighterAceOptions. - _shellcomp must accumulate options and metadata from all classes in the - hiearchy so this is important to test. - """ - optFlags = [['no-stalls', None, - 'Turn off the ability to stall your aircraft']] - optParameters = [['reality-level', None, - 'Select the level of physics reality (1-5)', '5']] - - compData = Completions( - descriptions={'no-stalls' : 'Can\'t stall your plane'}, - optActions={'reality-level' : - Completer(descr='Physics reality level')} - ) - - def opt_nocrash(self): - """ - Select that you can't crash your plane - """ - - - def opt_difficulty(self, difficulty): - """ - How tough are you? (1-10) - """ - - - -def _accuracyAction(): - # add tick marks just to exercise quoting - return CompleteList(['1', '2', '3'], descr='Accuracy\'`?') - - - -class SimpleProgOptions(usage.Options): - """ - Command-line options for a `Silly` imaginary program - """ - optFlags = [['color', 'c', 'Turn on color output'], - ['gray', 'g', 'Turn on gray-scale output'], - ['verbose', 'v', - 'Verbose logging (may be specified more than once)'], - ] - - optParameters = [['optimization', None, '5', - 'Select the level of optimization (1-5)'], - ['accuracy', 'a', '3', - 'Select the level of accuracy (1-3)'], - ] - - - compData = Completions( - descriptions={'color' : 'Color on', - 'optimization' : 'Optimization level'}, - multiUse=['verbose'], - mutuallyExclusive=[['color', 'gray']], - optActions={'optimization' : CompleteList(['1', '2', '3', '4', '5'], - descr='Optimization?'), - 'accuracy' : _accuracyAction}, - extraActions=[CompleteFiles(descr='output file')] - ) - - def opt_X(self): - """ - usage.Options does not recognize single-letter opt_ methods - """ - - - -class SimpleProgSub1(usage.Options): - optFlags = [['sub-opt', 's', 'Sub Opt One']] - - - -class SimpleProgSub2(usage.Options): - optFlags = [['sub-opt', 's', 'Sub Opt Two']] - - - -class SimpleProgWithSubcommands(SimpleProgOptions): - optFlags = [['some-option'], - ['other-option', 'o']] - - optParameters = [['some-param'], - ['other-param', 'p'], - ['another-param', 'P', 'Yet Another Param']] - - subCommands = [ ['sub1', None, SimpleProgSub1, 'Sub Command 1'], - ['sub2', None, SimpleProgSub2, 'Sub Command 2']] - - - -testOutput1 = """#compdef silly - -_arguments -s -A "-*" \\ -':output file (*):_files -g "*"' \\ -"(--accuracy)-a[Select the level of accuracy (1-3)]:Accuracy'\`?:(1 2 3)" \\ -"(-a)--accuracy=[Select the level of accuracy (1-3)]:Accuracy'\`?:(1 2 3)" \\ -'(--color --gray -g)-c[Color on]' \\ -'(--gray -c -g)--color[Color on]' \\ -'(--color --gray -c)-g[Turn on gray-scale output]' \\ -'(--color -c -g)--gray[Turn on gray-scale output]' \\ -'--help[Display this help and exit.]' \\ -'--optimization=[Optimization level]:Optimization?:(1 2 3 4 5)' \\ -'*-v[Verbose logging (may be specified more than once)]' \\ -'*--verbose[Verbose logging (may be specified more than once)]' \\ -'--version[Display Twisted version and exit.]' \\ -&& return 0 -""" - -# with sub-commands -testOutput2 = """#compdef silly2 - -_arguments -s -A "-*" \\ -'*::subcmd:->subcmd' \\ -':output file (*):_files -g "*"' \\ -"(--accuracy)-a[Select the level of accuracy (1-3)]:Accuracy'\`?:(1 2 3)" \\ -"(-a)--accuracy=[Select the level of accuracy (1-3)]:Accuracy'\`?:(1 2 3)" \\ -'(--another-param)-P[another-param]:another-param:_files' \\ -'(-P)--another-param=[another-param]:another-param:_files' \\ -'(--color --gray -g)-c[Color on]' \\ -'(--gray -c -g)--color[Color on]' \\ -'(--color --gray -c)-g[Turn on gray-scale output]' \\ -'(--color -c -g)--gray[Turn on gray-scale output]' \\ -'--help[Display this help and exit.]' \\ -'--optimization=[Optimization level]:Optimization?:(1 2 3 4 5)' \\ -'(--other-option)-o[other-option]' \\ -'(-o)--other-option[other-option]' \\ -'(--other-param)-p[other-param]:other-param:_files' \\ -'(-p)--other-param=[other-param]:other-param:_files' \\ -'--some-option[some-option]' \\ -'--some-param=[some-param]:some-param:_files' \\ -'*-v[Verbose logging (may be specified more than once)]' \\ -'*--verbose[Verbose logging (may be specified more than once)]' \\ -'--version[Display Twisted version and exit.]' \\ -&& return 0 -local _zsh_subcmds_array -_zsh_subcmds_array=( -"sub1:Sub Command 1" -"sub2:Sub Command 2" -) - -_describe "sub-command" _zsh_subcmds_array -""" diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_syslog.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_syslog.py deleted file mode 100755 index 559c62f3..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_syslog.py +++ /dev/null @@ -1,151 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -from twisted.trial.unittest import TestCase -from twisted.python.failure import Failure - -try: - import syslog as stdsyslog -except ImportError: - stdsyslog = None -else: - from twisted.python import syslog - - - -class SyslogObserverTests(TestCase): - """ - Tests for L{SyslogObserver} which sends Twisted log events to the syslog. - """ - events = None - - if stdsyslog is None: - skip = "syslog is not supported on this platform" - - def setUp(self): - self.patch(syslog.SyslogObserver, 'openlog', self.openlog) - self.patch(syslog.SyslogObserver, 'syslog', self.syslog) - self.observer = syslog.SyslogObserver('SyslogObserverTests') - - - def openlog(self, prefix, options, facility): - self.logOpened = (prefix, options, facility) - self.events = [] - - - def syslog(self, options, message): - self.events.append((options, message)) - - - def test_emitWithoutMessage(self): - """ - L{SyslogObserver.emit} ignores events with an empty value for the - C{'message'} key. - """ - self.observer.emit({'message': (), 'isError': False, 'system': '-'}) - self.assertEqual(self.events, []) - - - def test_emitCustomPriority(self): - """ - L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the - syslog priority, if that key is present in the event dictionary. - """ - self.observer.emit({ - 'message': ('hello, world',), 'isError': False, 'system': '-', - 'syslogPriority': stdsyslog.LOG_DEBUG}) - self.assertEqual( - self.events, - [(stdsyslog.LOG_DEBUG, '[-] hello, world')]) - - - def test_emitErrorPriority(self): - """ - L{SyslogObserver.emit} uses C{LOG_ALERT} if the event represents an - error. - """ - self.observer.emit({ - 'message': ('hello, world',), 'isError': True, 'system': '-', - 'failure': Failure(Exception("foo"))}) - self.assertEqual( - self.events, - [(stdsyslog.LOG_ALERT, '[-] hello, world')]) - - - def test_emitCustomPriorityOverridesError(self): - """ - L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} key if - it is specified even if the event dictionary represents an error. - """ - self.observer.emit({ - 'message': ('hello, world',), 'isError': True, 'system': '-', - 'syslogPriority': stdsyslog.LOG_NOTICE, - 'failure': Failure(Exception("bar"))}) - self.assertEqual( - self.events, - [(stdsyslog.LOG_NOTICE, '[-] hello, world')]) - - - def test_emitCustomFacility(self): - """ - L{SyslogObserver.emit} uses the value of the C{'syslogPriority'} as the - syslog priority, if that key is present in the event dictionary. - """ - self.observer.emit({ - 'message': ('hello, world',), 'isError': False, 'system': '-', - 'syslogFacility': stdsyslog.LOG_CRON}) - self.assertEqual( - self.events, - [(stdsyslog.LOG_INFO | stdsyslog.LOG_CRON, '[-] hello, world')]) - - - def test_emitCustomSystem(self): - """ - L{SyslogObserver.emit} uses the value of the C{'system'} key to prefix - the logged message. - """ - self.observer.emit({'message': ('hello, world',), 'isError': False, - 'system': 'nonDefaultSystem'}) - self.assertEqual( - self.events, - [(stdsyslog.LOG_INFO, "[nonDefaultSystem] hello, world")]) - - - def test_emitMessage(self): - """ - L{SyslogObserver.emit} logs the value of the C{'message'} key of the - event dictionary it is passed to the syslog. - """ - self.observer.emit({ - 'message': ('hello, world',), 'isError': False, - 'system': '-'}) - self.assertEqual( - self.events, - [(stdsyslog.LOG_INFO, "[-] hello, world")]) - - - def test_emitMultilineMessage(self): - """ - Each line of a multiline message is emitted separately to the syslog. - """ - self.observer.emit({ - 'message': ('hello,\nworld',), 'isError': False, - 'system': '-'}) - self.assertEqual( - self.events, - [(stdsyslog.LOG_INFO, '[-] hello,'), - (stdsyslog.LOG_INFO, '[-] \tworld')]) - - - def test_emitStripsTrailingEmptyLines(self): - """ - Trailing empty lines of a multiline message are omitted from the - messages sent to the syslog. - """ - self.observer.emit({ - 'message': ('hello,\nworld\n\n',), 'isError': False, - 'system': '-'}) - self.assertEqual( - self.events, - [(stdsyslog.LOG_INFO, '[-] hello,'), - (stdsyslog.LOG_INFO, '[-] \tworld')]) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_systemd.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_systemd.py deleted file mode 100755 index 23d590f9..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_systemd.py +++ /dev/null @@ -1,173 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for L{twisted.python.systemd}. -""" - -import os - -from twisted.trial.unittest import TestCase -from twisted.python.systemd import ListenFDs - - -class InheritedDescriptorsMixin(object): - """ - Mixin for a L{TestCase} subclass which defines test methods for some kind of - systemd sd-daemon class. In particular, it defines tests for a - C{inheritedDescriptors} method. - """ - def test_inheritedDescriptors(self): - """ - C{inheritedDescriptors} returns a list of integers giving the file - descriptors which were inherited from systemd. - """ - sddaemon = self.getDaemon(7, 3) - self.assertEqual([7, 8, 9], sddaemon.inheritedDescriptors()) - - - def test_repeated(self): - """ - Any subsequent calls to C{inheritedDescriptors} return the same list. - """ - sddaemon = self.getDaemon(7, 3) - self.assertEqual( - sddaemon.inheritedDescriptors(), - sddaemon.inheritedDescriptors()) - - - -class MemoryOnlyMixin(object): - """ - Mixin for a L{TestCase} subclass which creates creating a fake, in-memory - implementation of C{inheritedDescriptors}. This provides verification that - the fake behaves in a compatible way with the real implementation. - """ - def getDaemon(self, start, count): - """ - Invent C{count} new I{file descriptors} (actually integers, attached to - no real file description), starting at C{start}. Construct and return a - new L{ListenFDs} which will claim those integers represent inherited - file descriptors. - """ - return ListenFDs(range(start, start + count)) - - - -class EnvironmentMixin(object): - """ - Mixin for a L{TestCase} subclass which creates a real implementation of - C{inheritedDescriptors} which is based on the environment variables set by - systemd. To facilitate testing, this mixin will also create a fake - environment dictionary and add keys to it to make it look as if some - descriptors have been inherited. - """ - def initializeEnvironment(self, count, pid): - """ - Create a copy of the process environment and add I{LISTEN_FDS} and - I{LISTEN_PID} (the environment variables set by systemd) to it. - """ - result = os.environ.copy() - result['LISTEN_FDS'] = str(count) - result['LISTEN_PID'] = str(pid) - return result - - - def getDaemon(self, start, count): - """ - Create a new L{ListenFDs} instance, initialized with a fake environment - dictionary which will be set up as systemd would have set it up if - C{count} descriptors were being inherited. The descriptors will also - start at C{start}. - """ - fakeEnvironment = self.initializeEnvironment(count, os.getpid()) - return ListenFDs.fromEnvironment(environ=fakeEnvironment, start=start) - - - -class MemoryOnlyTests(MemoryOnlyMixin, InheritedDescriptorsMixin, TestCase): - """ - Apply tests to L{ListenFDs}, explicitly constructed with some fake file - descriptors. - """ - - - -class EnvironmentTests(EnvironmentMixin, InheritedDescriptorsMixin, TestCase): - """ - Apply tests to L{ListenFDs}, constructed based on an environment dictionary. - """ - def test_secondEnvironment(self): - """ - Only a single L{Environment} can extract inherited file descriptors. - """ - fakeEnvironment = self.initializeEnvironment(3, os.getpid()) - first = ListenFDs.fromEnvironment(environ=fakeEnvironment) - second = ListenFDs.fromEnvironment(environ=fakeEnvironment) - self.assertEqual(range(3, 6), first.inheritedDescriptors()) - self.assertEqual([], second.inheritedDescriptors()) - - - def test_mismatchedPID(self): - """ - If the current process PID does not match the PID in the environment, no - inherited descriptors are reported. - """ - fakeEnvironment = self.initializeEnvironment(3, os.getpid() + 1) - sddaemon = ListenFDs.fromEnvironment(environ=fakeEnvironment) - self.assertEqual([], sddaemon.inheritedDescriptors()) - - - def test_missingPIDVariable(self): - """ - If the I{LISTEN_PID} environment variable is not present, no inherited - descriptors are reported. - """ - fakeEnvironment = self.initializeEnvironment(3, os.getpid()) - del fakeEnvironment['LISTEN_PID'] - sddaemon = ListenFDs.fromEnvironment(environ=fakeEnvironment) - self.assertEqual([], sddaemon.inheritedDescriptors()) - - - def test_nonIntegerPIDVariable(self): - """ - If the I{LISTEN_PID} environment variable is set to a string that cannot - be parsed as an integer, no inherited descriptors are reported. - """ - fakeEnvironment = self.initializeEnvironment(3, "hello, world") - sddaemon = ListenFDs.fromEnvironment(environ=fakeEnvironment) - self.assertEqual([], sddaemon.inheritedDescriptors()) - - - def test_missingFDSVariable(self): - """ - If the I{LISTEN_FDS} environment variable is not present, no inherited - descriptors are reported. - """ - fakeEnvironment = self.initializeEnvironment(3, os.getpid()) - del fakeEnvironment['LISTEN_FDS'] - sddaemon = ListenFDs.fromEnvironment(environ=fakeEnvironment) - self.assertEqual([], sddaemon.inheritedDescriptors()) - - - def test_nonIntegerFDSVariable(self): - """ - If the I{LISTEN_FDS} environment variable is set to a string that cannot - be parsed as an integer, no inherited descriptors are reported. - """ - fakeEnvironment = self.initializeEnvironment("hello, world", os.getpid()) - sddaemon = ListenFDs.fromEnvironment(environ=fakeEnvironment) - self.assertEqual([], sddaemon.inheritedDescriptors()) - - - def test_defaultEnviron(self): - """ - If the process environment is not explicitly passed to - L{Environment.__init__}, the real process environment dictionary is - used. - """ - self.patch(os, 'environ', { - 'LISTEN_PID': str(os.getpid()), - 'LISTEN_FDS': '5'}) - sddaemon = ListenFDs.fromEnvironment() - self.assertEqual(range(3, 3 + 5), sddaemon.inheritedDescriptors()) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_util.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_util.py deleted file mode 100755 index 08c39d65..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_util.py +++ /dev/null @@ -1,928 +0,0 @@ -# -*- test-case-name: twisted.python.test.test_util -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for L{twisted.python.util}. -""" - -import os.path, sys -import shutil, errno -try: - import pwd, grp -except ImportError: - pwd = grp = None - -from twisted.trial import unittest - -from twisted.python import util -from twisted.internet import reactor -from twisted.internet.interfaces import IReactorProcess -from twisted.internet.protocol import ProcessProtocol -from twisted.internet.defer import Deferred -from twisted.internet.error import ProcessDone - -from twisted.test.test_process import MockOS - - - -class UtilTestCase(unittest.TestCase): - - def testUniq(self): - l = ["a", 1, "ab", "a", 3, 4, 1, 2, 2, 4, 6] - self.assertEqual(util.uniquify(l), ["a", 1, "ab", 3, 4, 2, 6]) - - def testRaises(self): - self.failUnless(util.raises(ZeroDivisionError, divmod, 1, 0)) - self.failIf(util.raises(ZeroDivisionError, divmod, 0, 1)) - - try: - util.raises(TypeError, divmod, 1, 0) - except ZeroDivisionError: - pass - else: - raise unittest.FailTest, "util.raises didn't raise when it should have" - - def testUninterruptably(self): - def f(a, b): - self.calls += 1 - exc = self.exceptions.pop() - if exc is not None: - raise exc(errno.EINTR, "Interrupted system call!") - return a + b - - self.exceptions = [None] - self.calls = 0 - self.assertEqual(util.untilConcludes(f, 1, 2), 3) - self.assertEqual(self.calls, 1) - - self.exceptions = [None, OSError, IOError] - self.calls = 0 - self.assertEqual(util.untilConcludes(f, 2, 3), 5) - self.assertEqual(self.calls, 3) - - def testNameToLabel(self): - """ - Test the various kinds of inputs L{nameToLabel} supports. - """ - nameData = [ - ('f', 'F'), - ('fo', 'Fo'), - ('foo', 'Foo'), - ('fooBar', 'Foo Bar'), - ('fooBarBaz', 'Foo Bar Baz'), - ] - for inp, out in nameData: - got = util.nameToLabel(inp) - self.assertEqual( - got, out, - "nameToLabel(%r) == %r != %r" % (inp, got, out)) - - - def test_uidFromNumericString(self): - """ - When L{uidFromString} is called with a base-ten string representation - of an integer, it returns the integer. - """ - self.assertEqual(util.uidFromString("100"), 100) - - - def test_uidFromUsernameString(self): - """ - When L{uidFromString} is called with a base-ten string representation - of an integer, it returns the integer. - """ - pwent = pwd.getpwuid(os.getuid()) - self.assertEqual(util.uidFromString(pwent.pw_name), pwent.pw_uid) - if pwd is None: - test_uidFromUsernameString.skip = ( - "Username/UID conversion requires the pwd module.") - - - def test_gidFromNumericString(self): - """ - When L{gidFromString} is called with a base-ten string representation - of an integer, it returns the integer. - """ - self.assertEqual(util.gidFromString("100"), 100) - - - def test_gidFromGroupnameString(self): - """ - When L{gidFromString} is called with a base-ten string representation - of an integer, it returns the integer. - """ - grent = grp.getgrgid(os.getgid()) - self.assertEqual(util.gidFromString(grent.gr_name), grent.gr_gid) - if grp is None: - test_gidFromGroupnameString.skip = ( - "Group Name/GID conversion requires the grp module.") - - - -class SwitchUIDTest(unittest.TestCase): - """ - Tests for L{util.switchUID}. - """ - - if getattr(os, "getuid", None) is None: - skip = "getuid/setuid not available" - - - def setUp(self): - self.mockos = MockOS() - self.patch(util, "os", self.mockos) - self.patch(util, "initgroups", self.initgroups) - self.initgroupsCalls = [] - - - def initgroups(self, uid, gid): - """ - Save L{util.initgroups} calls in C{self.initgroupsCalls}. - """ - self.initgroupsCalls.append((uid, gid)) - - - def test_uid(self): - """ - L{util.switchUID} calls L{util.initgroups} and then C{os.setuid} with - the given uid. - """ - util.switchUID(12000, None) - self.assertEqual(self.initgroupsCalls, [(12000, None)]) - self.assertEqual(self.mockos.actions, [("setuid", 12000)]) - - - def test_euid(self): - """ - L{util.switchUID} calls L{util.initgroups} and then C{os.seteuid} with - the given uid if the C{euid} parameter is set to C{True}. - """ - util.switchUID(12000, None, True) - self.assertEqual(self.initgroupsCalls, [(12000, None)]) - self.assertEqual(self.mockos.seteuidCalls, [12000]) - - - def test_currentUID(self): - """ - If the current uid is the same as the uid passed to L{util.switchUID}, - then initgroups does not get called, but a warning is issued. - """ - uid = self.mockos.getuid() - util.switchUID(uid, None) - self.assertEqual(self.initgroupsCalls, []) - self.assertEqual(self.mockos.actions, []) - warnings = self.flushWarnings([util.switchUID]) - self.assertEqual(len(warnings), 1) - self.assertIn('tried to drop privileges and setuid %i' % uid, - warnings[0]['message']) - self.assertIn('but uid is already %i' % uid, warnings[0]['message']) - - - def test_currentEUID(self): - """ - If the current euid is the same as the euid passed to L{util.switchUID}, - then initgroups does not get called, but a warning is issued. - """ - euid = self.mockos.geteuid() - util.switchUID(euid, None, True) - self.assertEqual(self.initgroupsCalls, []) - self.assertEqual(self.mockos.seteuidCalls, []) - warnings = self.flushWarnings([util.switchUID]) - self.assertEqual(len(warnings), 1) - self.assertIn('tried to drop privileges and seteuid %i' % euid, - warnings[0]['message']) - self.assertIn('but euid is already %i' % euid, warnings[0]['message']) - - - -class TestMergeFunctionMetadata(unittest.TestCase): - """ - Tests for L{mergeFunctionMetadata}. - """ - - def test_mergedFunctionBehavesLikeMergeTarget(self): - """ - After merging C{foo}'s data into C{bar}, the returned function behaves - as if it is C{bar}. - """ - foo_object = object() - bar_object = object() - - def foo(): - return foo_object - - def bar(x, y, (a, b), c=10, *d, **e): - return bar_object - - baz = util.mergeFunctionMetadata(foo, bar) - self.assertIdentical(baz(1, 2, (3, 4), quux=10), bar_object) - - - def test_moduleIsMerged(self): - """ - Merging C{foo} into C{bar} returns a function with C{foo}'s - C{__module__}. - """ - def foo(): - pass - - def bar(): - pass - bar.__module__ = 'somewhere.else' - - baz = util.mergeFunctionMetadata(foo, bar) - self.assertEqual(baz.__module__, foo.__module__) - - - def test_docstringIsMerged(self): - """ - Merging C{foo} into C{bar} returns a function with C{foo}'s docstring. - """ - - def foo(): - """ - This is foo. - """ - - def bar(): - """ - This is bar. - """ - - baz = util.mergeFunctionMetadata(foo, bar) - self.assertEqual(baz.__doc__, foo.__doc__) - - - def test_nameIsMerged(self): - """ - Merging C{foo} into C{bar} returns a function with C{foo}'s name. - """ - - def foo(): - pass - - def bar(): - pass - - baz = util.mergeFunctionMetadata(foo, bar) - self.assertEqual(baz.__name__, foo.__name__) - - - def test_instanceDictionaryIsMerged(self): - """ - Merging C{foo} into C{bar} returns a function with C{bar}'s - dictionary, updated by C{foo}'s. - """ - - def foo(): - pass - foo.a = 1 - foo.b = 2 - - def bar(): - pass - bar.b = 3 - bar.c = 4 - - baz = util.mergeFunctionMetadata(foo, bar) - self.assertEqual(foo.a, baz.a) - self.assertEqual(foo.b, baz.b) - self.assertEqual(bar.c, baz.c) - - - -class OrderedDictTest(unittest.TestCase): - def testOrderedDict(self): - d = util.OrderedDict() - d['a'] = 'b' - d['b'] = 'a' - d[3] = 12 - d[1234] = 4321 - self.assertEqual(repr(d), "{'a': 'b', 'b': 'a', 3: 12, 1234: 4321}") - self.assertEqual(d.values(), ['b', 'a', 12, 4321]) - del d[3] - self.assertEqual(repr(d), "{'a': 'b', 'b': 'a', 1234: 4321}") - self.assertEqual(d, {'a': 'b', 'b': 'a', 1234:4321}) - self.assertEqual(d.keys(), ['a', 'b', 1234]) - self.assertEqual(list(d.iteritems()), - [('a', 'b'), ('b','a'), (1234, 4321)]) - item = d.popitem() - self.assertEqual(item, (1234, 4321)) - - def testInitialization(self): - d = util.OrderedDict({'monkey': 'ook', - 'apple': 'red'}) - self.failUnless(d._order) - - d = util.OrderedDict(((1,1),(3,3),(2,2),(0,0))) - self.assertEqual(repr(d), "{1: 1, 3: 3, 2: 2, 0: 0}") - -class InsensitiveDictTest(unittest.TestCase): - def testPreserve(self): - InsensitiveDict=util.InsensitiveDict - dct=InsensitiveDict({'Foo':'bar', 1:2, 'fnz':{1:2}}, preserve=1) - self.assertEqual(dct['fnz'], {1:2}) - self.assertEqual(dct['foo'], 'bar') - self.assertEqual(dct.copy(), dct) - self.assertEqual(dct['foo'], dct.get('Foo')) - assert 1 in dct and 'foo' in dct - self.assertEqual(eval(repr(dct)), dct) - keys=['Foo', 'fnz', 1] - for x in keys: - assert x in dct.keys() - assert (x, dct[x]) in dct.items() - self.assertEqual(len(keys), len(dct)) - del dct[1] - del dct['foo'] - - def testNoPreserve(self): - InsensitiveDict=util.InsensitiveDict - dct=InsensitiveDict({'Foo':'bar', 1:2, 'fnz':{1:2}}, preserve=0) - keys=['foo', 'fnz', 1] - for x in keys: - assert x in dct.keys() - assert (x, dct[x]) in dct.items() - self.assertEqual(len(keys), len(dct)) - del dct[1] - del dct['foo'] - - - - -class PasswordTestingProcessProtocol(ProcessProtocol): - """ - Write the string C{"secret\n"} to a subprocess and then collect all of - its output and fire a Deferred with it when the process ends. - """ - def connectionMade(self): - self.output = [] - self.transport.write('secret\n') - - def childDataReceived(self, fd, output): - self.output.append((fd, output)) - - def processEnded(self, reason): - self.finished.callback((reason, self.output)) - - -class GetPasswordTest(unittest.TestCase): - if not IReactorProcess.providedBy(reactor): - skip = "Process support required to test getPassword" - - def test_stdin(self): - """ - Making sure getPassword accepts a password from standard input by - running a child process which uses getPassword to read in a string - which it then writes it out again. Write a string to the child - process and then read one and make sure it is the right string. - """ - p = PasswordTestingProcessProtocol() - p.finished = Deferred() - reactor.spawnProcess( - p, - sys.executable, - [sys.executable, - '-c', - ('import sys\n' - 'from twisted.python.util import getPassword\n' - 'sys.stdout.write(getPassword())\n' - 'sys.stdout.flush()\n')], - env={'PYTHONPATH': os.pathsep.join(sys.path)}) - - def processFinished((reason, output)): - reason.trap(ProcessDone) - self.assertIn((1, 'secret'), output) - - return p.finished.addCallback(processFinished) - - - -class SearchUpwardsTest(unittest.TestCase): - def testSearchupwards(self): - os.makedirs('searchupwards/a/b/c') - file('searchupwards/foo.txt', 'w').close() - file('searchupwards/a/foo.txt', 'w').close() - file('searchupwards/a/b/c/foo.txt', 'w').close() - os.mkdir('searchupwards/bar') - os.mkdir('searchupwards/bam') - os.mkdir('searchupwards/a/bar') - os.mkdir('searchupwards/a/b/bam') - actual=util.searchupwards('searchupwards/a/b/c', - files=['foo.txt'], - dirs=['bar', 'bam']) - expected=os.path.abspath('searchupwards') + os.sep - self.assertEqual(actual, expected) - shutil.rmtree('searchupwards') - actual=util.searchupwards('searchupwards/a/b/c', - files=['foo.txt'], - dirs=['bar', 'bam']) - expected=None - self.assertEqual(actual, expected) - - - -class IntervalDifferentialTestCase(unittest.TestCase): - def testDefault(self): - d = iter(util.IntervalDifferential([], 10)) - for i in range(100): - self.assertEqual(d.next(), (10, None)) - - def testSingle(self): - d = iter(util.IntervalDifferential([5], 10)) - for i in range(100): - self.assertEqual(d.next(), (5, 0)) - - def testPair(self): - d = iter(util.IntervalDifferential([5, 7], 10)) - for i in range(100): - self.assertEqual(d.next(), (5, 0)) - self.assertEqual(d.next(), (2, 1)) - self.assertEqual(d.next(), (3, 0)) - self.assertEqual(d.next(), (4, 1)) - self.assertEqual(d.next(), (1, 0)) - self.assertEqual(d.next(), (5, 0)) - self.assertEqual(d.next(), (1, 1)) - self.assertEqual(d.next(), (4, 0)) - self.assertEqual(d.next(), (3, 1)) - self.assertEqual(d.next(), (2, 0)) - self.assertEqual(d.next(), (5, 0)) - self.assertEqual(d.next(), (0, 1)) - - def testTriple(self): - d = iter(util.IntervalDifferential([2, 4, 5], 10)) - for i in range(100): - self.assertEqual(d.next(), (2, 0)) - self.assertEqual(d.next(), (2, 0)) - self.assertEqual(d.next(), (0, 1)) - self.assertEqual(d.next(), (1, 2)) - self.assertEqual(d.next(), (1, 0)) - self.assertEqual(d.next(), (2, 0)) - self.assertEqual(d.next(), (0, 1)) - self.assertEqual(d.next(), (2, 0)) - self.assertEqual(d.next(), (0, 2)) - self.assertEqual(d.next(), (2, 0)) - self.assertEqual(d.next(), (0, 1)) - self.assertEqual(d.next(), (2, 0)) - self.assertEqual(d.next(), (1, 2)) - self.assertEqual(d.next(), (1, 0)) - self.assertEqual(d.next(), (0, 1)) - self.assertEqual(d.next(), (2, 0)) - self.assertEqual(d.next(), (2, 0)) - self.assertEqual(d.next(), (0, 1)) - self.assertEqual(d.next(), (0, 2)) - - def testInsert(self): - d = iter(util.IntervalDifferential([], 10)) - self.assertEqual(d.next(), (10, None)) - d.addInterval(3) - self.assertEqual(d.next(), (3, 0)) - self.assertEqual(d.next(), (3, 0)) - d.addInterval(6) - self.assertEqual(d.next(), (3, 0)) - self.assertEqual(d.next(), (3, 0)) - self.assertEqual(d.next(), (0, 1)) - self.assertEqual(d.next(), (3, 0)) - self.assertEqual(d.next(), (3, 0)) - self.assertEqual(d.next(), (0, 1)) - - def testRemove(self): - d = iter(util.IntervalDifferential([3, 5], 10)) - self.assertEqual(d.next(), (3, 0)) - self.assertEqual(d.next(), (2, 1)) - self.assertEqual(d.next(), (1, 0)) - d.removeInterval(3) - self.assertEqual(d.next(), (4, 0)) - self.assertEqual(d.next(), (5, 0)) - d.removeInterval(5) - self.assertEqual(d.next(), (10, None)) - self.assertRaises(ValueError, d.removeInterval, 10) - - - -class Record(util.FancyEqMixin): - """ - Trivial user of L{FancyEqMixin} used by tests. - """ - compareAttributes = ('a', 'b') - - def __init__(self, a, b): - self.a = a - self.b = b - - - -class DifferentRecord(util.FancyEqMixin): - """ - Trivial user of L{FancyEqMixin} which is not related to L{Record}. - """ - compareAttributes = ('a', 'b') - - def __init__(self, a, b): - self.a = a - self.b = b - - - -class DerivedRecord(Record): - """ - A class with an inheritance relationship to L{Record}. - """ - - - -class EqualToEverything(object): - """ - A class the instances of which consider themselves equal to everything. - """ - def __eq__(self, other): - return True - - - def __ne__(self, other): - return False - - - -class EqualToNothing(object): - """ - A class the instances of which consider themselves equal to nothing. - """ - def __eq__(self, other): - return False - - - def __ne__(self, other): - return True - - - -class EqualityTests(unittest.TestCase): - """ - Tests for L{FancyEqMixin}. - """ - def test_identity(self): - """ - Instances of a class which mixes in L{FancyEqMixin} but which - defines no comparison attributes compare by identity. - """ - class Empty(util.FancyEqMixin): - pass - - self.assertFalse(Empty() == Empty()) - self.assertTrue(Empty() != Empty()) - empty = Empty() - self.assertTrue(empty == empty) - self.assertFalse(empty != empty) - - - def test_equality(self): - """ - Instances of a class which mixes in L{FancyEqMixin} should compare - equal if all of their attributes compare equal. They should not - compare equal if any of their attributes do not compare equal. - """ - self.assertTrue(Record(1, 2) == Record(1, 2)) - self.assertFalse(Record(1, 2) == Record(1, 3)) - self.assertFalse(Record(1, 2) == Record(2, 2)) - self.assertFalse(Record(1, 2) == Record(3, 4)) - - - def test_unequality(self): - """ - Unequality between instances of a particular L{record} should be - defined as the negation of equality. - """ - self.assertFalse(Record(1, 2) != Record(1, 2)) - self.assertTrue(Record(1, 2) != Record(1, 3)) - self.assertTrue(Record(1, 2) != Record(2, 2)) - self.assertTrue(Record(1, 2) != Record(3, 4)) - - - def test_differentClassesEquality(self): - """ - Instances of different classes which mix in L{FancyEqMixin} should not - compare equal. - """ - self.assertFalse(Record(1, 2) == DifferentRecord(1, 2)) - - - def test_differentClassesInequality(self): - """ - Instances of different classes which mix in L{FancyEqMixin} should - compare unequal. - """ - self.assertTrue(Record(1, 2) != DifferentRecord(1, 2)) - - - def test_inheritedClassesEquality(self): - """ - An instance of a class which derives from a class which mixes in - L{FancyEqMixin} should compare equal to an instance of the base class - if and only if all of their attributes compare equal. - """ - self.assertTrue(Record(1, 2) == DerivedRecord(1, 2)) - self.assertFalse(Record(1, 2) == DerivedRecord(1, 3)) - self.assertFalse(Record(1, 2) == DerivedRecord(2, 2)) - self.assertFalse(Record(1, 2) == DerivedRecord(3, 4)) - - - def test_inheritedClassesInequality(self): - """ - An instance of a class which derives from a class which mixes in - L{FancyEqMixin} should compare unequal to an instance of the base - class if any of their attributes compare unequal. - """ - self.assertFalse(Record(1, 2) != DerivedRecord(1, 2)) - self.assertTrue(Record(1, 2) != DerivedRecord(1, 3)) - self.assertTrue(Record(1, 2) != DerivedRecord(2, 2)) - self.assertTrue(Record(1, 2) != DerivedRecord(3, 4)) - - - def test_rightHandArgumentImplementsEquality(self): - """ - The right-hand argument to the equality operator is given a chance - to determine the result of the operation if it is of a type - unrelated to the L{FancyEqMixin}-based instance on the left-hand - side. - """ - self.assertTrue(Record(1, 2) == EqualToEverything()) - self.assertFalse(Record(1, 2) == EqualToNothing()) - - - def test_rightHandArgumentImplementsUnequality(self): - """ - The right-hand argument to the non-equality operator is given a - chance to determine the result of the operation if it is of a type - unrelated to the L{FancyEqMixin}-based instance on the left-hand - side. - """ - self.assertFalse(Record(1, 2) != EqualToEverything()) - self.assertTrue(Record(1, 2) != EqualToNothing()) - - - -class RunAsEffectiveUserTests(unittest.TestCase): - """ - Test for the L{util.runAsEffectiveUser} function. - """ - - if getattr(os, "geteuid", None) is None: - skip = "geteuid/seteuid not available" - - def setUp(self): - self.mockos = MockOS() - self.patch(os, "geteuid", self.mockos.geteuid) - self.patch(os, "getegid", self.mockos.getegid) - self.patch(os, "seteuid", self.mockos.seteuid) - self.patch(os, "setegid", self.mockos.setegid) - - - def _securedFunction(self, startUID, startGID, wantUID, wantGID): - """ - Check if wanted UID/GID matched start or saved ones. - """ - self.assertTrue(wantUID == startUID or - wantUID == self.mockos.seteuidCalls[-1]) - self.assertTrue(wantGID == startGID or - wantGID == self.mockos.setegidCalls[-1]) - - - def test_forwardResult(self): - """ - L{util.runAsEffectiveUser} forwards the result obtained by calling the - given function - """ - result = util.runAsEffectiveUser(0, 0, lambda: 1) - self.assertEqual(result, 1) - - - def test_takeParameters(self): - """ - L{util.runAsEffectiveUser} pass the given parameters to the given - function. - """ - result = util.runAsEffectiveUser(0, 0, lambda x: 2*x, 3) - self.assertEqual(result, 6) - - - def test_takesKeyworkArguments(self): - """ - L{util.runAsEffectiveUser} pass the keyword parameters to the given - function. - """ - result = util.runAsEffectiveUser(0, 0, lambda x, y=1, z=1: x*y*z, 2, z=3) - self.assertEqual(result, 6) - - - def _testUIDGIDSwitch(self, startUID, startGID, wantUID, wantGID, - expectedUIDSwitches, expectedGIDSwitches): - """ - Helper method checking the calls to C{os.seteuid} and C{os.setegid} - made by L{util.runAsEffectiveUser}, when switching from startUID to - wantUID and from startGID to wantGID. - """ - self.mockos.euid = startUID - self.mockos.egid = startGID - util.runAsEffectiveUser( - wantUID, wantGID, - self._securedFunction, startUID, startGID, wantUID, wantGID) - self.assertEqual(self.mockos.seteuidCalls, expectedUIDSwitches) - self.assertEqual(self.mockos.setegidCalls, expectedGIDSwitches) - self.mockos.seteuidCalls = [] - self.mockos.setegidCalls = [] - - - def test_root(self): - """ - Check UID/GID switches when current effective UID is root. - """ - self._testUIDGIDSwitch(0, 0, 0, 0, [], []) - self._testUIDGIDSwitch(0, 0, 1, 0, [1, 0], []) - self._testUIDGIDSwitch(0, 0, 0, 1, [], [1, 0]) - self._testUIDGIDSwitch(0, 0, 1, 1, [1, 0], [1, 0]) - - - def test_UID(self): - """ - Check UID/GID switches when current effective UID is non-root. - """ - self._testUIDGIDSwitch(1, 0, 0, 0, [0, 1], []) - self._testUIDGIDSwitch(1, 0, 1, 0, [], []) - self._testUIDGIDSwitch(1, 0, 1, 1, [0, 1, 0, 1], [1, 0]) - self._testUIDGIDSwitch(1, 0, 2, 1, [0, 2, 0, 1], [1, 0]) - - - def test_GID(self): - """ - Check UID/GID switches when current effective GID is non-root. - """ - self._testUIDGIDSwitch(0, 1, 0, 0, [], [0, 1]) - self._testUIDGIDSwitch(0, 1, 0, 1, [], []) - self._testUIDGIDSwitch(0, 1, 1, 1, [1, 0], []) - self._testUIDGIDSwitch(0, 1, 1, 2, [1, 0], [2, 1]) - - - def test_UIDGID(self): - """ - Check UID/GID switches when current effective UID/GID is non-root. - """ - self._testUIDGIDSwitch(1, 1, 0, 0, [0, 1], [0, 1]) - self._testUIDGIDSwitch(1, 1, 0, 1, [0, 1], []) - self._testUIDGIDSwitch(1, 1, 1, 0, [0, 1, 0, 1], [0, 1]) - self._testUIDGIDSwitch(1, 1, 1, 1, [], []) - self._testUIDGIDSwitch(1, 1, 2, 1, [0, 2, 0, 1], []) - self._testUIDGIDSwitch(1, 1, 1, 2, [0, 1, 0, 1], [2, 1]) - self._testUIDGIDSwitch(1, 1, 2, 2, [0, 2, 0, 1], [2, 1]) - - - -class UnsignedIDTests(unittest.TestCase): - """ - Tests for L{util.unsignedID} and L{util.setIDFunction}. - """ - def setUp(self): - """ - Save the value of L{util._idFunction} and arrange for it to be restored - after the test runs. - """ - self.addCleanup(setattr, util, '_idFunction', util._idFunction) - - - def test_setIDFunction(self): - """ - L{util.setIDFunction} returns the last value passed to it. - """ - value = object() - previous = util.setIDFunction(value) - result = util.setIDFunction(previous) - self.assertIdentical(value, result) - - - def test_unsignedID(self): - """ - L{util.unsignedID} uses the function passed to L{util.setIDFunction} to - determine the unique integer id of an object and then adjusts it to be - positive if necessary. - """ - foo = object() - bar = object() - - # A fake object identity mapping - objects = {foo: 17, bar: -73} - def fakeId(obj): - return objects[obj] - - util.setIDFunction(fakeId) - - self.assertEqual(util.unsignedID(foo), 17) - self.assertEqual(util.unsignedID(bar), (sys.maxint + 1) * 2 - 73) - - - def test_defaultIDFunction(self): - """ - L{util.unsignedID} uses the built in L{id} by default. - """ - obj = object() - idValue = id(obj) - if idValue < 0: - idValue += (sys.maxint + 1) * 2 - - self.assertEqual(util.unsignedID(obj), idValue) - - - -class InitGroupsTests(unittest.TestCase): - """ - Tests for L{util.initgroups}. - """ - - if pwd is None: - skip = "pwd not available" - - - def setUp(self): - self.addCleanup(setattr, util, "_c_initgroups", util._c_initgroups) - self.addCleanup(setattr, util, "setgroups", util.setgroups) - - - def test_initgroupsForceC(self): - """ - If we fake the presence of the C extension, it's called instead of the - Python implementation. - """ - calls = [] - util._c_initgroups = lambda x, y: calls.append((x, y)) - setgroupsCalls = [] - util.setgroups = calls.append - - util.initgroups(os.getuid(), 4) - self.assertEqual(calls, [(pwd.getpwuid(os.getuid())[0], 4)]) - self.assertFalse(setgroupsCalls) - - - def test_initgroupsForcePython(self): - """ - If we fake the absence of the C extension, the Python implementation is - called instead, calling C{os.setgroups}. - """ - util._c_initgroups = None - calls = [] - util.setgroups = calls.append - util.initgroups(os.getuid(), os.getgid()) - # Something should be in the calls, we don't really care what - self.assertTrue(calls) - - - def test_initgroupsInC(self): - """ - If the C extension is present, it's called instead of the Python - version. We check that by making sure C{os.setgroups} is not called. - """ - calls = [] - util.setgroups = calls.append - try: - util.initgroups(os.getuid(), os.getgid()) - except OSError: - pass - self.assertFalse(calls) - - - if util._c_initgroups is None: - test_initgroupsInC.skip = "C initgroups not available" - - -class DeprecationTests(unittest.TestCase): - """ - Tests for deprecations in C{twisted.python.util}. - """ - def test_getPluginDirs(self): - """ - L{util.getPluginDirs} is deprecated. - """ - util.getPluginDirs() - warnings = self.flushWarnings(offendingFunctions=[ - self.test_getPluginDirs]) - self.assertEqual( - warnings[0]['message'], - "twisted.python.util.getPluginDirs is deprecated since Twisted " - "12.2.") - self.assertEqual(warnings[0]['category'], DeprecationWarning) - self.assertEqual(len(warnings), 1) - - - def test_addPluginDir(self): - """ - L{util.addPluginDir} is deprecated. - """ - util.addPluginDir() - warnings = self.flushWarnings(offendingFunctions=[ - self.test_addPluginDir]) - self.assertEqual( - warnings[0]['message'], - "twisted.python.util.addPluginDir is deprecated since Twisted " - "12.2.") - self.assertEqual(warnings[0]['category'], DeprecationWarning) - self.assertEqual(len(warnings), 1) - - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_versions.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_versions.py deleted file mode 100755 index 79388cfa..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_versions.py +++ /dev/null @@ -1,323 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -import sys -from cStringIO import StringIO - -from twisted.python.versions import getVersionString, IncomparableVersions -from twisted.python.versions import Version, _inf -from twisted.python.filepath import FilePath - -from twisted.trial import unittest - - - -VERSION_4_ENTRIES = """\ -<?xml version="1.0" encoding="utf-8"?> -<wc-entries - xmlns="svn:"> -<entry - committed-rev="18210" - name="" - committed-date="2006-09-21T04:43:09.542953Z" - url="svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk/twisted" - last-author="exarkun" - kind="dir" - uuid="bbbe8e31-12d6-0310-92fd-ac37d47ddeeb" - repos="svn+ssh://svn.twistedmatrix.com/svn/Twisted" - revision="18211"/> -</wc-entries> -""" - - - -VERSION_8_ENTRIES = """\ -8 - -dir -22715 -svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk -""" - - -VERSION_9_ENTRIES = """\ -9 - -dir -22715 -svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk -""" - - -VERSION_10_ENTRIES = """\ -10 - -dir -22715 -svn+ssh://svn.twistedmatrix.com/svn/Twisted/trunk -""" - - -class VersionsTest(unittest.TestCase): - - def test_versionComparison(self): - """ - Versions can be compared for equality and order. - """ - va = Version("dummy", 1, 0, 0) - vb = Version("dummy", 0, 1, 0) - self.failUnless(va > vb) - self.failUnless(vb < va) - self.failUnless(va >= vb) - self.failUnless(vb <= va) - self.failUnless(va != vb) - self.failUnless(vb == Version("dummy", 0, 1, 0)) - self.failUnless(vb == vb) - - # BREAK IT DOWN@!! - self.failIf(va < vb) - self.failIf(vb > va) - self.failIf(va <= vb) - self.failIf(vb >= va) - self.failIf(va == vb) - self.failIf(vb != Version("dummy", 0, 1, 0)) - self.failIf(vb != vb) - - - def test_comparingPrereleasesWithReleases(self): - """ - Prereleases are always less than versions without prereleases. - """ - va = Version("whatever", 1, 0, 0, prerelease=1) - vb = Version("whatever", 1, 0, 0) - self.assertTrue(va < vb) - self.assertFalse(va > vb) - self.assertNotEquals(vb, va) - - - def test_comparingPrereleases(self): - """ - The value specified as the prerelease is used in version comparisons. - """ - va = Version("whatever", 1, 0, 0, prerelease=1) - vb = Version("whatever", 1, 0, 0, prerelease=2) - self.assertTrue(va < vb) - self.assertFalse(va > vb) - self.assertNotEqual(va, vb) - - - def test_infComparison(self): - """ - L{_inf} is equal to L{_inf}. - - This is a regression test. - """ - self.assertEqual(_inf, _inf) - - - def testDontAllowBuggyComparisons(self): - self.assertRaises(IncomparableVersions, - cmp, - Version("dummy", 1, 0, 0), - Version("dumym", 1, 0, 0)) - - - def test_repr(self): - """ - Calling C{repr} on a version returns a human-readable string - representation of the version. - """ - self.assertEqual(repr(Version("dummy", 1, 2, 3)), - "Version('dummy', 1, 2, 3)") - - - def test_reprWithPrerelease(self): - """ - Calling C{repr} on a version with a prerelease returns a human-readable - string representation of the version including the prerelease. - """ - self.assertEqual(repr(Version("dummy", 1, 2, 3, prerelease=4)), - "Version('dummy', 1, 2, 3, prerelease=4)") - - - def test_str(self): - """ - Calling C{str} on a version returns a human-readable string - representation of the version. - """ - self.assertEqual(str(Version("dummy", 1, 2, 3)), - "[dummy, version 1.2.3]") - - - def test_strWithPrerelease(self): - """ - Calling C{str} on a version with a prerelease includes the prerelease. - """ - self.assertEqual(str(Version("dummy", 1, 0, 0, prerelease=1)), - "[dummy, version 1.0.0pre1]") - - - def testShort(self): - self.assertEqual(Version('dummy', 1, 2, 3).short(), '1.2.3') - - - def test_goodSVNEntries_4(self): - """ - Version should be able to parse an SVN format 4 entries file. - """ - version = Version("dummy", 1, 0, 0) - self.assertEqual( - version._parseSVNEntries_4(StringIO(VERSION_4_ENTRIES)), '18211') - - - def test_goodSVNEntries_8(self): - """ - Version should be able to parse an SVN format 8 entries file. - """ - version = Version("dummy", 1, 0, 0) - self.assertEqual( - version._parseSVNEntries_8(StringIO(VERSION_8_ENTRIES)), '22715') - - - def test_goodSVNEntries_9(self): - """ - Version should be able to parse an SVN format 9 entries file. - """ - version = Version("dummy", 1, 0, 0) - self.assertEqual( - version._parseSVNEntries_9(StringIO(VERSION_9_ENTRIES)), '22715') - - - def test_goodSVNEntriesTenPlus(self): - """ - Version should be able to parse an SVN format 10 entries file. - """ - version = Version("dummy", 1, 0, 0) - self.assertEqual( - version._parseSVNEntriesTenPlus(StringIO(VERSION_10_ENTRIES)), '22715') - - - def test_getVersionString(self): - """ - L{getVersionString} returns a string with the package name and the - short version number. - """ - self.assertEqual( - 'Twisted 8.0.0', getVersionString(Version('Twisted', 8, 0, 0))) - - - def test_getVersionStringWithPrerelease(self): - """ - L{getVersionString} includes the prerelease, if any. - """ - self.assertEqual( - getVersionString(Version("whatever", 8, 0, 0, prerelease=1)), - "whatever 8.0.0pre1") - - - def test_base(self): - """ - The L{base} method returns a very simple representation of the version. - """ - self.assertEqual(Version("foo", 1, 0, 0).base(), "1.0.0") - - - def test_baseWithPrerelease(self): - """ - The base version includes 'preX' for versions with prereleases. - """ - self.assertEqual(Version("foo", 1, 0, 0, prerelease=8).base(), - "1.0.0pre8") - - - -class FormatDiscoveryTests(unittest.TestCase): - """ - Tests which discover the parsing method based on the imported module name. - """ - - def setUp(self): - """ - Create a temporary directory with a package structure in it. - """ - self.entry = FilePath(self.mktemp()) - self.preTestModules = sys.modules.copy() - sys.path.append(self.entry.path) - pkg = self.entry.child("twisted_python_versions_package") - pkg.makedirs() - pkg.child("__init__.py").setContent( - "from twisted.python.versions import Version\n" - "version = Version('twisted_python_versions_package', 1, 0, 0)\n") - self.svnEntries = pkg.child(".svn") - self.svnEntries.makedirs() - - - def tearDown(self): - """ - Remove the imported modules and sys.path modifications. - """ - sys.modules.clear() - sys.modules.update(self.preTestModules) - sys.path.remove(self.entry.path) - - - def checkSVNFormat(self, formatVersion, entriesText, expectedRevision): - """ - Check for the given revision being detected after setting the SVN - entries text and format version of the test directory structure. - """ - self.svnEntries.child("format").setContent(formatVersion+"\n") - self.svnEntries.child("entries").setContent(entriesText) - self.assertEqual(self.getVersion()._getSVNVersion(), expectedRevision) - - - def getVersion(self): - """ - Import and retrieve the Version object from our dynamically created - package. - """ - import twisted_python_versions_package - return twisted_python_versions_package.version - - - def test_detectVersion4(self): - """ - Verify that version 4 format file will be properly detected and parsed. - """ - self.checkSVNFormat("4", VERSION_4_ENTRIES, '18211') - - - def test_detectVersion8(self): - """ - Verify that version 8 format files will be properly detected and - parsed. - """ - self.checkSVNFormat("8", VERSION_8_ENTRIES, '22715') - - - def test_detectVersion9(self): - """ - Verify that version 9 format files will be properly detected and - parsed. - """ - self.checkSVNFormat("9", VERSION_9_ENTRIES, '22715') - - - def test_detectVersion10(self): - """ - Verify that version 10 format files will be properly detected and - parsed. - - Differing from previous formats, the version 10 format lacks a - I{format} file and B{only} has the version information on the first - line of the I{entries} file. - """ - self.svnEntries.child("entries").setContent(VERSION_10_ENTRIES) - self.assertEqual(self.getVersion()._getSVNVersion(), '22715') - - - def test_detectUnknownVersion(self): - """ - Verify that a new version of SVN will result in the revision 'Unknown'. - """ - self.checkSVNFormat("some-random-new-version", "ooga booga!", 'Unknown') diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_win32.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_win32.py deleted file mode 100755 index e262ea2b..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_win32.py +++ /dev/null @@ -1,35 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-from twisted.trial import unittest
-from twisted.python.runtime import platform
-from twisted.python.win32 import cmdLineQuote
-
-
-class CommandLineQuotingTests(unittest.TestCase):
- """
- Tests for L{cmdLineQuote}.
- """
-
- def test_argWithoutSpaces(self):
- """
- Calling C{cmdLineQuote} with an argument with no spaces should
- return the argument unchanged.
- """
- self.assertEqual(cmdLineQuote('an_argument'), 'an_argument')
-
-
- def test_argWithSpaces(self):
- """
- Calling C{cmdLineQuote} with an argument containing spaces should
- return the argument surrounded by quotes.
- """
- self.assertEqual(cmdLineQuote('An Argument'), '"An Argument"')
-
-
- def test_emptyStringArg(self):
- """
- Calling C{cmdLineQuote} with an empty string should return a
- quoted empty string.
- """
- self.assertEqual(cmdLineQuote(''), '""')
diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_zipstream.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_zipstream.py deleted file mode 100755 index b9d9a8a5..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_zipstream.py +++ /dev/null @@ -1,367 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for L{twisted.python.zipstream} -""" - -import sys -import random -import zipfile - -from twisted.python.compat import set -from twisted.python import zipstream, filepath -from twisted.python.hashlib import md5 -from twisted.trial import unittest - - -class FileEntryMixin: - """ - File entry classes should behave as file-like objects - """ - def getFileEntry(self, contents): - """ - Return an appropriate zip file entry - """ - filename = self.mktemp() - z = zipfile.ZipFile(filename, 'w', self.compression) - z.writestr('content', contents) - z.close() - z = zipstream.ChunkingZipFile(filename, 'r') - return z.readfile('content') - - - def test_isatty(self): - """ - zip files should not be ttys, so isatty() should be false - """ - self.assertEqual(self.getFileEntry('').isatty(), False) - - - def test_closed(self): - """ - The C{closed} attribute should reflect whether C{close()} has been - called. - """ - fileEntry = self.getFileEntry('') - self.assertEqual(fileEntry.closed, False) - fileEntry.close() - self.assertEqual(fileEntry.closed, True) - - - def test_readline(self): - """ - C{readline()} should mirror L{file.readline} and return up to a single - deliminter. - """ - fileEntry = self.getFileEntry('hoho\nho') - self.assertEqual(fileEntry.readline(), 'hoho\n') - self.assertEqual(fileEntry.readline(), 'ho') - self.assertEqual(fileEntry.readline(), '') - - - def test_next(self): - """ - Zip file entries should implement the iterator protocol as files do. - """ - fileEntry = self.getFileEntry('ho\nhoho') - self.assertEqual(fileEntry.next(), 'ho\n') - self.assertEqual(fileEntry.next(), 'hoho') - self.assertRaises(StopIteration, fileEntry.next) - - - def test_readlines(self): - """ - C{readlines()} should return a list of all the lines. - """ - fileEntry = self.getFileEntry('ho\nho\nho') - self.assertEqual(fileEntry.readlines(), ['ho\n', 'ho\n', 'ho']) - - - def test_iteration(self): - """ - C{__iter__()} and C{xreadlines()} should return C{self}. - """ - fileEntry = self.getFileEntry('') - self.assertIdentical(iter(fileEntry), fileEntry) - self.assertIdentical(fileEntry.xreadlines(), fileEntry) - - - def test_readWhole(self): - """ - C{.read()} should read the entire file. - """ - contents = "Hello, world!" - entry = self.getFileEntry(contents) - self.assertEqual(entry.read(), contents) - - - def test_readPartial(self): - """ - C{.read(num)} should read num bytes from the file. - """ - contents = "0123456789" - entry = self.getFileEntry(contents) - one = entry.read(4) - two = entry.read(200) - self.assertEqual(one, "0123") - self.assertEqual(two, "456789") - - - def test_tell(self): - """ - C{.tell()} should return the number of bytes that have been read so - far. - """ - contents = "x" * 100 - entry = self.getFileEntry(contents) - entry.read(2) - self.assertEqual(entry.tell(), 2) - entry.read(4) - self.assertEqual(entry.tell(), 6) - - - -class DeflatedZipFileEntryTest(FileEntryMixin, unittest.TestCase): - """ - DeflatedZipFileEntry should be file-like - """ - compression = zipfile.ZIP_DEFLATED - - - -class ZipFileEntryTest(FileEntryMixin, unittest.TestCase): - """ - ZipFileEntry should be file-like - """ - compression = zipfile.ZIP_STORED - - - -class ZipstreamTest(unittest.TestCase): - """ - Tests for twisted.python.zipstream - """ - def setUp(self): - """ - Creates junk data that can be compressed and a test directory for any - files that will be created - """ - self.testdir = filepath.FilePath(self.mktemp()) - self.testdir.makedirs() - self.unzipdir = self.testdir.child('unzipped') - self.unzipdir.makedirs() - - - def makeZipFile(self, contents, directory=''): - """ - Makes a zip file archive containing len(contents) files. Contents - should be a list of strings, each string being the content of one file. - """ - zpfilename = self.testdir.child('zipfile.zip').path - zpfile = zipfile.ZipFile(zpfilename, 'w') - for i, content in enumerate(contents): - filename = str(i) - if directory: - filename = directory + "/" + filename - zpfile.writestr(filename, content) - zpfile.close() - return zpfilename - - - def test_invalidMode(self): - """ - A ChunkingZipFile opened in write-mode should not allow .readfile(), - and raise a RuntimeError instead. - """ - czf = zipstream.ChunkingZipFile(self.mktemp(), "w") - self.assertRaises(RuntimeError, czf.readfile, "something") - - - def test_closedArchive(self): - """ - A closed ChunkingZipFile should raise a L{RuntimeError} when - .readfile() is invoked. - """ - czf = zipstream.ChunkingZipFile(self.makeZipFile(["something"]), "r") - czf.close() - self.assertRaises(RuntimeError, czf.readfile, "something") - - - def test_invalidHeader(self): - """ - A zipfile entry with the wrong magic number should raise BadZipfile for - readfile(), but that should not affect other files in the archive. - """ - fn = self.makeZipFile(["test contents", - "more contents"]) - zf = zipfile.ZipFile(fn, "r") - zeroOffset = zf.getinfo("0").header_offset - zf.close() - # Zero out just the one header. - scribble = file(fn, "r+b") - scribble.seek(zeroOffset, 0) - scribble.write(chr(0) * 4) - scribble.close() - czf = zipstream.ChunkingZipFile(fn) - self.assertRaises(zipfile.BadZipfile, czf.readfile, "0") - self.assertEqual(czf.readfile("1").read(), "more contents") - - - def test_filenameMismatch(self): - """ - A zipfile entry with a different filename than is found in the central - directory should raise BadZipfile. - """ - fn = self.makeZipFile(["test contents", - "more contents"]) - zf = zipfile.ZipFile(fn, "r") - info = zf.getinfo("0") - info.filename = "not zero" - zf.close() - scribble = file(fn, "r+b") - scribble.seek(info.header_offset, 0) - scribble.write(info.FileHeader()) - scribble.close() - - czf = zipstream.ChunkingZipFile(fn) - self.assertRaises(zipfile.BadZipfile, czf.readfile, "0") - self.assertEqual(czf.readfile("1").read(), "more contents") - - - if sys.version_info < (2, 5): - # In python 2.4 and earlier, consistency between the directory and the - # file header are verified at archive-opening time. In python 2.5 - # (and, presumably, later) it is readzipfile's responsibility. - message = "Consistency-checking only necessary in 2.5." - test_invalidHeader.skip = message - test_filenameMismatch.skip = message - - - - def test_unsupportedCompression(self): - """ - A zipfile which describes an unsupported compression mechanism should - raise BadZipfile. - """ - fn = self.mktemp() - zf = zipfile.ZipFile(fn, "w") - zi = zipfile.ZipInfo("0") - zf.writestr(zi, "some data") - # Mangle its compression type in the central directory; can't do this - # before the writestr call or zipfile will (correctly) tell us not to - # pass bad compression types :) - zi.compress_type = 1234 - zf.close() - - czf = zipstream.ChunkingZipFile(fn) - self.assertRaises(zipfile.BadZipfile, czf.readfile, "0") - - - def test_extraData(self): - """ - readfile() should skip over 'extra' data present in the zip metadata. - """ - fn = self.mktemp() - zf = zipfile.ZipFile(fn, 'w') - zi = zipfile.ZipInfo("0") - zi.extra = "hello, extra" - zf.writestr(zi, "the real data") - zf.close() - czf = zipstream.ChunkingZipFile(fn) - self.assertEqual(czf.readfile("0").read(), "the real data") - - - def test_unzipIterChunky(self): - """ - L{twisted.python.zipstream.unzipIterChunky} returns an iterator which - must be exhausted to completely unzip the input archive. - """ - numfiles = 10 - contents = ['This is test file %d!' % i for i in range(numfiles)] - zpfilename = self.makeZipFile(contents) - list(zipstream.unzipIterChunky(zpfilename, self.unzipdir.path)) - self.assertEqual( - set(self.unzipdir.listdir()), - set(map(str, range(numfiles)))) - - for child in self.unzipdir.children(): - num = int(child.basename()) - self.assertEqual(child.getContent(), contents[num]) - - - def test_unzipIterChunkyDirectory(self): - """ - The path to which a file is extracted by L{zipstream.unzipIterChunky} - is determined by joining the C{directory} argument to C{unzip} with the - path within the archive of the file being extracted. - """ - numfiles = 10 - contents = ['This is test file %d!' % i for i in range(numfiles)] - zpfilename = self.makeZipFile(contents, 'foo') - list(zipstream.unzipIterChunky(zpfilename, self.unzipdir.path)) - self.assertEqual( - set(self.unzipdir.child('foo').listdir()), - set(map(str, range(numfiles)))) - - for child in self.unzipdir.child('foo').children(): - num = int(child.basename()) - self.assertEqual(child.getContent(), contents[num]) - - - # XXX these tests are kind of gross and old, but I think unzipIterChunky is - # kind of a gross function anyway. We should really write an abstract - # copyTo/moveTo that operates on FilePath and make sure ZipPath can support - # it, then just deprecate / remove this stuff. - def _unzipIterChunkyTest(self, compression, chunksize, lower, upper): - """ - unzipIterChunky should unzip the given number of bytes per iteration. - """ - junk = ' '.join([str(random.random()) for n in xrange(1000)]) - junkmd5 = md5(junk).hexdigest() - - tempdir = filepath.FilePath(self.mktemp()) - tempdir.makedirs() - zfpath = tempdir.child('bigfile.zip').path - self._makebigfile(zfpath, compression, junk) - uziter = zipstream.unzipIterChunky(zfpath, tempdir.path, - chunksize=chunksize) - r = uziter.next() - # test that the number of chunks is in the right ballpark; - # this could theoretically be any number but statistically it - # should always be in this range - approx = lower < r < upper - self.failUnless(approx) - for r in uziter: - pass - self.assertEqual(r, 0) - newmd5 = md5( - tempdir.child("zipstreamjunk").open().read()).hexdigest() - self.assertEqual(newmd5, junkmd5) - - def test_unzipIterChunkyStored(self): - """ - unzipIterChunky should unzip the given number of bytes per iteration on - a stored archive. - """ - self._unzipIterChunkyTest(zipfile.ZIP_STORED, 500, 35, 45) - - - def test_chunkyDeflated(self): - """ - unzipIterChunky should unzip the given number of bytes per iteration on - a deflated archive. - """ - self._unzipIterChunkyTest(zipfile.ZIP_DEFLATED, 972, 23, 27) - - - def _makebigfile(self, filename, compression, junk): - """ - Create a zip file with the given file name and compression scheme. - """ - zf = zipfile.ZipFile(filename, 'w', compression) - for i in range(10): - fn = 'zipstream%d' % i - zf.writestr(fn, "") - zf.writestr('zipstreamjunk', junk) - zf.close() diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_zshcomp.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_zshcomp.py deleted file mode 100755 index 13865b21..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/python/test/test_zshcomp.py +++ /dev/null @@ -1,228 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Test cases for twisted.python.zshcomp -""" -import os -import os.path -from cStringIO import StringIO - -from twisted.trial import unittest -from twisted.python import zshcomp, usage - - - -class ZshcompTestCase(unittest.TestCase): - """ - Tests for the zsh completion function builder in twisted/python/zshcomp.py - """ - def test_buildAll(self): - """ - Build all the completion functions for twisted commands - no errors - should be raised - """ - dirname = self.mktemp() - os.mkdir(dirname) - skippedCmds = [x[0] for x in zshcomp.makeCompFunctionFiles(dirname)] - - # verify a zsh function was created for each twisted command - for info in zshcomp.generateFor: - if info[0] in skippedCmds: - continue - funcPath = os.path.join(dirname, '_' + info[0]) - self.assertTrue(os.path.exists(funcPath)) - - - def test_accumulateMetadata(self): - """ - The zsh_* variables you can place on Options classes are - picked up correctly? - """ - opts = FighterAceExtendedOptions() - ag = zshcomp.ArgumentsGenerator('dummy_cmd', opts, 'dummy_value') - - altArgDescr = FighterAceOptions.zsh_altArgDescr.copy() - altArgDescr.update(FighterAceExtendedOptions.zsh_altArgDescr) - - actionDescr = FighterAceOptions.zsh_actionDescr.copy() - actionDescr.update(FighterAceExtendedOptions.zsh_actionDescr) - - self.assertEqual(ag.altArgDescr, altArgDescr) - self.assertEqual(ag.actionDescr, actionDescr) - self.assertEqual(ag.multiUse, FighterAceOptions.zsh_multiUse) - self.assertEqual(ag.mutuallyExclusive, - FighterAceOptions.zsh_mutuallyExclusive) - self.assertEqual(ag.actions, FighterAceOptions.zsh_actions) - self.assertEqual(ag.extras, FighterAceOptions.zsh_extras) - - - def test_accumulateAdditionalOptions(self): - """ - We pick up options that are only defined by having an - appropriately named method on your Options class, - e.g. def opt_foo(self, foo) - """ - opts = FighterAceExtendedOptions() - ag = zshcomp.ArgumentsGenerator('dummy_cmd', opts, 'dummy_value') - - self.assertIn('nocrash', ag.optFlags_d) - self.assertIn('nocrash', ag.optAll_d) - - self.assertIn('difficulty', ag.optParams_d) - self.assertIn('difficulty', ag.optAll_d) - - - def test_verifyZshNames(self): - """ - Using a parameter/flag name that doesn't exist - will raise an error - """ - class TmpOptions(FighterAceExtendedOptions): - zsh_actions = {'detaill' : 'foo'} # Note typo of detail - - opts = TmpOptions() - self.assertRaises(ValueError, zshcomp.ArgumentsGenerator, - 'dummy_cmd', opts, 'dummy_value') - - - def test_zshCode(self): - """ - Generate a completion function, and test the textual output - against a known correct output - """ - cmd_name = 'testprog' - opts = SillyOptions() - f = StringIO() - b = zshcomp.Builder(cmd_name, opts, f) - b.write() - f.reset() - self.assertEqual(f.read(), testOutput1) - - - def test_skipBuild(self): - """ - makeCompFunctionFiles skips building for commands whos - script module cannot be imported - """ - generateFor = [('test_cmd', 'no.way.your.gonna.import.this', 'Foo')] - skips = zshcomp.makeCompFunctionFiles('out_dir', generateFor, {}) - # no exceptions should be raised. hooray. - self.assertEqual(len(skips), 1) - self.assertEqual(len(skips[0]), 2) - self.assertEqual(skips[0][0], 'test_cmd') - self.assertTrue(isinstance(skips[0][1], ImportError)) - - - -class FighterAceOptions(usage.Options): - """ - Command-line options for an imaginary "Fighter Ace" game - """ - optFlags = [['fokker', 'f', - 'Select the Fokker Dr.I as your dogfighter aircraft'], - ['albatros', 'a', - 'Select the Albatros D-III as your dogfighter aircraft'], - ['spad', 's', - 'Select the SPAD S.VII as your dogfighter aircraft'], - ['bristol', 'b', - 'Select the Bristol Scout as your dogfighter aircraft'], - ['physics', 'p', - 'Enable secret Twisted physics engine'], - ['jam', 'j', - 'Enable a small chance that your machine guns will jam!'], - ['verbose', 'v', - 'Verbose logging (may be specified more than once)'], - ] - - optParameters = [['pilot-name', None, "What's your name, Ace?", - 'Manfred von Richthofen'], - ['detail', 'd', - 'Select the level of rendering detail (1-5)', '3'], - ] - - zsh_altArgDescr = {'physics' : 'Twisted-Physics', - 'detail' : 'Rendering detail level'} - zsh_actionDescr = {'detail' : 'Pick your detail'} - zsh_multiUse = ['verbose'] - zsh_mutuallyExclusive = [['fokker', 'albatros', 'spad', 'bristol']] - zsh_actions = {'detail' : '(1 2 3 4 5)'} - zsh_extras = [':saved game file to load:_files'] - - - -class FighterAceExtendedOptions(FighterAceOptions): - """ - Extend the options and zsh metadata provided by FighterAceOptions. zshcomp - must accumulate options and metadata from all classes in the hiearchy so - this is important for testing - """ - optFlags = [['no-stalls', None, - 'Turn off the ability to stall your aircraft']] - optParameters = [['reality-level', None, - 'Select the level of physics reality (1-5)', '5']] - - zsh_altArgDescr = {'no-stalls' : 'Can\'t stall your plane'} - zsh_actionDescr = {'reality-level' : 'Physics reality level'} - - - def opt_nocrash(self): - """Select that you can't crash your plane""" - - - def opt_difficulty(self, difficulty): - """How tough are you? (1-10)""" - - - -def _accuracyAction(): - return '(1 2 3)' - - - -class SillyOptions(usage.Options): - """ - Command-line options for a "silly" program - """ - optFlags = [['color', 'c', 'Turn on color output'], - ['gray', 'g', 'Turn on gray-scale output'], - ['verbose', 'v', - 'Verbose logging (may be specified more than once)'], - ] - - optParameters = [['optimization', None, - 'Select the level of optimization (1-5)', '5'], - ['accuracy', 'a', - 'Select the level of accuracy (1-3)', '3'], - ] - - - zsh_altArgDescr = {'color' : 'Color on', - 'optimization' : 'Optimization level'} - zsh_actionDescr = {'optimization' : 'Optimization?', - 'accuracy' : 'Accuracy?'} - zsh_multiUse = ['verbose'] - zsh_mutuallyExclusive = [['color', 'gray']] - zsh_actions = {'optimization' : '(1 2 3 4 5)', - 'accuracy' : _accuracyAction} - zsh_extras = [':output file:_files'] - - - -testOutput1 = """#compdef testprog -_arguments -s -A "-*" \\ -':output file:_files' \\ -'(--accuracy)-a[3]:Accuracy?:(1 2 3)' \\ -'(-a)--accuracy=[3]:Accuracy?:(1 2 3)' \\ -'(--gray -g --color)-c[Color on]' \\ -'(--gray -g -c)--color[Color on]' \\ -'(--color -c --gray)-g[Turn on gray-scale output]' \\ -'(--color -c -g)--gray[Turn on gray-scale output]' \\ -'--help[Display this help and exit.]' \\ -'--optimization=[Optimization level]:Optimization?:(1 2 3 4 5)' \\ -'*-v[Verbose logging (may be specified more than once)]' \\ -'*--verbose[Verbose logging (may be specified more than once)]' \\ -'--version[Display Twisted version and exit.]' \\ -&& return 0 -""" - |