diff options
Diffstat (limited to 'lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test')
34 files changed, 0 insertions, 9660 deletions
diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/__init__.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/__init__.py deleted file mode 100755 index e2395372..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""unittesting framework tests""" diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/detests.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/detests.py deleted file mode 100755 index cc08821f..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/detests.py +++ /dev/null @@ -1,201 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for Deferred handling by L{twisted.trial.unittest.TestCase}. -""" - -from twisted.trial import unittest -from twisted.internet import defer, threads, reactor - - -class DeferredSetUpOK(unittest.TestCase): - def setUp(self): - d = defer.succeed('value') - d.addCallback(self._cb_setUpCalled) - return d - - def _cb_setUpCalled(self, ignored): - self._setUpCalled = True - - def test_ok(self): - self.failUnless(self._setUpCalled) - - -class DeferredSetUpFail(unittest.TestCase): - testCalled = False - - def setUp(self): - return defer.fail(unittest.FailTest('i fail')) - - def test_ok(self): - DeferredSetUpFail.testCalled = True - self.fail("I should not get called") - - -class DeferredSetUpCallbackFail(unittest.TestCase): - testCalled = False - - def setUp(self): - d = defer.succeed('value') - d.addCallback(self._cb_setUpCalled) - return d - - def _cb_setUpCalled(self, ignored): - self.fail('deliberate failure') - - def test_ok(self): - DeferredSetUpCallbackFail.testCalled = True - - -class DeferredSetUpError(unittest.TestCase): - testCalled = False - - def setUp(self): - return defer.fail(RuntimeError('deliberate error')) - - def test_ok(self): - DeferredSetUpError.testCalled = True - - -class DeferredSetUpNeverFire(unittest.TestCase): - testCalled = False - - def setUp(self): - return defer.Deferred() - - def test_ok(self): - DeferredSetUpNeverFire.testCalled = True - - -class DeferredSetUpSkip(unittest.TestCase): - testCalled = False - - def setUp(self): - d = defer.succeed('value') - d.addCallback(self._cb1) - return d - - def _cb1(self, ignored): - raise unittest.SkipTest("skip me") - - def test_ok(self): - DeferredSetUpSkip.testCalled = True - - -class DeferredTests(unittest.TestCase): - touched = False - - def _cb_fail(self, reason): - self.fail(reason) - - def _cb_error(self, reason): - raise RuntimeError(reason) - - def _cb_skip(self, reason): - raise unittest.SkipTest(reason) - - def _touchClass(self, ignored): - self.__class__.touched = True - - def setUp(self): - self.__class__.touched = False - - def test_pass(self): - return defer.succeed('success') - - def test_passGenerated(self): - self._touchClass(None) - yield None - test_passGenerated = defer.deferredGenerator(test_passGenerated) - - def test_fail(self): - return defer.fail(self.failureException('I fail')) - - def test_failureInCallback(self): - d = defer.succeed('fail') - d.addCallback(self._cb_fail) - return d - - def test_errorInCallback(self): - d = defer.succeed('error') - d.addCallback(self._cb_error) - return d - - def test_skip(self): - d = defer.succeed('skip') - d.addCallback(self._cb_skip) - d.addCallback(self._touchClass) - return d - - def test_thread(self): - return threads.deferToThread(lambda : None) - - def test_expectedFailure(self): - d = defer.succeed('todo') - d.addCallback(self._cb_error) - return d - test_expectedFailure.todo = "Expected failure" - - -class TimeoutTests(unittest.TestCase): - timedOut = None - - def test_pass(self): - d = defer.Deferred() - reactor.callLater(0, d.callback, 'hoorj!') - return d - test_pass.timeout = 2 - - def test_passDefault(self): - # test default timeout - d = defer.Deferred() - reactor.callLater(0, d.callback, 'hoorj!') - return d - - def test_timeout(self): - return defer.Deferred() - test_timeout.timeout = 0.1 - - def test_timeoutZero(self): - return defer.Deferred() - test_timeoutZero.timeout = 0 - - def test_expectedFailure(self): - return defer.Deferred() - test_expectedFailure.timeout = 0.1 - test_expectedFailure.todo = "i will get it right, eventually" - - def test_skip(self): - return defer.Deferred() - test_skip.timeout = 0.1 - test_skip.skip = "i will get it right, eventually" - - def test_errorPropagation(self): - def timedOut(err): - self.__class__.timedOut = err - return err - d = defer.Deferred() - d.addErrback(timedOut) - return d - test_errorPropagation.timeout = 0.1 - - def test_calledButNeverCallback(self): - d = defer.Deferred() - def neverFire(r): - return defer.Deferred() - d.addCallback(neverFire) - d.callback(1) - return d - test_calledButNeverCallback.timeout = 0.1 - - -class TestClassTimeoutAttribute(unittest.TestCase): - timeout = 0.2 - - def setUp(self): - self.d = defer.Deferred() - - def testMethod(self): - self.methodCalled = True - return self.d diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/erroneous.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/erroneous.py deleted file mode 100755 index 6c0f8408..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/erroneous.py +++ /dev/null @@ -1,167 +0,0 @@ -# -*- test-case-name: twisted.trial.test.test_tests -*- -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Definitions of test cases with various interesting error-related behaviors, to -be used by test modules to exercise different features of trial's test runner. - -See the L{twisted.trial.test.test_tests} module docstring for details about how -this code is arranged. -""" - -from __future__ import division - -from twisted.trial import unittest, util -from twisted.internet import reactor, protocol, defer - - -class FoolishError(Exception): - pass - - - -class FailureInSetUpMixin(object): - def setUp(self): - raise FoolishError, "I am a broken setUp method" - - def test_noop(self): - pass - - - -class SynchronousTestFailureInSetUp( - FailureInSetUpMixin, unittest.SynchronousTestCase): - pass - - - -class AsynchronousTestFailureInSetUp( - FailureInSetUpMixin, unittest.TestCase): - pass - - - -class FailureInTearDownMixin(object): - def tearDown(self): - raise FoolishError, "I am a broken tearDown method" - - def test_noop(self): - pass - - - -class SynchronousTestFailureInTearDown( - FailureInTearDownMixin, unittest.SynchronousTestCase): - pass - - - -class AsynchronousTestFailureInTearDown( - FailureInTearDownMixin, unittest.TestCase): - pass - - - -class TestRegularFail(unittest.SynchronousTestCase): - def test_fail(self): - self.fail("I fail") - - def test_subfail(self): - self.subroutine() - - def subroutine(self): - self.fail("I fail inside") - -class TestFailureInDeferredChain(unittest.TestCase): - def test_fail(self): - d = defer.Deferred() - d.addCallback(self._later) - reactor.callLater(0, d.callback, None) - return d - def _later(self, res): - self.fail("I fail later") - - - -class ErrorTest(unittest.SynchronousTestCase): - """ - A test case which has a L{test_foo} which will raise an error. - - @ivar ran: boolean indicating whether L{test_foo} has been run. - """ - ran = False - - def test_foo(self): - """ - Set C{self.ran} to True and raise a C{ZeroDivisionError} - """ - self.ran = True - 1/0 - - - -class TestSkipTestCase(unittest.SynchronousTestCase): - pass - -TestSkipTestCase.skip = "skipping this test" - - -class DelayedCall(unittest.TestCase): - hiddenExceptionMsg = "something blew up" - - def go(self): - raise RuntimeError(self.hiddenExceptionMsg) - - def testHiddenException(self): - """ - What happens if an error is raised in a DelayedCall and an error is - also raised in the test? - - L{test_reporter.TestErrorReporting.testHiddenException} checks that - both errors get reported. - - Note that this behaviour is deprecated. A B{real} test would return a - Deferred that got triggered by the callLater. This would guarantee the - delayed call error gets reported. - """ - reactor.callLater(0, self.go) - reactor.iterate(0.01) - self.fail("Deliberate failure to mask the hidden exception") - testHiddenException.suppress = [util.suppress( - message=r'reactor\.iterate cannot be used.*', - category=DeprecationWarning)] - - -class ReactorCleanupTests(unittest.TestCase): - def test_leftoverPendingCalls(self): - def _(): - print 'foo!' - reactor.callLater(10000.0, _) - -class SocketOpenTest(unittest.TestCase): - def test_socketsLeftOpen(self): - f = protocol.Factory() - f.protocol = protocol.Protocol - reactor.listenTCP(0, f) - -class TimingOutDeferred(unittest.TestCase): - def test_alpha(self): - pass - - def test_deferredThatNeverFires(self): - self.methodCalled = True - d = defer.Deferred() - return d - - def test_omega(self): - pass - - -def unexpectedException(self): - """i will raise an unexpected exception... - ... *CAUSE THAT'S THE KINDA GUY I AM* - - >>> 1/0 - """ - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite.py deleted file mode 100755 index 89ad1629..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) 2006 Twisted Matrix Laboratories. See LICENSE for details - -""" -Mock test module that contains a C{test_suite} method. L{runner.TestLoader} -should load the tests from the C{test_suite}, not from the C{Foo} C{TestCase}. - -See {twisted.trial.test.test_loader.LoaderTest.test_loadModuleWith_test_suite}. -""" - - -from twisted.trial import unittest, runner - -class Foo(unittest.TestCase): - def test_foo(self): - pass - - -def test_suite(): - ts = runner.TestSuite() - ts.name = "MyCustomSuite" - return ts diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite2.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite2.py deleted file mode 100755 index 6d05457e..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite2.py +++ /dev/null @@ -1,21 +0,0 @@ -# Copyright (c) 2006 Twisted Matrix Laboratories. See LICENSE for details - -""" -Mock test module that contains a C{testSuite} method. L{runner.TestLoader} -should load the tests from the C{testSuite}, not from the C{Foo} C{TestCase}. - -See L{twisted.trial.test.test_loader.LoaderTest.test_loadModuleWith_testSuite}. -""" - - -from twisted.trial import unittest, runner - -class Foo(unittest.TestCase): - def test_foo(self): - pass - - -def testSuite(): - ts = runner.TestSuite() - ts.name = "MyCustomSuite" - return ts diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite3.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite3.py deleted file mode 100755 index c5b89d47..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite3.py +++ /dev/null @@ -1,28 +0,0 @@ -# Copyright (c) 2006 Twisted Matrix Laboratories. See LICENSE for details - -""" -Mock test module that contains both a C{test_suite} and a C{testSuite} method. -L{runner.TestLoader} should load the tests from the C{testSuite}, not from the -C{Foo} C{TestCase} nor from the C{test_suite} method. - -See {twisted.trial.test.test_loader.LoaderTest.test_loadModuleWithBothCustom}. -""" - - -from twisted.trial import unittest, runner - -class Foo(unittest.TestCase): - def test_foo(self): - pass - - -def test_suite(): - ts = runner.TestSuite() - ts.name = "test_suite" - return ts - - -def testSuite(): - ts = runner.TestSuite() - ts.name = "testSuite" - return ts diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockdoctest.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockdoctest.py deleted file mode 100755 index 85beaddd..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockdoctest.py +++ /dev/null @@ -1,104 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -# this module is a trivial class with doctests and a __test__ attribute -# to test trial's doctest support with python2.4 -from __future__ import division - -class Counter(object): - """a simple counter object for testing trial's doctest support - - >>> c = Counter() - >>> c.value() - 0 - >>> c += 3 - >>> c.value() - 3 - >>> c.incr() - >>> c.value() == 4 - True - >>> c == 4 - True - >>> c != 9 - True - - """ - _count = 0 - - def __init__(self, initialValue=0, maxval=None): - self._count = initialValue - self.maxval = maxval - - def __iadd__(self, other): - """add other to my value and return self - - >>> c = Counter(100) - >>> c += 333 - >>> c == 433 - True - """ - if self.maxval is not None and ((self._count + other) > self.maxval): - raise ValueError, "sorry, counter got too big" - else: - self._count += other - return self - - def __eq__(self, other): - """equality operator, compare other to my value() - - >>> c = Counter() - >>> c == 0 - True - >>> c += 10 - >>> c.incr() - >>> c == 10 # fail this test on purpose - True - - """ - return self._count == other - - def __ne__(self, other): - """inequality operator - - >>> c = Counter() - >>> c != 10 - True - """ - return not self.__eq__(other) - - def incr(self): - """increment my value by 1 - - >>> from twisted.trial.test.mockdoctest import Counter - >>> c = Counter(10, 11) - >>> c.incr() - >>> c.value() == 11 - True - >>> c.incr() - Traceback (most recent call last): - File "<stdin>", line 1, in ? - File "twisted/trial/test/mockdoctest.py", line 51, in incr - self.__iadd__(1) - File "twisted/trial/test/mockdoctest.py", line 39, in __iadd__ - raise ValueError, "sorry, counter got too big" - ValueError: sorry, counter got too big - """ - self.__iadd__(1) - - def value(self): - """return this counter's value - - >>> c = Counter(555) - >>> c.value() == 555 - True - """ - return self._count - - def unexpectedException(self): - """i will raise an unexpected exception... - ... *CAUSE THAT'S THE KINDA GUY I AM* - - >>> 1/0 - """ - - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/moduleself.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/moduleself.py deleted file mode 100755 index 1f87c823..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/moduleself.py +++ /dev/null @@ -1,7 +0,0 @@ -# -*- test-case-name: twisted.trial.test.moduleself -*- -from twisted.trial import unittest - -class Foo(unittest.TestCase): - - def testFoo(self): - pass diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/moduletest.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/moduletest.py deleted file mode 100755 index c5e1d701..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/moduletest.py +++ /dev/null @@ -1,11 +0,0 @@ -# -*- test-case-name: twisted.trial.test.test_test_visitor -*- - -# fodder for test_script, which parses files for emacs local variable -# declarations. This one is supposed to have: -# test-case-name: twisted.trial.test.test_test_visitor. -# in the first line -# The class declaration is irrelevant - -class Foo(object): - pass - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/notpython b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/notpython deleted file mode 100644 index 311485ce..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/notpython +++ /dev/null @@ -1,2 +0,0 @@ - -this isn't python diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/novars.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/novars.py deleted file mode 100755 index 93bc03df..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/novars.py +++ /dev/null @@ -1,6 +0,0 @@ -# fodder for test_script, which parses files for emacs local variable -# declarations. This one is supposed to have none. -# The class declaration is irrelevant - -class Bar(object): - pass diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/packages.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/packages.py deleted file mode 100755 index 7a183645..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/packages.py +++ /dev/null @@ -1,156 +0,0 @@ -import sys, os -from twisted.trial import unittest - -testModule = """ -from twisted.trial import unittest - -class FooTest(unittest.TestCase): - def testFoo(self): - pass -""" - -dosModule = testModule.replace('\n', '\r\n') - - -testSample = """ -'''This module is used by test_loader to test the Trial test loading -functionality. Do NOT change the number of tests in this module. -Do NOT change the names the tests in this module. -''' - -import unittest as pyunit -from twisted.trial import unittest - -class FooTest(unittest.TestCase): - def test_foo(self): - pass - - def test_bar(self): - pass - - -class PyunitTest(pyunit.TestCase): - def test_foo(self): - pass - - def test_bar(self): - pass - - -class NotATest(object): - def test_foo(self): - pass - - -class AlphabetTest(unittest.TestCase): - def test_a(self): - pass - - def test_b(self): - pass - - def test_c(self): - pass -""" - -testInheritanceSample = """ -'''This module is used by test_loader to test the Trial test loading -functionality. Do NOT change the number of tests in this module. -Do NOT change the names the tests in this module. -''' - -from twisted.trial import unittest - -class X(object): - - def test_foo(self): - pass - -class A(unittest.TestCase, X): - pass - -class B(unittest.TestCase, X): - pass - -""" - -class PackageTest(unittest.TestCase): - files = [ - ('badpackage/__init__.py', 'frotz\n'), - ('badpackage/test_module.py', ''), - ('package2/__init__.py', ''), - ('package2/test_module.py', 'import frotz\n'), - ('package/__init__.py', ''), - ('package/frotz.py', 'frotz\n'), - ('package/test_bad_module.py', - 'raise ZeroDivisionError("fake error")'), - ('package/test_dos_module.py', dosModule), - ('package/test_import_module.py', 'import frotz'), - ('package/test_module.py', testModule), - ('goodpackage/__init__.py', ''), - ('goodpackage/test_sample.py', testSample), - ('goodpackage/sub/__init__.py', ''), - ('goodpackage/sub/test_sample.py', testSample), - ('inheritancepackage/__init__.py', ''), - ('inheritancepackage/test_x.py', testInheritanceSample), - ] - - def _toModuleName(self, filename): - name = os.path.splitext(filename)[0] - segs = name.split('/') - if segs[-1] == '__init__': - segs = segs[:-1] - return '.'.join(segs) - - def getModules(self): - return map(self._toModuleName, zip(*self.files)[0]) - - def cleanUpModules(self): - modules = self.getModules() - modules.sort() - modules.reverse() - for module in modules: - try: - del sys.modules[module] - except KeyError: - pass - - def createFiles(self, files, parentDir='.'): - for filename, contents in self.files: - filename = os.path.join(parentDir, filename) - self._createDirectory(filename) - fd = open(filename, 'w') - fd.write(contents) - fd.close() - - def _createDirectory(self, filename): - directory = os.path.dirname(filename) - if not os.path.exists(directory): - os.makedirs(directory) - - def setUp(self, parentDir=None): - if parentDir is None: - parentDir = self.mktemp() - self.parent = parentDir - self.createFiles(self.files, parentDir) - - def tearDown(self): - self.cleanUpModules() - -class SysPathManglingTest(PackageTest): - def setUp(self, parent=None): - self.oldPath = sys.path[:] - self.newPath = sys.path[:] - if parent is None: - parent = self.mktemp() - PackageTest.setUp(self, parent) - self.newPath.append(self.parent) - self.mangleSysPath(self.newPath) - - def tearDown(self): - PackageTest.tearDown(self) - self.mangleSysPath(self.oldPath) - - def mangleSysPath(self, pathVar): - sys.path[:] = pathVar - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/sample.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/sample.py deleted file mode 100755 index d8644197..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/sample.py +++ /dev/null @@ -1,108 +0,0 @@ -"""This module is used by test_loader to test the Trial test loading -functionality. Do NOT change the number of tests in this module. Do NOT change -the names the tests in this module. -""" - -import unittest as pyunit -from twisted.trial import unittest -from twisted.python.util import mergeFunctionMetadata - - - -class FooTest(unittest.TestCase): - - - def test_foo(self): - pass - - - def test_bar(self): - pass - - - -def badDecorator(fn): - """ - Decorate a function without preserving the name of the original function. - Always return a function with the same name. - """ - def nameCollision(*args, **kwargs): - return fn(*args, **kwargs) - return nameCollision - - - -def goodDecorator(fn): - """ - Decorate a function and preserve the original name. - """ - def nameCollision(*args, **kwargs): - return fn(*args, **kwargs) - return mergeFunctionMetadata(fn, nameCollision) - - - -class DecorationTest(unittest.TestCase): - def test_badDecorator(self): - """ - This test method is decorated in a way that gives it a confusing name - that collides with another method. - """ - test_badDecorator = badDecorator(test_badDecorator) - - - def test_goodDecorator(self): - """ - This test method is decorated in a way that preserves its name. - """ - test_goodDecorator = goodDecorator(test_goodDecorator) - - - def renamedDecorator(self): - """ - This is secretly a test method and will be decorated and then renamed so - test discovery can find it. - """ - test_renamedDecorator = goodDecorator(renamedDecorator) - - - def nameCollision(self): - """ - This isn't a test, it's just here to collide with tests. - """ - - - -class PyunitTest(pyunit.TestCase): - - - def test_foo(self): - pass - - - def test_bar(self): - pass - - - -class NotATest(object): - - - def test_foo(self): - pass - - - -class AlphabetTest(unittest.TestCase): - - - def test_a(self): - pass - - - def test_b(self): - pass - - - def test_c(self): - pass diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/scripttest.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/scripttest.py deleted file mode 100755 index 267c1892..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/scripttest.py +++ /dev/null @@ -1,14 +0,0 @@ -#!/usr/bin/env python -# -*- test-case-name: twisted.trial.test.test_test_visitor,twisted.trial.test.test_class -*- - -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -# fodder for test_script, which parses files for emacs local variable -# declarations. This one is supposed to have: -# test-case-name: twisted.trial.test.test_test_visitor -# in the second line -# The class declaration is irrelevant - -class Foo(object): - pass diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/skipping.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/skipping.py deleted file mode 100755 index 66a075c2..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/skipping.py +++ /dev/null @@ -1,268 +0,0 @@ -# -*- test-case-name: twisted.trial.test.test_tests -*- -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Definitions of test cases with various interesting behaviors, to be used by -L{twisted.trial.test.test_tests} and other test modules to exercise different -features of trial's test runner. - -See the L{twisted.trial.test.test_tests} module docstring for details about how -this code is arranged. -""" - -from twisted.trial.unittest import ( - SynchronousTestCase, TestCase, SkipTest, FailTest) - - -class SkippingMixin(object): - def test_skip1(self): - raise SkipTest('skip1') - - def test_skip2(self): - raise RuntimeError("I should not get raised") - test_skip2.skip = 'skip2' - - def test_skip3(self): - self.fail('I should not fail') - test_skip3.skip = 'skip3' - - - -class SynchronousSkipping(SkippingMixin, SynchronousTestCase): - pass - - - -class AsynchronousSkipping(SkippingMixin, TestCase): - pass - - - -class SkippingSetUpMixin(object): - def setUp(self): - raise SkipTest('skipSetUp') - - def test_1(self): - pass - - def test_2(self): - pass - - -class SynchronousSkippingSetUp(SkippingSetUpMixin, SynchronousTestCase): - pass - - - -class AsynchronousSkippingSetUp(SkippingSetUpMixin, TestCase): - pass - - - -class DeprecatedReasonlessSkipMixin(object): - def test_1(self): - raise SkipTest() - - - -class SynchronousDeprecatedReasonlessSkip( - DeprecatedReasonlessSkipMixin, SynchronousTestCase): - pass - - - -class AsynchronousDeprecatedReasonlessSkip( - DeprecatedReasonlessSkipMixin, TestCase): - pass - - - -class SkippedClassMixin(object): - skip = 'class' - def setUp(self): - self.__class__._setUpRan = True - def test_skip1(self): - raise SkipTest('skip1') - def test_skip2(self): - raise RuntimeError("Ought to skip me") - test_skip2.skip = 'skip2' - def test_skip3(self): - pass - def test_skip4(self): - raise RuntimeError("Skip me too") - - - -class SynchronousSkippedClass(SkippedClassMixin, SynchronousTestCase): - pass - - - -class AsynchronousSkippedClass(SkippedClassMixin, TestCase): - pass - - - -class TodoMixin(object): - def test_todo1(self): - self.fail("deliberate failure") - test_todo1.todo = "todo1" - - def test_todo2(self): - raise RuntimeError("deliberate error") - test_todo2.todo = "todo2" - - def test_todo3(self): - """unexpected success""" - test_todo3.todo = 'todo3' - - - - -class SynchronousTodo(TodoMixin, SynchronousTestCase): - pass - - - -class AsynchronousTodo(TodoMixin, TestCase): - pass - - - -class SetUpTodoMixin(object): - def setUp(self): - raise RuntimeError("deliberate error") - - def test_todo1(self): - pass - test_todo1.todo = "setUp todo1" - - - -class SynchronousSetUpTodo(SetUpTodoMixin, SynchronousTestCase): - pass - - - -class AsynchronousSetUpTodo(SetUpTodoMixin, TestCase): - pass - - - -class TearDownTodoMixin(object): - def tearDown(self): - raise RuntimeError("deliberate error") - - def test_todo1(self): - pass - test_todo1.todo = "tearDown todo1" - - - -class SynchronousTearDownTodo(TearDownTodoMixin, SynchronousTestCase): - pass - - - -class AsynchronousTearDownTodo(TearDownTodoMixin, TestCase): - pass - - - -class TodoClassMixin(object): - todo = "class" - def test_todo1(self): - pass - test_todo1.todo = "method" - def test_todo2(self): - pass - def test_todo3(self): - self.fail("Deliberate Failure") - test_todo3.todo = "method" - def test_todo4(self): - self.fail("Deliberate Failure") - - - -class SynchronousTodoClass(TodoClassMixin, SynchronousTestCase): - pass - - - -class AsynchronousTodoClass(TodoClassMixin, TestCase): - pass - - - -class StrictTodoMixin(object): - def test_todo1(self): - raise RuntimeError("expected failure") - test_todo1.todo = (RuntimeError, "todo1") - - def test_todo2(self): - raise RuntimeError("expected failure") - test_todo2.todo = ((RuntimeError, OSError), "todo2") - - def test_todo3(self): - raise RuntimeError("we had no idea!") - test_todo3.todo = (OSError, "todo3") - - def test_todo4(self): - raise RuntimeError("we had no idea!") - test_todo4.todo = ((OSError, SyntaxError), "todo4") - - def test_todo5(self): - self.fail("deliberate failure") - test_todo5.todo = (FailTest, "todo5") - - def test_todo6(self): - self.fail("deliberate failure") - test_todo6.todo = (RuntimeError, "todo6") - - def test_todo7(self): - pass - test_todo7.todo = (RuntimeError, "todo7") - - - -class SynchronousStrictTodo(StrictTodoMixin, SynchronousTestCase): - pass - - - -class AsynchronousStrictTodo(StrictTodoMixin, TestCase): - pass - - - -class AddCleanupMixin(object): - def setUp(self): - self.log = ['setUp'] - - def brokenSetUp(self): - self.log = ['setUp'] - raise RuntimeError("Deliberate failure") - - def skippingSetUp(self): - self.log = ['setUp'] - raise SkipTest("Don't do this") - - def append(self, thing): - self.log.append(thing) - - def tearDown(self): - self.log.append('tearDown') - - def runTest(self): - self.log.append('runTest') - - - -class SynchronousAddCleanup(AddCleanupMixin, SynchronousTestCase): - pass - - - -class AsynchronousAddCleanup(AddCleanupMixin, TestCase): - pass diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/suppression.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/suppression.py deleted file mode 100755 index 2b87afcd..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/suppression.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- test-case-name: twisted.trial.test.test_tests -*- -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Test cases used to make sure that warning supression works at the module, -method, and class levels. - -See the L{twisted.trial.test.test_tests} module docstring for details about how -this code is arranged. -""" - -import warnings - -from twisted.trial import unittest, util - - - -METHOD_WARNING_MSG = "method warning message" -CLASS_WARNING_MSG = "class warning message" -MODULE_WARNING_MSG = "module warning message" - -class MethodWarning(Warning): - pass - -class ClassWarning(Warning): - pass - -class ModuleWarning(Warning): - pass - -class EmitMixin: - def _emit(self): - warnings.warn(METHOD_WARNING_MSG, MethodWarning) - warnings.warn(CLASS_WARNING_MSG, ClassWarning) - warnings.warn(MODULE_WARNING_MSG, ModuleWarning) - - -class SuppressionMixin(EmitMixin): - suppress = [util.suppress(message=CLASS_WARNING_MSG)] - - def testSuppressMethod(self): - self._emit() - testSuppressMethod.suppress = [util.suppress(message=METHOD_WARNING_MSG)] - - def testSuppressClass(self): - self._emit() - - def testOverrideSuppressClass(self): - self._emit() - testOverrideSuppressClass.suppress = [] - - - -class SynchronousTestSuppression(SuppressionMixin, unittest.SynchronousTestCase): - pass - - - -class AsynchronousTestSuppression(SuppressionMixin, unittest.TestCase): - pass - - - -class SetUpSuppressionMixin(object): - def setUp(self): - self._emit() - - - -class SynchronousTestSetUpSuppression(SetUpSuppressionMixin, SynchronousTestSuppression): - pass - - - -class AsynchronousTestSetUpSuppression(SetUpSuppressionMixin, AsynchronousTestSuppression): - pass - - - -class TearDownSuppressionMixin(object): - def tearDown(self): - self._emit() - - - -class SynchronousTestTearDownSuppression(TearDownSuppressionMixin, SynchronousTestSuppression): - pass - - - -class AsynchronousTestTearDownSuppression(TearDownSuppressionMixin, AsynchronousTestSuppression): - pass - - - -class TestSuppression2Mixin(EmitMixin): - def testSuppressModule(self): - self._emit() - - - -class SynchronousTestSuppression2(TestSuppression2Mixin, unittest.SynchronousTestCase): - pass - - - -class AsynchronousTestSuppression2(TestSuppression2Mixin, unittest.TestCase): - pass - - -suppress = [util.suppress(message=MODULE_WARNING_MSG)] diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_assertions.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_assertions.py deleted file mode 100755 index a9490e03..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_assertions.py +++ /dev/null @@ -1,1026 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for assertions provided by C{SynchronousTestCase} and C{TestCase}, -provided by L{twisted.trial.unittest}. - -L{TestFailureTests} demonstrates that L{SynchronousTestCase.fail} works, so that -is the only method on C{twisted.trial.unittest.SynchronousTestCase} that is -initially assumed to work. The test classes are arranged so that the methods -demonstrated to work earlier in the file are used by those later in the file -(even though the runner will probably not run the tests in this order). -""" - -from __future__ import division - -import warnings -from pprint import pformat -import unittest as pyunit - -from twisted.python import reflect, failure -from twisted.python.deprecate import deprecated, getVersionString -from twisted.python.versions import Version -from twisted.internet import defer -from twisted.trial import unittest, runner, reporter - -class MockEquality(object): - def __init__(self, name): - self.name = name - - def __repr__(self): - return "MockEquality(%s)" % (self.name,) - - def __eq__(self, other): - if not hasattr(other, 'name'): - raise ValueError("%r not comparable to %r" % (other, self)) - return self.name[0] == other.name[0] - - -class TestFailureTests(pyunit.TestCase): - """ - Tests for the most basic functionality of L{SynchronousTestCase}, for - failing tests. - - This class contains tests to demonstrate that L{SynchronousTestCase.fail} - can be used to fail a test, and that that failure is reflected in the test - result object. This should be sufficient functionality so that further - tests can be built on L{SynchronousTestCase} instead of - L{unittest.TestCase}. This depends on L{unittest.TestCase} working. - """ - class FailingTest(unittest.SynchronousTestCase): - def test_fails(self): - self.fail("This test fails.") - - - def setUp(self): - """ - Load a suite of one test which can be used to exercise the failure - handling behavior. - """ - components = [ - __name__, self.__class__.__name__, self.FailingTest.__name__] - self.loader = pyunit.TestLoader() - self.suite = self.loader.loadTestsFromName(".".join(components)) - self.test = list(self.suite)[0] - - - def test_fail(self): - """ - L{SynchronousTestCase.fail} raises - L{SynchronousTestCase.failureException} with the given argument. - """ - try: - self.test.fail("failed") - except self.test.failureException as result: - self.assertEqual("failed", str(result)) - else: - self.fail( - "SynchronousTestCase.fail method did not raise " - "SynchronousTestCase.failureException") - - - def test_failingExceptionFails(self): - """ - When a test method raises L{SynchronousTestCase.failureException}, the test is - marked as having failed on the L{TestResult}. - """ - result = pyunit.TestResult() - self.suite.run(result) - self.failIf(result.wasSuccessful()) - self.assertEqual(result.errors, []) - self.assertEqual(len(result.failures), 1) - self.assertEqual(result.failures[0][0], self.test) - - - -class AssertFalseTests(unittest.SynchronousTestCase): - """ - Tests for L{SynchronousTestCase}'s C{assertFalse} and C{failIf} assertion - methods. - - This is pretty paranoid. Still, a certain paranoia is healthy if you - are testing a unit testing framework. - - @note: As of 11.2, C{assertFalse} is preferred over C{failIf}. - """ - def _assertFalseFalse(self, method): - """ - Perform the positive case test for C{failIf} or C{assertFalse}. - - @param method: The test method to test. - """ - for notTrue in [0, 0.0, False, None, (), []]: - result = method(notTrue, "failed on %r" % (notTrue,)) - if result != notTrue: - self.fail("Did not return argument %r" % (notTrue,)) - - - def _assertFalseTrue(self, method): - """ - Perform the negative case test for C{failIf} or C{assertFalse}. - - @param method: The test method to test. - """ - for true in [1, True, 'cat', [1,2], (3,4)]: - try: - method(true, "failed on %r" % (true,)) - except self.failureException, e: - if str(e) != "failed on %r" % (true,): - self.fail("Raised incorrect exception on %r: %r" % (true, e)) - else: - self.fail("Call to failIf(%r) didn't fail" % (true,)) - - - def test_failIfFalse(self): - """ - L{SynchronousTestCase.failIf} returns its argument if its argument is - not considered true. - """ - self._assertFalseFalse(self.failIf) - - - def test_assertFalseFalse(self): - """ - L{SynchronousTestCase.assertFalse} returns its argument if its argument - is not considered true. - """ - self._assertFalseFalse(self.assertFalse) - - - def test_failIfTrue(self): - """ - L{SynchronousTestCase.failIf} raises - L{SynchronousTestCase.failureException} if its argument is considered - true. - """ - self._assertFalseTrue(self.failIf) - - - def test_assertFalseTrue(self): - """ - L{SynchronousTestCase.assertFalse} raises - L{SynchronousTestCase.failureException} if its argument is considered - true. - """ - self._assertFalseTrue(self.assertFalse) - - - -class AssertTrueTests(unittest.SynchronousTestCase): - """ - Tests for L{SynchronousTestCase}'s C{assertTrue} and C{failUnless} assertion - methods. - - This is pretty paranoid. Still, a certain paranoia is healthy if you - are testing a unit testing framework. - - @note: As of 11.2, C{assertTrue} is preferred over C{failUnless}. - """ - def _assertTrueFalse(self, method): - """ - Perform the negative case test for C{assertTrue} and C{failUnless}. - - @param method: The test method to test. - """ - for notTrue in [0, 0.0, False, None, (), []]: - try: - method(notTrue, "failed on %r" % (notTrue,)) - except self.failureException, e: - if str(e) != "failed on %r" % (notTrue,): - self.fail( - "Raised incorrect exception on %r: %r" % (notTrue, e)) - else: - self.fail( - "Call to %s(%r) didn't fail" % (method.__name__, notTrue,)) - - - def _assertTrueTrue(self, method): - """ - Perform the positive case test for C{assertTrue} and C{failUnless}. - - @param method: The test method to test. - """ - for true in [1, True, 'cat', [1,2], (3,4)]: - result = method(true, "failed on %r" % (true,)) - if result != true: - self.fail("Did not return argument %r" % (true,)) - - - def test_assertTrueFalse(self): - """ - L{SynchronousTestCase.assertTrue} raises - L{SynchronousTestCase.failureException} if its argument is not - considered true. - """ - self._assertTrueFalse(self.assertTrue) - - - def test_failUnlessFalse(self): - """ - L{SynchronousTestCase.failUnless} raises - L{SynchronousTestCase.failureException} if its argument is not - considered true. - """ - self._assertTrueFalse(self.failUnless) - - - def test_assertTrueTrue(self): - """ - L{SynchronousTestCase.assertTrue} returns its argument if its argument - is considered true. - """ - self._assertTrueTrue(self.assertTrue) - - - def test_failUnlessTrue(self): - """ - L{SynchronousTestCase.failUnless} returns its argument if its argument - is considered true. - """ - self._assertTrueTrue(self.failUnless) - - - -class TestSynchronousAssertions(unittest.SynchronousTestCase): - """ - Tests for L{SynchronousTestCase}'s assertion methods. That is, failUnless*, - failIf*, assert* (not covered by other more specific test classes). - - Note: As of 11.2, assertEqual is preferred over the failUnlessEqual(s) - variants. Tests have been modified to reflect this preference. - - This is pretty paranoid. Still, a certain paranoia is healthy if you are - testing a unit testing framework. - """ - def _testEqualPair(self, first, second): - x = self.assertEqual(first, second) - if x != first: - self.fail("assertEqual should return first parameter") - - - def _testUnequalPair(self, first, second): - try: - self.assertEqual(first, second) - except self.failureException, e: - expected = 'not equal:\na = %s\nb = %s\n' % ( - pformat(first), pformat(second)) - if str(e) != expected: - self.fail("Expected: %r; Got: %s" % (expected, str(e))) - else: - self.fail("Call to assertEqual(%r, %r) didn't fail" - % (first, second)) - - - def test_assertEqual_basic(self): - self._testEqualPair('cat', 'cat') - self._testUnequalPair('cat', 'dog') - self._testEqualPair([1], [1]) - self._testUnequalPair([1], 'orange') - - - def test_assertEqual_custom(self): - x = MockEquality('first') - y = MockEquality('second') - z = MockEquality('fecund') - self._testEqualPair(x, x) - self._testEqualPair(x, z) - self._testUnequalPair(x, y) - self._testUnequalPair(y, z) - - - def test_assertEqualMessage(self): - """ - When a message is passed to L{assertEqual}, it is included in the - error message. - """ - exception = self.assertRaises( - self.failureException, self.assertEqual, - 'foo', 'bar', 'message') - self.assertEqual( - str(exception), - "message\nnot equal:\na = 'foo'\nb = 'bar'\n") - - - def test_assertEqualNoneMessage(self): - """ - If a message is specified as C{None}, it is not included in the error - message of L{assertEqual}. - """ - exception = self.assertRaises( - self.failureException, self.assertEqual, 'foo', 'bar', None) - self.assertEqual(str(exception), "not equal:\na = 'foo'\nb = 'bar'\n") - - - def test_assertEqual_incomparable(self): - apple = MockEquality('apple') - orange = ['orange'] - try: - self.assertEqual(apple, orange) - except self.failureException: - self.fail("Fail raised when ValueError ought to have been raised.") - except ValueError: - # good. error not swallowed - pass - else: - self.fail("Comparing %r and %r should have raised an exception" - % (apple, orange)) - - - def _raiseError(self, error): - raise error - - def test_failUnlessRaises_expected(self): - x = self.failUnlessRaises(ValueError, self._raiseError, ValueError) - self.failUnless(isinstance(x, ValueError), - "Expect failUnlessRaises to return instance of raised " - "exception.") - - def test_failUnlessRaises_unexpected(self): - try: - self.failUnlessRaises(ValueError, self._raiseError, TypeError) - except TypeError: - self.fail("failUnlessRaises shouldn't re-raise unexpected " - "exceptions") - except self.failureException: - # what we expect - pass - else: - self.fail("Expected exception wasn't raised. Should have failed") - - def test_failUnlessRaises_noException(self): - try: - self.failUnlessRaises(ValueError, lambda : None) - except self.failureException, e: - self.assertEqual(str(e), - 'ValueError not raised (None returned)') - else: - self.fail("Exception not raised. Should have failed") - - def test_failUnlessRaises_failureException(self): - x = self.failUnlessRaises(self.failureException, self._raiseError, - self.failureException) - self.failUnless(isinstance(x, self.failureException), - "Expected %r instance to be returned" - % (self.failureException,)) - try: - x = self.failUnlessRaises(self.failureException, self._raiseError, - ValueError) - except self.failureException: - # what we expect - pass - else: - self.fail("Should have raised exception") - - def test_failIfEqual_basic(self): - x, y, z = [1], [2], [1] - ret = self.failIfEqual(x, y) - self.assertEqual(ret, x, - "failIfEqual should return first parameter") - self.failUnlessRaises(self.failureException, - self.failIfEqual, x, x) - self.failUnlessRaises(self.failureException, - self.failIfEqual, x, z) - - def test_failIfEqual_customEq(self): - x = MockEquality('first') - y = MockEquality('second') - z = MockEquality('fecund') - ret = self.failIfEqual(x, y) - self.assertEqual(ret, x, - "failIfEqual should return first parameter") - self.failUnlessRaises(self.failureException, - self.failIfEqual, x, x) - # test when __ne__ is not defined - self.failIfEqual(x, z, "__ne__ not defined, so not equal") - - - def test_failIfIdenticalPositive(self): - """ - C{failIfIdentical} returns its first argument if its first and second - arguments are not the same object. - """ - x = object() - y = object() - result = self.failIfIdentical(x, y) - self.assertEqual(x, result) - - - def test_failIfIdenticalNegative(self): - """ - C{failIfIdentical} raises C{failureException} if its first and second - arguments are the same object. - """ - x = object() - self.failUnlessRaises(self.failureException, - self.failIfIdentical, x, x) - - - def test_failUnlessIdentical(self): - x, y, z = [1], [1], [2] - ret = self.failUnlessIdentical(x, x) - self.assertEqual(ret, x, - 'failUnlessIdentical should return first ' - 'parameter') - self.failUnlessRaises(self.failureException, - self.failUnlessIdentical, x, y) - self.failUnlessRaises(self.failureException, - self.failUnlessIdentical, x, z) - - def test_failUnlessApproximates(self): - x, y, z = 1.0, 1.1, 1.2 - self.failUnlessApproximates(x, x, 0.2) - ret = self.failUnlessApproximates(x, y, 0.2) - self.assertEqual(ret, x, "failUnlessApproximates should return " - "first parameter") - self.failUnlessRaises(self.failureException, - self.failUnlessApproximates, x, z, 0.1) - self.failUnlessRaises(self.failureException, - self.failUnlessApproximates, x, y, 0.1) - - def test_failUnlessAlmostEqual(self): - precision = 5 - x = 8.000001 - y = 8.00001 - z = 8.000002 - self.failUnlessAlmostEqual(x, x, precision) - ret = self.failUnlessAlmostEqual(x, z, precision) - self.assertEqual(ret, x, "failUnlessAlmostEqual should return " - "first parameter (%r, %r)" % (ret, x)) - self.failUnlessRaises(self.failureException, - self.failUnlessAlmostEqual, x, y, precision) - - def test_failIfAlmostEqual(self): - precision = 5 - x = 8.000001 - y = 8.00001 - z = 8.000002 - ret = self.failIfAlmostEqual(x, y, precision) - self.assertEqual(ret, x, "failIfAlmostEqual should return " - "first parameter (%r, %r)" % (ret, x)) - self.failUnlessRaises(self.failureException, - self.failIfAlmostEqual, x, x, precision) - self.failUnlessRaises(self.failureException, - self.failIfAlmostEqual, x, z, precision) - - def test_failUnlessSubstring(self): - x = "cat" - y = "the dog sat" - z = "the cat sat" - self.failUnlessSubstring(x, x) - ret = self.failUnlessSubstring(x, z) - self.assertEqual(ret, x, 'should return first parameter') - self.failUnlessRaises(self.failureException, - self.failUnlessSubstring, x, y) - self.failUnlessRaises(self.failureException, - self.failUnlessSubstring, z, x) - - def test_failIfSubstring(self): - x = "cat" - y = "the dog sat" - z = "the cat sat" - self.failIfSubstring(z, x) - ret = self.failIfSubstring(x, y) - self.assertEqual(ret, x, 'should return first parameter') - self.failUnlessRaises(self.failureException, - self.failIfSubstring, x, x) - self.failUnlessRaises(self.failureException, - self.failIfSubstring, x, z) - - - def test_assertIsInstance(self): - """ - Test a true condition of assertIsInstance. - """ - A = type('A', (object,), {}) - a = A() - self.assertIsInstance(a, A) - - - def test_assertIsInstanceMultipleClasses(self): - """ - Test a true condition of assertIsInstance with multiple classes. - """ - A = type('A', (object,), {}) - B = type('B', (object,), {}) - a = A() - self.assertIsInstance(a, (A, B)) - - - def test_assertIsInstanceError(self): - """ - Test an error with assertIsInstance. - """ - A = type('A', (object,), {}) - B = type('B', (object,), {}) - a = A() - self.assertRaises(self.failureException, self.assertIsInstance, a, B) - - - def test_assertIsInstanceErrorMultipleClasses(self): - """ - Test an error with assertIsInstance and multiple classes. - """ - A = type('A', (object,), {}) - B = type('B', (object,), {}) - C = type('C', (object,), {}) - a = A() - self.assertRaises(self.failureException, self.assertIsInstance, a, (B, C)) - - - def test_assertIsInstanceCustomMessage(self): - """ - If L{TestCase.assertIsInstance} is passed a custom message as its 3rd - argument, the message is included in the failure exception raised when - the assertion fails. - """ - exc = self.assertRaises( - self.failureException, - self.assertIsInstance, 3, str, "Silly assertion") - self.assertIn("Silly assertion", str(exc)) - - - def test_assertNotIsInstance(self): - """ - Test a true condition of assertNotIsInstance. - """ - A = type('A', (object,), {}) - B = type('B', (object,), {}) - a = A() - self.assertNotIsInstance(a, B) - - - def test_assertNotIsInstanceMultipleClasses(self): - """ - Test a true condition of assertNotIsInstance and multiple classes. - """ - A = type('A', (object,), {}) - B = type('B', (object,), {}) - C = type('C', (object,), {}) - a = A() - self.assertNotIsInstance(a, (B, C)) - - - def test_assertNotIsInstanceError(self): - """ - Test an error with assertNotIsInstance. - """ - A = type('A', (object,), {}) - a = A() - error = self.assertRaises(self.failureException, - self.assertNotIsInstance, a, A) - self.assertEqual(str(error), "%r is an instance of %s" % (a, A)) - - - def test_assertNotIsInstanceErrorMultipleClasses(self): - """ - Test an error with assertNotIsInstance and multiple classes. - """ - A = type('A', (object,), {}) - B = type('B', (object,), {}) - a = A() - self.assertRaises(self.failureException, self.assertNotIsInstance, a, (A, B)) - - - def test_assertDictEqual(self): - """ - L{twisted.trial.unittest.TestCase} supports the C{assertDictEqual} - method inherited from the standard library in Python 2.7. - """ - self.assertDictEqual({'a': 1}, {'a': 1}) - if getattr(unittest.SynchronousTestCase, 'assertDictEqual', None) is None: - test_assertDictEqual.skip = ( - "assertDictEqual is not available on this version of Python") - - - -class TestAsynchronousAssertions(unittest.TestCase): - """ - Tests for L{TestCase}'s asynchronous extensions to L{SynchronousTestCase}. - That is, assertFailure. - """ - def test_assertFailure(self): - d = defer.maybeDeferred(lambda: 1/0) - return self.assertFailure(d, ZeroDivisionError) - - - def test_assertFailure_wrongException(self): - d = defer.maybeDeferred(lambda: 1/0) - self.assertFailure(d, OverflowError) - d.addCallbacks(lambda x: self.fail('Should have failed'), - lambda x: x.trap(self.failureException)) - return d - - - def test_assertFailure_noException(self): - d = defer.succeed(None) - self.assertFailure(d, ZeroDivisionError) - d.addCallbacks(lambda x: self.fail('Should have failed'), - lambda x: x.trap(self.failureException)) - return d - - - def test_assertFailure_moreInfo(self): - """ - In the case of assertFailure failing, check that we get lots of - information about the exception that was raised. - """ - try: - 1/0 - except ZeroDivisionError: - f = failure.Failure() - d = defer.fail(f) - d = self.assertFailure(d, RuntimeError) - d.addErrback(self._checkInfo, f) - return d - - - def _checkInfo(self, assertionFailure, f): - assert assertionFailure.check(self.failureException) - output = assertionFailure.getErrorMessage() - self.assertIn(f.getErrorMessage(), output) - self.assertIn(f.getBriefTraceback(), output) - - - def test_assertFailure_masked(self): - """ - A single wrong assertFailure should fail the whole test. - """ - class ExampleFailure(Exception): - pass - - class TC(unittest.TestCase): - failureException = ExampleFailure - def test_assertFailure(self): - d = defer.maybeDeferred(lambda: 1/0) - self.assertFailure(d, OverflowError) - self.assertFailure(d, ZeroDivisionError) - return d - - test = TC('test_assertFailure') - result = reporter.TestResult() - test.run(result) - self.assertEqual(1, len(result.failures)) - - -class WarningAssertionTests(unittest.SynchronousTestCase): - def test_assertWarns(self): - """ - Test basic assertWarns report. - """ - def deprecated(a): - warnings.warn("Woo deprecated", category=DeprecationWarning) - return a - r = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__, - deprecated, 123) - self.assertEqual(r, 123) - - - def test_assertWarnsRegistryClean(self): - """ - Test that assertWarns cleans the warning registry, so the warning is - not swallowed the second time. - """ - def deprecated(a): - warnings.warn("Woo deprecated", category=DeprecationWarning) - return a - r1 = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__, - deprecated, 123) - self.assertEqual(r1, 123) - # The warning should be raised again - r2 = self.assertWarns(DeprecationWarning, "Woo deprecated", __file__, - deprecated, 321) - self.assertEqual(r2, 321) - - - def test_assertWarnsError(self): - """ - Test assertWarns failure when no warning is generated. - """ - def normal(a): - return a - self.assertRaises(self.failureException, - self.assertWarns, DeprecationWarning, "Woo deprecated", __file__, - normal, 123) - - - def test_assertWarnsWrongCategory(self): - """ - Test assertWarns failure when the category is wrong. - """ - def deprecated(a): - warnings.warn("Foo deprecated", category=DeprecationWarning) - return a - self.assertRaises(self.failureException, - self.assertWarns, UserWarning, "Foo deprecated", __file__, - deprecated, 123) - - - def test_assertWarnsWrongMessage(self): - """ - Test assertWarns failure when the message is wrong. - """ - def deprecated(a): - warnings.warn("Foo deprecated", category=DeprecationWarning) - return a - self.assertRaises(self.failureException, - self.assertWarns, DeprecationWarning, "Bar deprecated", __file__, - deprecated, 123) - - - def test_assertWarnsWrongFile(self): - """ - If the warning emitted by a function refers to a different file than is - passed to C{assertWarns}, C{failureException} is raised. - """ - def deprecated(a): - # stacklevel=2 points at the direct caller of the function. The - # way assertRaises is invoked below, the direct caller will be - # something somewhere in trial, not something in this file. In - # Python 2.5 and earlier, stacklevel of 0 resulted in a warning - # pointing to the warnings module itself. Starting in Python 2.6, - # stacklevel of 0 and 1 both result in a warning pointing to *this* - # file, presumably due to the fact that the warn function is - # implemented in C and has no convenient Python - # filename/linenumber. - warnings.warn( - "Foo deprecated", category=DeprecationWarning, stacklevel=2) - self.assertRaises( - self.failureException, - # Since the direct caller isn't in this file, try to assert that - # the warning *does* point to this file, so that assertWarns raises - # an exception. - self.assertWarns, DeprecationWarning, "Foo deprecated", __file__, - deprecated, 123) - - def test_assertWarnsOnClass(self): - """ - Test assertWarns works when creating a class instance. - """ - class Warn: - def __init__(self): - warnings.warn("Do not call me", category=RuntimeWarning) - r = self.assertWarns(RuntimeWarning, "Do not call me", __file__, - Warn) - self.assertTrue(isinstance(r, Warn)) - r = self.assertWarns(RuntimeWarning, "Do not call me", __file__, - Warn) - self.assertTrue(isinstance(r, Warn)) - - - def test_assertWarnsOnMethod(self): - """ - Test assertWarns works when used on an instance method. - """ - class Warn: - def deprecated(self, a): - warnings.warn("Bar deprecated", category=DeprecationWarning) - return a - w = Warn() - r = self.assertWarns(DeprecationWarning, "Bar deprecated", __file__, - w.deprecated, 321) - self.assertEqual(r, 321) - r = self.assertWarns(DeprecationWarning, "Bar deprecated", __file__, - w.deprecated, 321) - self.assertEqual(r, 321) - - - def test_assertWarnsOnCall(self): - """ - Test assertWarns works on instance with C{__call__} method. - """ - class Warn: - def __call__(self, a): - warnings.warn("Egg deprecated", category=DeprecationWarning) - return a - w = Warn() - r = self.assertWarns(DeprecationWarning, "Egg deprecated", __file__, - w, 321) - self.assertEqual(r, 321) - r = self.assertWarns(DeprecationWarning, "Egg deprecated", __file__, - w, 321) - self.assertEqual(r, 321) - - - def test_assertWarnsFilter(self): - """ - Test assertWarns on a warning filterd by default. - """ - def deprecated(a): - warnings.warn("Woo deprecated", category=PendingDeprecationWarning) - return a - r = self.assertWarns(PendingDeprecationWarning, "Woo deprecated", - __file__, deprecated, 123) - self.assertEqual(r, 123) - - - def test_assertWarnsMultipleWarnings(self): - """ - C{assertWarns} does not raise an exception if the function it is passed - triggers the same warning more than once. - """ - def deprecated(): - warnings.warn("Woo deprecated", category=PendingDeprecationWarning) - def f(): - deprecated() - deprecated() - self.assertWarns( - PendingDeprecationWarning, "Woo deprecated", __file__, f) - - - def test_assertWarnsDifferentWarnings(self): - """ - For now, assertWarns is unable to handle multiple different warnings, - so it should raise an exception if it's the case. - """ - def deprecated(a): - warnings.warn("Woo deprecated", category=DeprecationWarning) - warnings.warn("Another one", category=PendingDeprecationWarning) - e = self.assertRaises(self.failureException, - self.assertWarns, DeprecationWarning, "Woo deprecated", - __file__, deprecated, 123) - self.assertEqual(str(e), "Can't handle different warnings") - - - def test_assertWarnsAfterUnassertedWarning(self): - """ - Warnings emitted before L{TestCase.assertWarns} is called do not get - flushed and do not alter the behavior of L{TestCase.assertWarns}. - """ - class TheWarning(Warning): - pass - - def f(message): - warnings.warn(message, category=TheWarning) - f("foo") - self.assertWarns(TheWarning, "bar", __file__, f, "bar") - [warning] = self.flushWarnings([f]) - self.assertEqual(warning['message'], "foo") - - - -class TestAssertionNames(unittest.SynchronousTestCase): - """ - Tests for consistency of naming within TestCase assertion methods - """ - def _getAsserts(self): - dct = {} - reflect.accumulateMethods(self, dct, 'assert') - return [ dct[k] for k in dct if not k.startswith('Not') and k != '_' ] - - def _name(self, x): - return x.__name__ - - - def test_failUnlessMatchesAssert(self): - """ - The C{failUnless*} test methods are a subset of the C{assert*} test - methods. This is intended to ensure that methods using the - I{failUnless} naming scheme are not added without corresponding methods - using the I{assert} naming scheme. The I{assert} naming scheme is - preferred, and new I{assert}-prefixed methods may be added without - corresponding I{failUnless}-prefixed methods. - """ - asserts = set(self._getAsserts()) - failUnlesses = set(reflect.prefixedMethods(self, 'failUnless')) - self.assertEqual( - failUnlesses, asserts.intersection(failUnlesses)) - - - def test_failIf_matches_assertNot(self): - asserts = reflect.prefixedMethods(unittest.SynchronousTestCase, 'assertNot') - failIfs = reflect.prefixedMethods(unittest.SynchronousTestCase, 'failIf') - self.assertEqual(sorted(asserts, key=self._name), - sorted(failIfs, key=self._name)) - - def test_equalSpelling(self): - for name, value in vars(self).items(): - if not callable(value): - continue - if name.endswith('Equal'): - self.failUnless(hasattr(self, name+'s'), - "%s but no %ss" % (name, name)) - self.assertEqual(value, getattr(self, name+'s')) - if name.endswith('Equals'): - self.failUnless(hasattr(self, name[:-1]), - "%s but no %s" % (name, name[:-1])) - self.assertEqual(value, getattr(self, name[:-1])) - - -class TestCallDeprecated(unittest.SynchronousTestCase): - """ - Test use of the L{SynchronousTestCase.callDeprecated} method with version objects. - """ - - version = Version('Twisted', 8, 0, 0) - - def test_callDeprecatedSuppressesWarning(self): - """ - callDeprecated calls a deprecated callable, suppressing the - deprecation warning. - """ - self.callDeprecated(self.version, oldMethod, 'foo') - self.assertEqual( - self.flushWarnings(), [], "No warnings should be shown") - - - def test_callDeprecatedCallsFunction(self): - """ - L{callDeprecated} actually calls the callable passed to it, and - forwards the result. - """ - result = self.callDeprecated(self.version, oldMethod, 'foo') - self.assertEqual('foo', result) - - - def test_failsWithoutDeprecation(self): - """ - L{callDeprecated} raises a test failure if the callable is not - deprecated. - """ - def notDeprecated(): - pass - exception = self.assertRaises( - self.failureException, - self.callDeprecated, self.version, notDeprecated) - self.assertEqual( - "%r is not deprecated." % notDeprecated, str(exception)) - - - def test_failsWithIncorrectDeprecation(self): - """ - callDeprecated raises a test failure if the callable was deprecated - at a different version to the one expected. - """ - differentVersion = Version('Foo', 1, 2, 3) - exception = self.assertRaises( - self.failureException, - self.callDeprecated, - differentVersion, oldMethod, 'foo') - self.assertIn(getVersionString(self.version), str(exception)) - self.assertIn(getVersionString(differentVersion), str(exception)) - - - def test_nestedDeprecation(self): - """ - L{callDeprecated} ignores all deprecations apart from the first. - - Multiple warnings are generated when a deprecated function calls - another deprecated function. The first warning is the one generated by - the explicitly called function. That's the warning that we care about. - """ - differentVersion = Version('Foo', 1, 2, 3) - - def nestedDeprecation(*args): - return oldMethod(*args) - nestedDeprecation = deprecated(differentVersion)(nestedDeprecation) - - self.callDeprecated(differentVersion, nestedDeprecation, 24) - - # The oldMethod deprecation should have been emitted too, not captured - # by callDeprecated. Flush it now to make sure it did happen and to - # prevent it from showing up on stdout. - warningsShown = self.flushWarnings() - self.assertEqual(len(warningsShown), 1) - - - def test_callDeprecationWithMessage(self): - """ - L{callDeprecated} can take a message argument used to check the warning - emitted. - """ - self.callDeprecated((self.version, "newMethod"), - oldMethodReplaced, 1) - - - def test_callDeprecationWithWrongMessage(self): - """ - If the message passed to L{callDeprecated} doesn't match, - L{callDeprecated} raises a test failure. - """ - exception = self.assertRaises( - self.failureException, - self.callDeprecated, - (self.version, "something.wrong"), - oldMethodReplaced, 1) - self.assertIn(getVersionString(self.version), str(exception)) - self.assertIn("please use newMethod instead", str(exception)) - - - - -@deprecated(TestCallDeprecated.version) -def oldMethod(x): - """ - Deprecated method for testing. - """ - return x - - -@deprecated(TestCallDeprecated.version, replacement="newMethod") -def oldMethodReplaced(x): - """ - Another deprecated method, which has been deprecated in favor of the - mythical 'newMethod'. - """ - return 2 * x diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_deferred.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_deferred.py deleted file mode 100755 index 5ecc8ce1..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_deferred.py +++ /dev/null @@ -1,220 +0,0 @@ -from twisted.internet import defer -from twisted.trial import unittest -from twisted.trial import runner, reporter, util -from twisted.trial.test import detests - - -class TestSetUp(unittest.TestCase): - def _loadSuite(self, klass): - loader = runner.TestLoader() - r = reporter.TestResult() - s = loader.loadClass(klass) - return r, s - - def test_success(self): - result, suite = self._loadSuite(detests.DeferredSetUpOK) - suite(result) - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - - def test_fail(self): - self.failIf(detests.DeferredSetUpFail.testCalled) - result, suite = self._loadSuite(detests.DeferredSetUpFail) - suite(result) - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.failures), 0) - self.assertEqual(len(result.errors), 1) - self.failIf(detests.DeferredSetUpFail.testCalled) - - def test_callbackFail(self): - self.failIf(detests.DeferredSetUpCallbackFail.testCalled) - result, suite = self._loadSuite(detests.DeferredSetUpCallbackFail) - suite(result) - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.failures), 0) - self.assertEqual(len(result.errors), 1) - self.failIf(detests.DeferredSetUpCallbackFail.testCalled) - - def test_error(self): - self.failIf(detests.DeferredSetUpError.testCalled) - result, suite = self._loadSuite(detests.DeferredSetUpError) - suite(result) - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.failures), 0) - self.assertEqual(len(result.errors), 1) - self.failIf(detests.DeferredSetUpError.testCalled) - - def test_skip(self): - self.failIf(detests.DeferredSetUpSkip.testCalled) - result, suite = self._loadSuite(detests.DeferredSetUpSkip) - suite(result) - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.failures), 0) - self.assertEqual(len(result.errors), 0) - self.assertEqual(len(result.skips), 1) - self.failIf(detests.DeferredSetUpSkip.testCalled) - - -class TestNeverFire(unittest.TestCase): - def setUp(self): - self._oldTimeout = util.DEFAULT_TIMEOUT_DURATION - util.DEFAULT_TIMEOUT_DURATION = 0.1 - - def tearDown(self): - util.DEFAULT_TIMEOUT_DURATION = self._oldTimeout - - def _loadSuite(self, klass): - loader = runner.TestLoader() - r = reporter.TestResult() - s = loader.loadClass(klass) - return r, s - - def test_setUp(self): - self.failIf(detests.DeferredSetUpNeverFire.testCalled) - result, suite = self._loadSuite(detests.DeferredSetUpNeverFire) - suite(result) - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.failures), 0) - self.assertEqual(len(result.errors), 1) - self.failIf(detests.DeferredSetUpNeverFire.testCalled) - self.failUnless(result.errors[0][1].check(defer.TimeoutError)) - - -class TestTester(unittest.TestCase): - def getTest(self, name): - raise NotImplementedError("must override me") - - def runTest(self, name): - result = reporter.TestResult() - self.getTest(name).run(result) - return result - - -class TestDeferred(TestTester): - def getTest(self, name): - return detests.DeferredTests(name) - - def test_pass(self): - result = self.runTest('test_pass') - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - - def test_passGenerated(self): - result = self.runTest('test_passGenerated') - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.failUnless(detests.DeferredTests.touched) - - def test_fail(self): - result = self.runTest('test_fail') - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.failures), 1) - - def test_failureInCallback(self): - result = self.runTest('test_failureInCallback') - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.failures), 1) - - def test_errorInCallback(self): - result = self.runTest('test_errorInCallback') - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.errors), 1) - - def test_skip(self): - result = self.runTest('test_skip') - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.skips), 1) - self.failIf(detests.DeferredTests.touched) - - def test_todo(self): - result = self.runTest('test_expectedFailure') - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.errors), 0) - self.assertEqual(len(result.failures), 0) - self.assertEqual(len(result.expectedFailures), 1) - - def test_thread(self): - result = self.runTest('test_thread') - self.assertEqual(result.testsRun, 1) - self.failUnless(result.wasSuccessful(), result.errors) - - -class TestTimeout(TestTester): - def getTest(self, name): - return detests.TimeoutTests(name) - - def _wasTimeout(self, error): - self.assertEqual(error.check(defer.TimeoutError), - defer.TimeoutError) - - def test_pass(self): - result = self.runTest('test_pass') - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - - def test_passDefault(self): - result = self.runTest('test_passDefault') - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - - def test_timeout(self): - result = self.runTest('test_timeout') - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.errors), 1) - self._wasTimeout(result.errors[0][1]) - - def test_timeoutZero(self): - result = self.runTest('test_timeoutZero') - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.errors), 1) - self._wasTimeout(result.errors[0][1]) - - def test_skip(self): - result = self.runTest('test_skip') - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.skips), 1) - - def test_todo(self): - result = self.runTest('test_expectedFailure') - self.failUnless(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.expectedFailures), 1) - self._wasTimeout(result.expectedFailures[0][1]) - - def test_errorPropagation(self): - result = self.runTest('test_errorPropagation') - self.failIf(result.wasSuccessful()) - self.assertEqual(result.testsRun, 1) - self._wasTimeout(detests.TimeoutTests.timedOut) - - def test_classTimeout(self): - loader = runner.TestLoader() - suite = loader.loadClass(detests.TestClassTimeoutAttribute) - result = reporter.TestResult() - suite.run(result) - self.assertEqual(len(result.errors), 1) - self._wasTimeout(result.errors[0][1]) - - def test_callbackReturnsNonCallingDeferred(self): - #hacky timeout - # raises KeyboardInterrupt because Trial sucks - from twisted.internet import reactor - call = reactor.callLater(2, reactor.crash) - result = self.runTest('test_calledButNeverCallback') - if call.active(): - call.cancel() - self.failIf(result.wasSuccessful()) - self._wasTimeout(result.errors[0][1]) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_doctest.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_doctest.py deleted file mode 100755 index 4506bed1..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_doctest.py +++ /dev/null @@ -1,64 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Test Twisted's doctest support. -""" - -from twisted.trial import itrial, runner, unittest, reporter -from twisted.trial.test import mockdoctest - - -class TestRunners(unittest.TestCase): - """ - Tests for Twisted's doctest support. - """ - - def test_id(self): - """ - Check that the id() of the doctests' case object contains the FQPN of - the actual tests. We need this because id() has weird behaviour w/ - doctest in Python 2.3. - """ - loader = runner.TestLoader() - suite = loader.loadDoctests(mockdoctest) - idPrefix = 'twisted.trial.test.mockdoctest.Counter' - for test in suite._tests: - self.assertIn(idPrefix, itrial.ITestCase(test).id()) - - - def test_basicTrialIntegration(self): - """ - L{loadDoctests} loads all of the doctests in the given module. - """ - loader = runner.TestLoader() - suite = loader.loadDoctests(mockdoctest) - self.assertEqual(7, suite.countTestCases()) - - - def _testRun(self, suite): - """ - Run C{suite} and check the result. - """ - result = reporter.TestResult() - suite.run(result) - self.assertEqual(5, result.successes) - # doctest reports failures as errors in 2.3 - self.assertEqual(2, len(result.errors) + len(result.failures)) - - - def test_expectedResults(self, count=1): - """ - Trial can correctly run doctests with its xUnit test APIs. - """ - suite = runner.TestLoader().loadDoctests(mockdoctest) - self._testRun(suite) - - - def test_repeatable(self): - """ - Doctests should be runnable repeatably. - """ - suite = runner.TestLoader().loadDoctests(mockdoctest) - self._testRun(suite) - self._testRun(suite) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_keyboard.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_keyboard.py deleted file mode 100755 index c5471a5e..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_keyboard.py +++ /dev/null @@ -1,113 +0,0 @@ -import StringIO -from twisted.trial import unittest -from twisted.trial import reporter, runner - - -class TrialTest(unittest.TestCase): - def setUp(self): - self.output = StringIO.StringIO() - self.reporter = reporter.TestResult() - self.loader = runner.TestLoader() - - -class TestInterruptInTest(TrialTest): - class InterruptedTest(unittest.TestCase): - def test_02_raiseInterrupt(self): - raise KeyboardInterrupt - - def test_01_doNothing(self): - pass - - def test_03_doNothing(self): - TestInterruptInTest.test_03_doNothing_run = True - - def setUp(self): - super(TestInterruptInTest, self).setUp() - self.suite = self.loader.loadClass(TestInterruptInTest.InterruptedTest) - TestInterruptInTest.test_03_doNothing_run = None - - def test_setUpOK(self): - self.assertEqual(3, self.suite.countTestCases()) - self.assertEqual(0, self.reporter.testsRun) - self.failIf(self.reporter.shouldStop) - - def test_interruptInTest(self): - runner.TrialSuite([self.suite]).run(self.reporter) - self.failUnless(self.reporter.shouldStop) - self.assertEqual(2, self.reporter.testsRun) - self.failIf(TestInterruptInTest.test_03_doNothing_run, - "test_03_doNothing ran.") - - -class TestInterruptInSetUp(TrialTest): - testsRun = 0 - - class InterruptedTest(unittest.TestCase): - def setUp(self): - if TestInterruptInSetUp.testsRun > 0: - raise KeyboardInterrupt - - def test_01(self): - TestInterruptInSetUp.testsRun += 1 - - def test_02(self): - TestInterruptInSetUp.testsRun += 1 - TestInterruptInSetUp.test_02_run = True - - def setUp(self): - super(TestInterruptInSetUp, self).setUp() - self.suite = self.loader.loadClass( - TestInterruptInSetUp.InterruptedTest) - TestInterruptInSetUp.test_02_run = False - TestInterruptInSetUp.testsRun = 0 - - def test_setUpOK(self): - self.assertEqual(0, TestInterruptInSetUp.testsRun) - self.assertEqual(2, self.suite.countTestCases()) - self.assertEqual(0, self.reporter.testsRun) - self.failIf(self.reporter.shouldStop) - - def test_interruptInSetUp(self): - runner.TrialSuite([self.suite]).run(self.reporter) - self.failUnless(self.reporter.shouldStop) - self.assertEqual(2, self.reporter.testsRun) - self.failIf(TestInterruptInSetUp.test_02_run, - "test_02 ran") - - -class TestInterruptInTearDown(TrialTest): - testsRun = 0 - - class InterruptedTest(unittest.TestCase): - def tearDown(self): - if TestInterruptInTearDown.testsRun > 0: - raise KeyboardInterrupt - - def test_01(self): - TestInterruptInTearDown.testsRun += 1 - - def test_02(self): - TestInterruptInTearDown.testsRun += 1 - TestInterruptInTearDown.test_02_run = True - - def setUp(self): - super(TestInterruptInTearDown, self).setUp() - self.suite = self.loader.loadClass( - TestInterruptInTearDown.InterruptedTest) - TestInterruptInTearDown.testsRun = 0 - TestInterruptInTearDown.test_02_run = False - - def test_setUpOK(self): - self.assertEqual(0, TestInterruptInTearDown.testsRun) - self.assertEqual(2, self.suite.countTestCases()) - self.assertEqual(0, self.reporter.testsRun) - self.failIf(self.reporter.shouldStop) - - def test_interruptInTearDown(self): - runner.TrialSuite([self.suite]).run(self.reporter) - self.assertEqual(1, self.reporter.testsRun) - self.failUnless(self.reporter.shouldStop) - self.failIf(TestInterruptInTearDown.test_02_run, - "test_02 ran") - - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_loader.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_loader.py deleted file mode 100755 index f08588e2..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_loader.py +++ /dev/null @@ -1,611 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for loading tests by name. -""" - -import os -import shutil -import sys - -from twisted.python import util -from twisted.python.hashlib import md5 -from twisted.trial.test import packages -from twisted.trial import runner, reporter, unittest -from twisted.trial.itrial import ITestCase - -from twisted.python.modules import getModule - - - -def testNames(tests): - """ - Return the id of each test within the given test suite or case. - """ - names = [] - for test in unittest._iterateTests(tests): - names.append(test.id()) - return names - - - -class FinderTest(packages.PackageTest): - def setUp(self): - packages.PackageTest.setUp(self) - self.loader = runner.TestLoader() - - def tearDown(self): - packages.PackageTest.tearDown(self) - - def test_findPackage(self): - sample1 = self.loader.findByName('twisted') - import twisted as sample2 - self.assertEqual(sample1, sample2) - - def test_findModule(self): - sample1 = self.loader.findByName('twisted.trial.test.sample') - import sample as sample2 - self.assertEqual(sample1, sample2) - - def test_findFile(self): - path = util.sibpath(__file__, 'sample.py') - sample1 = self.loader.findByName(path) - import sample as sample2 - self.assertEqual(sample1, sample2) - - def test_findObject(self): - sample1 = self.loader.findByName('twisted.trial.test.sample.FooTest') - import sample - self.assertEqual(sample.FooTest, sample1) - - def test_findNonModule(self): - self.failUnlessRaises(AttributeError, - self.loader.findByName, - 'twisted.trial.test.nonexistent') - - def test_findNonPackage(self): - self.failUnlessRaises(ValueError, - self.loader.findByName, - 'nonextant') - - def test_findNonFile(self): - path = util.sibpath(__file__, 'nonexistent.py') - self.failUnlessRaises(ValueError, self.loader.findByName, path) - - - -class FileTest(packages.SysPathManglingTest): - """ - Tests for L{runner.filenameToModule}. - """ - def test_notFile(self): - self.failUnlessRaises(ValueError, - runner.filenameToModule, 'doesntexist') - - def test_moduleInPath(self): - sample1 = runner.filenameToModule(util.sibpath(__file__, 'sample.py')) - import sample as sample2 - self.assertEqual(sample2, sample1) - - - def test_moduleNotInPath(self): - """ - If passed the path to a file containing the implementation of a - module within a package which is not on the import path, - L{runner.filenameToModule} returns a module object loosely - resembling the module defined by that file anyway. - """ - # "test_sample" isn't actually the name of this module. However, - # filenameToModule can't seem to figure that out. So clean up this - # mis-named module. It would be better if this weren't necessary - # and filenameToModule either didn't exist or added a correctly - # named module to sys.modules. - self.addCleanup(sys.modules.pop, 'test_sample', None) - - self.mangleSysPath(self.oldPath) - sample1 = runner.filenameToModule( - os.path.join(self.parent, 'goodpackage', 'test_sample.py')) - self.mangleSysPath(self.newPath) - from goodpackage import test_sample as sample2 - self.assertEqual(os.path.splitext(sample2.__file__)[0], - os.path.splitext(sample1.__file__)[0]) - - - def test_packageInPath(self): - package1 = runner.filenameToModule(os.path.join(self.parent, - 'goodpackage')) - import goodpackage - self.assertEqual(goodpackage, package1) - - - def test_packageNotInPath(self): - """ - If passed the path to a directory which represents a package which - is not on the import path, L{runner.filenameToModule} returns a - module object loosely resembling the package defined by that - directory anyway. - """ - # "__init__" isn't actually the name of the package! However, - # filenameToModule is pretty stupid and decides that is its name - # after all. Make sure it gets cleaned up. See the comment in - # test_moduleNotInPath for possible courses of action related to - # this. - self.addCleanup(sys.modules.pop, "__init__") - - self.mangleSysPath(self.oldPath) - package1 = runner.filenameToModule( - os.path.join(self.parent, 'goodpackage')) - self.mangleSysPath(self.newPath) - import goodpackage - self.assertEqual(os.path.splitext(goodpackage.__file__)[0], - os.path.splitext(package1.__file__)[0]) - - - def test_directoryNotPackage(self): - self.failUnlessRaises(ValueError, runner.filenameToModule, - util.sibpath(__file__, 'directory')) - - def test_filenameNotPython(self): - self.failUnlessRaises(ValueError, runner.filenameToModule, - util.sibpath(__file__, 'notpython.py')) - - def test_filenameMatchesPackage(self): - filename = os.path.join(self.parent, 'goodpackage.py') - fd = open(filename, 'w') - fd.write(packages.testModule) - fd.close() - try: - module = runner.filenameToModule(filename) - self.assertEqual(filename, module.__file__) - finally: - os.remove(filename) - - def test_directory(self): - """ - Test loader against a filesystem directory. It should handle - 'path' and 'path/' the same way. - """ - path = util.sibpath(__file__, 'goodDirectory') - os.mkdir(path) - f = file(os.path.join(path, '__init__.py'), "w") - f.close() - try: - module = runner.filenameToModule(path) - self.assert_(module.__name__.endswith('goodDirectory')) - module = runner.filenameToModule(path + os.path.sep) - self.assert_(module.__name__.endswith('goodDirectory')) - finally: - shutil.rmtree(path) - - - -class LoaderTest(packages.SysPathManglingTest): - """ - Tests for L{trial.TestLoader}. - """ - - def setUp(self): - self.loader = runner.TestLoader() - packages.SysPathManglingTest.setUp(self) - - - def test_sortCases(self): - import sample - suite = self.loader.loadClass(sample.AlphabetTest) - self.assertEqual(['test_a', 'test_b', 'test_c'], - [test._testMethodName for test in suite._tests]) - newOrder = ['test_b', 'test_c', 'test_a'] - sortDict = dict(zip(newOrder, range(3))) - self.loader.sorter = lambda x : sortDict.get(x.shortDescription(), -1) - suite = self.loader.loadClass(sample.AlphabetTest) - self.assertEqual(newOrder, - [test._testMethodName for test in suite._tests]) - - - def test_loadMethod(self): - import sample - suite = self.loader.loadMethod(sample.FooTest.test_foo) - self.assertEqual(1, suite.countTestCases()) - self.assertEqual('test_foo', suite._testMethodName) - - - def test_loadFailingMethod(self): - # test added for issue1353 - import erroneous - suite = self.loader.loadMethod(erroneous.TestRegularFail.test_fail) - result = reporter.TestResult() - suite.run(result) - self.assertEqual(result.testsRun, 1) - self.assertEqual(len(result.failures), 1) - - - def test_loadNonMethod(self): - import sample - self.failUnlessRaises(TypeError, self.loader.loadMethod, sample) - self.failUnlessRaises(TypeError, - self.loader.loadMethod, sample.FooTest) - self.failUnlessRaises(TypeError, self.loader.loadMethod, "string") - self.failUnlessRaises(TypeError, - self.loader.loadMethod, ('foo', 'bar')) - - - def test_loadBadDecorator(self): - """ - A decorated test method for which the decorator has failed to set the - method's __name__ correctly is loaded and its name in the class scope - discovered. - """ - import sample - suite = self.loader.loadMethod(sample.DecorationTest.test_badDecorator) - self.assertEqual(1, suite.countTestCases()) - self.assertEqual('test_badDecorator', suite._testMethodName) - - - def test_loadGoodDecorator(self): - """ - A decorated test method for which the decorator has set the method's - __name__ correctly is loaded and the only name by which it goes is used. - """ - import sample - suite = self.loader.loadMethod( - sample.DecorationTest.test_goodDecorator) - self.assertEqual(1, suite.countTestCases()) - self.assertEqual('test_goodDecorator', suite._testMethodName) - - - def test_loadRenamedDecorator(self): - """ - Load a decorated method which has been copied to a new name inside the - class. Thus its __name__ and its key in the class's __dict__ no - longer match. - """ - import sample - suite = self.loader.loadMethod( - sample.DecorationTest.test_renamedDecorator) - self.assertEqual(1, suite.countTestCases()) - self.assertEqual('test_renamedDecorator', suite._testMethodName) - - - def test_loadClass(self): - import sample - suite = self.loader.loadClass(sample.FooTest) - self.assertEqual(2, suite.countTestCases()) - self.assertEqual(['test_bar', 'test_foo'], - [test._testMethodName for test in suite._tests]) - - - def test_loadNonClass(self): - import sample - self.failUnlessRaises(TypeError, self.loader.loadClass, sample) - self.failUnlessRaises(TypeError, - self.loader.loadClass, sample.FooTest.test_foo) - self.failUnlessRaises(TypeError, self.loader.loadClass, "string") - self.failUnlessRaises(TypeError, - self.loader.loadClass, ('foo', 'bar')) - - - def test_loadNonTestCase(self): - import sample - self.failUnlessRaises(ValueError, self.loader.loadClass, - sample.NotATest) - - - def test_loadModule(self): - import sample - suite = self.loader.loadModule(sample) - self.assertEqual(10, suite.countTestCases()) - - - def test_loadNonModule(self): - import sample - self.failUnlessRaises(TypeError, - self.loader.loadModule, sample.FooTest) - self.failUnlessRaises(TypeError, - self.loader.loadModule, sample.FooTest.test_foo) - self.failUnlessRaises(TypeError, self.loader.loadModule, "string") - self.failUnlessRaises(TypeError, - self.loader.loadModule, ('foo', 'bar')) - - - def test_loadPackage(self): - import goodpackage - suite = self.loader.loadPackage(goodpackage) - self.assertEqual(7, suite.countTestCases()) - - - def test_loadNonPackage(self): - import sample - self.failUnlessRaises(TypeError, - self.loader.loadPackage, sample.FooTest) - self.failUnlessRaises(TypeError, - self.loader.loadPackage, sample.FooTest.test_foo) - self.failUnlessRaises(TypeError, self.loader.loadPackage, "string") - self.failUnlessRaises(TypeError, - self.loader.loadPackage, ('foo', 'bar')) - - - def test_loadModuleAsPackage(self): - import sample - ## XXX -- should this instead raise a ValueError? -- jml - self.failUnlessRaises(TypeError, self.loader.loadPackage, sample) - - - def test_loadPackageRecursive(self): - import goodpackage - suite = self.loader.loadPackage(goodpackage, recurse=True) - self.assertEqual(14, suite.countTestCases()) - - - def test_loadAnythingOnModule(self): - import sample - suite = self.loader.loadAnything(sample) - self.assertEqual(sample.__name__, - suite._tests[0]._tests[0].__class__.__module__) - - - def test_loadAnythingOnClass(self): - import sample - suite = self.loader.loadAnything(sample.FooTest) - self.assertEqual(2, suite.countTestCases()) - - - def test_loadAnythingOnMethod(self): - import sample - suite = self.loader.loadAnything(sample.FooTest.test_foo) - self.assertEqual(1, suite.countTestCases()) - - - def test_loadAnythingOnPackage(self): - import goodpackage - suite = self.loader.loadAnything(goodpackage) - self.failUnless(isinstance(suite, self.loader.suiteFactory)) - self.assertEqual(7, suite.countTestCases()) - - - def test_loadAnythingOnPackageRecursive(self): - import goodpackage - suite = self.loader.loadAnything(goodpackage, recurse=True) - self.failUnless(isinstance(suite, self.loader.suiteFactory)) - self.assertEqual(14, suite.countTestCases()) - - - def test_loadAnythingOnString(self): - # the important thing about this test is not the string-iness - # but the non-handledness. - self.failUnlessRaises(TypeError, - self.loader.loadAnything, "goodpackage") - - - def test_importErrors(self): - import package - suite = self.loader.loadPackage(package, recurse=True) - result = reporter.Reporter() - suite.run(result) - self.assertEqual(False, result.wasSuccessful()) - self.assertEqual(2, len(result.errors)) - errors = [test.id() for test, error in result.errors] - errors.sort() - self.assertEqual(errors, ['package.test_bad_module', - 'package.test_import_module']) - - - def test_differentInstances(self): - """ - L{TestLoader.loadClass} returns a suite with each test method - represented by a different instances of the L{TestCase} they are - defined on. - """ - class DistinctInstances(unittest.TestCase): - def test_1(self): - self.first = 'test1Run' - - def test_2(self): - self.assertFalse(hasattr(self, 'first')) - - suite = self.loader.loadClass(DistinctInstances) - result = reporter.Reporter() - suite.run(result) - self.assertTrue(result.wasSuccessful()) - - - def test_loadModuleWith_test_suite(self): - """ - Check that C{test_suite} is used when present and other L{TestCase}s are - not included. - """ - from twisted.trial.test import mockcustomsuite - suite = self.loader.loadModule(mockcustomsuite) - self.assertEqual(0, suite.countTestCases()) - self.assertEqual("MyCustomSuite", getattr(suite, 'name', None)) - - - def test_loadModuleWith_testSuite(self): - """ - Check that C{testSuite} is used when present and other L{TestCase}s are - not included. - """ - from twisted.trial.test import mockcustomsuite2 - suite = self.loader.loadModule(mockcustomsuite2) - self.assertEqual(0, suite.countTestCases()) - self.assertEqual("MyCustomSuite", getattr(suite, 'name', None)) - - - def test_loadModuleWithBothCustom(self): - """ - Check that if C{testSuite} and C{test_suite} are both present in a - module then C{testSuite} gets priority. - """ - from twisted.trial.test import mockcustomsuite3 - suite = self.loader.loadModule(mockcustomsuite3) - self.assertEqual('testSuite', getattr(suite, 'name', None)) - - - def test_customLoadRaisesAttributeError(self): - """ - Make sure that any C{AttributeError}s raised by C{testSuite} are not - swallowed by L{TestLoader}. - """ - def testSuite(): - raise AttributeError('should be reraised') - from twisted.trial.test import mockcustomsuite2 - mockcustomsuite2.testSuite, original = (testSuite, - mockcustomsuite2.testSuite) - try: - self.assertRaises(AttributeError, self.loader.loadModule, - mockcustomsuite2) - finally: - mockcustomsuite2.testSuite = original - - - # XXX - duplicated and modified from test_script - def assertSuitesEqual(self, test1, test2): - names1 = testNames(test1) - names2 = testNames(test2) - names1.sort() - names2.sort() - self.assertEqual(names1, names2) - - - def test_loadByNamesDuplicate(self): - """ - Check that loadByNames ignores duplicate names - """ - module = 'twisted.trial.test.test_test_visitor' - suite1 = self.loader.loadByNames([module, module], True) - suite2 = self.loader.loadByName(module, True) - self.assertSuitesEqual(suite1, suite2) - - - def test_loadDifferentNames(self): - """ - Check that loadByNames loads all the names that it is given - """ - modules = ['goodpackage', 'package.test_module'] - suite1 = self.loader.loadByNames(modules) - suite2 = runner.TestSuite(map(self.loader.loadByName, modules)) - self.assertSuitesEqual(suite1, suite2) - - def test_loadInheritedMethods(self): - """ - Check that test methods names which are inherited from are all - loaded rather than just one. - """ - methods = ['inheritancepackage.test_x.A.test_foo', - 'inheritancepackage.test_x.B.test_foo'] - suite1 = self.loader.loadByNames(methods) - suite2 = runner.TestSuite(map(self.loader.loadByName, methods)) - self.assertSuitesEqual(suite1, suite2) - - - -class ZipLoadingTest(LoaderTest): - def setUp(self): - from twisted.test.test_paths import zipit - LoaderTest.setUp(self) - zipit(self.parent, self.parent+'.zip') - self.parent += '.zip' - self.mangleSysPath(self.oldPath+[self.parent]) - - - -class PackageOrderingTest(packages.SysPathManglingTest): - if sys.version_info < (2, 4): - skip = ( - "Python 2.3 import semantics make this behavior incorrect on that " - "version of Python as well as difficult to test. The second " - "import of a package which raised an exception the first time it " - "was imported will succeed on Python 2.3, whereas it will fail on " - "later versions of Python. Trial does not account for this, so " - "this test fails with inconsistencies between the expected and " - "the received loader errors.") - - def setUp(self): - self.loader = runner.TestLoader() - self.topDir = self.mktemp() - parent = os.path.join(self.topDir, "uberpackage") - os.makedirs(parent) - file(os.path.join(parent, "__init__.py"), "wb").close() - packages.SysPathManglingTest.setUp(self, parent) - self.mangleSysPath(self.oldPath + [self.topDir]) - - def _trialSortAlgorithm(self, sorter): - """ - Right now, halfway by accident, trial sorts like this: - - 1. all modules are grouped together in one list and sorted. - - 2. within each module, the classes are grouped together in one list - and sorted. - - 3. finally within each class, each test method is grouped together - in a list and sorted. - - This attempts to return a sorted list of testable thingies following - those rules, so that we can compare the behavior of loadPackage. - - The things that show as 'cases' are errors from modules which failed to - import, and test methods. Let's gather all those together. - """ - pkg = getModule('uberpackage') - testModules = [] - for testModule in pkg.walkModules(): - if testModule.name.split(".")[-1].startswith("test_"): - testModules.append(testModule) - sortedModules = sorted(testModules, key=sorter) # ONE - for modinfo in sortedModules: - # Now let's find all the classes. - module = modinfo.load(None) - if module is None: - yield modinfo - else: - testClasses = [] - for attrib in modinfo.iterAttributes(): - if runner.isTestCase(attrib.load()): - testClasses.append(attrib) - sortedClasses = sorted(testClasses, key=sorter) # TWO - for clsinfo in sortedClasses: - testMethods = [] - for attr in clsinfo.iterAttributes(): - if attr.name.split(".")[-1].startswith('test'): - testMethods.append(attr) - sortedMethods = sorted(testMethods, key=sorter) # THREE - for methinfo in sortedMethods: - yield methinfo - - - def loadSortedPackages(self, sorter=runner.name): - """ - Verify that packages are loaded in the correct order. - """ - import uberpackage - self.loader.sorter = sorter - suite = self.loader.loadPackage(uberpackage, recurse=True) - # XXX: Work around strange, unexplained Zope crap. - # jml, 2007-11-15. - suite = unittest.decorate(suite, ITestCase) - resultingTests = list(unittest._iterateTests(suite)) - manifest = list(self._trialSortAlgorithm(sorter)) - for number, (manifestTest, actualTest) in enumerate( - zip(manifest, resultingTests)): - self.assertEqual( - manifestTest.name, actualTest.id(), - "#%d: %s != %s" % - (number, manifestTest.name, actualTest.id())) - self.assertEqual(len(manifest), len(resultingTests)) - - - def test_sortPackagesDefaultOrder(self): - self.loadSortedPackages() - - - def test_sortPackagesSillyOrder(self): - def sillySorter(s): - # This has to work on fully-qualified class names and class - # objects, which is silly, but it's the "spec", such as it is. -# if isinstance(s, type) or isinstance(s, types.ClassType): -# return s.__module__+'.'+s.__name__ - n = runner.name(s) - d = md5(n).hexdigest() - return d - self.loadSortedPackages(sillySorter) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_log.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_log.py deleted file mode 100755 index a2865506..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_log.py +++ /dev/null @@ -1,235 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Test the interaction between trial and errors logged during test run. -""" -from __future__ import division - -import time - -from twisted.internet import reactor, task -from twisted.python import failure, log -from twisted.trial import unittest, reporter - - -def makeFailure(): - """ - Return a new, realistic failure. - """ - try: - 1/0 - except ZeroDivisionError: - f = failure.Failure() - return f - - - -class Mask(object): - """ - Hide C{MockTest}s from Trial's automatic test finder. - """ - class FailureLoggingMixin(object): - def test_silent(self): - """ - Don't log any errors. - """ - - def test_single(self): - """ - Log a single error. - """ - log.err(makeFailure()) - - def test_double(self): - """ - Log two errors. - """ - log.err(makeFailure()) - log.err(makeFailure()) - - - class SynchronousFailureLogging(FailureLoggingMixin, unittest.SynchronousTestCase): - pass - - - class AsynchronousFailureLogging(FailureLoggingMixin, unittest.TestCase): - def test_inCallback(self): - """ - Log an error in an asynchronous callback. - """ - return task.deferLater(reactor, 0, lambda: log.err(makeFailure())) - - - -class TestObserver(unittest.SynchronousTestCase): - """ - Tests for L{unittest._LogObserver}, a helper for the implementation of - L{SynchronousTestCase.flushLoggedErrors}. - """ - def setUp(self): - self.result = reporter.TestResult() - self.observer = unittest._LogObserver() - - - def test_msg(self): - """ - Test that a standard log message doesn't go anywhere near the result. - """ - self.observer.gotEvent({'message': ('some message',), - 'time': time.time(), 'isError': 0, - 'system': '-'}) - self.assertEqual(self.observer.getErrors(), []) - - - def test_error(self): - """ - Test that an observed error gets added to the result - """ - f = makeFailure() - self.observer.gotEvent({'message': (), - 'time': time.time(), 'isError': 1, - 'system': '-', 'failure': f, - 'why': None}) - self.assertEqual(self.observer.getErrors(), [f]) - - - def test_flush(self): - """ - Check that flushing the observer with no args removes all errors. - """ - self.test_error() - flushed = self.observer.flushErrors() - self.assertEqual(self.observer.getErrors(), []) - self.assertEqual(len(flushed), 1) - self.assertTrue(flushed[0].check(ZeroDivisionError)) - - - def _makeRuntimeFailure(self): - return failure.Failure(RuntimeError('test error')) - - - def test_flushByType(self): - """ - Check that flushing the observer remove all failures of the given type. - """ - self.test_error() # log a ZeroDivisionError to the observer - f = self._makeRuntimeFailure() - self.observer.gotEvent(dict(message=(), time=time.time(), isError=1, - system='-', failure=f, why=None)) - flushed = self.observer.flushErrors(ZeroDivisionError) - self.assertEqual(self.observer.getErrors(), [f]) - self.assertEqual(len(flushed), 1) - self.assertTrue(flushed[0].check(ZeroDivisionError)) - - - def test_ignoreErrors(self): - """ - Check that C{_ignoreErrors} actually causes errors to be ignored. - """ - self.observer._ignoreErrors(ZeroDivisionError) - f = makeFailure() - self.observer.gotEvent({'message': (), - 'time': time.time(), 'isError': 1, - 'system': '-', 'failure': f, - 'why': None}) - self.assertEqual(self.observer.getErrors(), []) - - - def test_clearIgnores(self): - """ - Check that C{_clearIgnores} ensures that previously ignored errors - get captured. - """ - self.observer._ignoreErrors(ZeroDivisionError) - self.observer._clearIgnores() - f = makeFailure() - self.observer.gotEvent({'message': (), - 'time': time.time(), 'isError': 1, - 'system': '-', 'failure': f, - 'why': None}) - self.assertEqual(self.observer.getErrors(), [f]) - - - -class LogErrorsMixin(object): - """ - High-level tests demonstrating the expected behaviour of logged errors - during tests. - """ - - def setUp(self): - self.result = reporter.TestResult() - - def tearDown(self): - self.flushLoggedErrors(ZeroDivisionError) - - - def test_singleError(self): - """ - Test that a logged error gets reported as a test error. - """ - test = self.MockTest('test_single') - test(self.result) - self.assertEqual(len(self.result.errors), 1) - self.assertTrue(self.result.errors[0][1].check(ZeroDivisionError), - self.result.errors[0][1]) - self.assertEqual(0, self.result.successes) - - - def test_twoErrors(self): - """ - Test that when two errors get logged, they both get reported as test - errors. - """ - test = self.MockTest('test_double') - test(self.result) - self.assertEqual(len(self.result.errors), 2) - self.assertEqual(0, self.result.successes) - - - def test_errorsIsolated(self): - """ - Check that an error logged in one test doesn't fail the next test. - """ - t1 = self.MockTest('test_single') - t2 = self.MockTest('test_silent') - t1(self.result) - t2(self.result) - self.assertEqual(len(self.result.errors), 1) - self.assertEqual(self.result.errors[0][0], t1) - self.assertEqual(1, self.result.successes) - - - def test_boundedObservers(self): - """ - There are no extra log observers after a test runs. - """ - # XXX trial is *all about* global log state. It should really be fixed. - observer = unittest._LogObserver() - self.patch(unittest, '_logObserver', observer) - observers = log.theLogPublisher.observers[:] - test = self.MockTest() - test(self.result) - self.assertEqual(observers, log.theLogPublisher.observers) - - - -class SynchronousLogErrorsTests(LogErrorsMixin, unittest.SynchronousTestCase): - MockTest = Mask.SynchronousFailureLogging - - - -class AsynchronousLogErrorsTests(LogErrorsMixin, unittest.TestCase): - MockTest = Mask.AsynchronousFailureLogging - - def test_inCallback(self): - """ - Test that errors logged in callbacks get reported as test errors. - """ - test = self.MockTest('test_inCallback') - test(self.result) - self.assertEqual(len(self.result.errors), 1) - self.assertTrue(self.result.errors[0][1].check(ZeroDivisionError), - self.result.errors[0][1]) - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_output.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_output.py deleted file mode 100755 index bedde9e2..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_output.py +++ /dev/null @@ -1,162 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for the output generated by trial. -""" - -import os, StringIO - -from twisted.scripts import trial -from twisted.trial import runner -from twisted.trial.test import packages - - -def runTrial(*args): - from twisted.trial import reporter - config = trial.Options() - config.parseOptions(args) - output = StringIO.StringIO() - myRunner = runner.TrialRunner( - reporter.VerboseTextReporter, - stream=output, - workingDirectory=config['temp-directory']) - suite = trial._getSuite(config) - result = myRunner.run(suite) - return output.getvalue() - - -class TestImportErrors(packages.SysPathManglingTest): - """Actually run trial as if on the command line and check that the output - is what we expect. - """ - - debug = False - parent = "_testImportErrors" - def runTrial(self, *args): - return runTrial('--temp-directory', self.mktemp(), *args) - - def _print(self, stuff): - print stuff - return stuff - - def failUnlessIn(self, container, containee, *args, **kwargs): - # redefined to be useful in callbacks - super(TestImportErrors, self).failUnlessIn( - containee, container, *args, **kwargs) - return container - - def failIfIn(self, container, containee, *args, **kwargs): - # redefined to be useful in callbacks - super(TestImportErrors, self).failIfIn( - containee, container, *args, **kwargs) - return container - - def test_trialRun(self): - self.runTrial() - - def test_nonexistentModule(self): - d = self.runTrial('twisted.doesntexist') - self.failUnlessIn(d, '[ERROR]') - self.failUnlessIn(d, 'twisted.doesntexist') - return d - - def test_nonexistentPackage(self): - d = self.runTrial('doesntexist') - self.failUnlessIn(d, 'doesntexist') - self.failUnlessIn(d, 'ModuleNotFound') - self.failUnlessIn(d, '[ERROR]') - return d - - def test_nonexistentPackageWithModule(self): - d = self.runTrial('doesntexist.barney') - self.failUnlessIn(d, 'doesntexist.barney') - self.failUnlessIn(d, 'ObjectNotFound') - self.failUnlessIn(d, '[ERROR]') - return d - - def test_badpackage(self): - d = self.runTrial('badpackage') - self.failUnlessIn(d, '[ERROR]') - self.failUnlessIn(d, 'badpackage') - self.failIfIn(d, 'IOError') - return d - - def test_moduleInBadpackage(self): - d = self.runTrial('badpackage.test_module') - self.failUnlessIn(d, "[ERROR]") - self.failUnlessIn(d, "badpackage.test_module") - self.failIfIn(d, 'IOError') - return d - - def test_badmodule(self): - d = self.runTrial('package.test_bad_module') - self.failUnlessIn(d, '[ERROR]') - self.failUnlessIn(d, 'package.test_bad_module') - self.failIfIn(d, 'IOError') - self.failIfIn(d, '<module ') - return d - - def test_badimport(self): - d = self.runTrial('package.test_import_module') - self.failUnlessIn(d, '[ERROR]') - self.failUnlessIn(d, 'package.test_import_module') - self.failIfIn(d, 'IOError') - self.failIfIn(d, '<module ') - return d - - def test_recurseImport(self): - d = self.runTrial('package') - self.failUnlessIn(d, '[ERROR]') - self.failUnlessIn(d, 'test_bad_module') - self.failUnlessIn(d, 'test_import_module') - self.failIfIn(d, '<module ') - self.failIfIn(d, 'IOError') - return d - - def test_recurseImportErrors(self): - d = self.runTrial('package2') - self.failUnlessIn(d, '[ERROR]') - self.failUnlessIn(d, 'package2') - self.failUnlessIn(d, 'test_module') - self.failUnlessIn(d, "No module named frotz") - self.failIfIn(d, '<module ') - self.failIfIn(d, 'IOError') - return d - - def test_nonRecurseImportErrors(self): - d = self.runTrial('-N', 'package2') - self.failUnlessIn(d, '[ERROR]') - self.failUnlessIn(d, "No module named frotz") - self.failIfIn(d, '<module ') - return d - - def test_regularRun(self): - d = self.runTrial('package.test_module') - self.failIfIn(d, '[ERROR]') - self.failIfIn(d, 'IOError') - self.failUnlessIn(d, 'OK') - self.failUnlessIn(d, 'PASSED (successes=1)') - return d - - def test_filename(self): - self.mangleSysPath(self.oldPath) - d = self.runTrial( - os.path.join(self.parent, 'package', 'test_module.py')) - self.failIfIn(d, '[ERROR]') - self.failIfIn(d, 'IOError') - self.failUnlessIn(d, 'OK') - self.failUnlessIn(d, 'PASSED (successes=1)') - return d - - def test_dosFile(self): - ## XXX -- not really an output test, more of a script test - self.mangleSysPath(self.oldPath) - d = self.runTrial( - os.path.join(self.parent, - 'package', 'test_dos_module.py')) - self.failIfIn(d, '[ERROR]') - self.failIfIn(d, 'IOError') - self.failUnlessIn(d, 'OK') - self.failUnlessIn(d, 'PASSED (successes=1)') - return d diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_plugins.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_plugins.py deleted file mode 100755 index e1ec6aa7..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_plugins.py +++ /dev/null @@ -1,46 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. -# -# Maintainer: Jonathan Lange - -""" -Tests for L{twisted.plugins.twisted_trial}. -""" - -from twisted.plugin import getPlugins -from twisted.trial import unittest -from twisted.trial.itrial import IReporter - - -class TestPlugins(unittest.TestCase): - """ - Tests for Trial's reporter plugins. - """ - - def getPluginsByLongOption(self, longOption): - """ - Return the Trial reporter plugin with the given long option. - - If more than one is found, raise ValueError. If none are found, raise - IndexError. - """ - plugins = [ - plugin for plugin in getPlugins(IReporter) - if plugin.longOpt == longOption] - if len(plugins) > 1: - raise ValueError( - "More than one plugin found with long option %r: %r" - % (longOption, plugins)) - return plugins[0] - - - def test_subunitPlugin(self): - """ - One of the reporter plugins is the subunit reporter plugin. - """ - subunitPlugin = self.getPluginsByLongOption('subunit') - self.assertEqual('Subunit Reporter', subunitPlugin.name) - self.assertEqual('twisted.trial.reporter', subunitPlugin.module) - self.assertEqual('subunit', subunitPlugin.longOpt) - self.assertIdentical(None, subunitPlugin.shortOpt) - self.assertEqual('SubunitReporter', subunitPlugin.klass) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_pyunitcompat.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_pyunitcompat.py deleted file mode 100755 index 7b851541..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_pyunitcompat.py +++ /dev/null @@ -1,222 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. -# -# Maintainer: Jonathan Lange -from __future__ import division - -import sys -import traceback - -from zope.interface import implements - -from twisted.python import reflect -from twisted.python.failure import Failure -from twisted.trial import util -from twisted.trial.unittest import TestCase, PyUnitResultAdapter -from twisted.trial.itrial import IReporter, ITestCase -from twisted.trial.test import erroneous - -pyunit = __import__('unittest') - - -class TestPyUnitTestCase(TestCase): - - class PyUnitTest(pyunit.TestCase): - - def test_pass(self): - pass - - - def setUp(self): - self.original = self.PyUnitTest('test_pass') - self.test = ITestCase(self.original) - - - def test_visit(self): - """ - Trial assumes that test cases implement visit(). - """ - log = [] - def visitor(test): - log.append(test) - self.test.visit(visitor) - self.assertEqual(log, [self.test]) - test_visit.suppress = [ - util.suppress(category=DeprecationWarning, - message="Test visitors deprecated in Twisted 8.0")] - - - def test_callable(self): - """ - Tests must be callable in order to be used with Python's unittest.py. - """ - self.assertTrue(callable(self.test), - "%r is not callable." % (self.test,)) - - -class TestPyUnitResult(TestCase): - """ - Tests to show that PyUnitResultAdapter wraps TestResult objects from the - standard library 'unittest' module in such a way as to make them usable and - useful from Trial. - """ - - def test_dontUseAdapterWhenReporterProvidesIReporter(self): - """ - The L{PyUnitResultAdapter} is only used when the result passed to - C{run} does *not* provide L{IReporter}. - """ - class StubReporter(object): - """ - A reporter which records data about calls made to it. - - @ivar errors: Errors passed to L{addError}. - @ivar failures: Failures passed to L{addFailure}. - """ - - implements(IReporter) - - def __init__(self): - self.errors = [] - self.failures = [] - - def startTest(self, test): - """ - Do nothing. - """ - - def stopTest(self, test): - """ - Do nothing. - """ - - def addError(self, test, error): - """ - Record the error. - """ - self.errors.append(error) - - test = erroneous.ErrorTest("test_foo") - result = StubReporter() - test.run(result) - self.assertIsInstance(result.errors[0], Failure) - - - def test_success(self): - class SuccessTest(TestCase): - ran = False - def test_foo(s): - s.ran = True - test = SuccessTest('test_foo') - result = pyunit.TestResult() - test.run(result) - - self.failUnless(test.ran) - self.assertEqual(1, result.testsRun) - self.failUnless(result.wasSuccessful()) - - def test_failure(self): - class FailureTest(TestCase): - ran = False - def test_foo(s): - s.ran = True - s.fail('boom!') - test = FailureTest('test_foo') - result = pyunit.TestResult() - test.run(result) - - self.failUnless(test.ran) - self.assertEqual(1, result.testsRun) - self.assertEqual(1, len(result.failures)) - self.failIf(result.wasSuccessful()) - - def test_error(self): - test = erroneous.ErrorTest('test_foo') - result = pyunit.TestResult() - test.run(result) - - self.failUnless(test.ran) - self.assertEqual(1, result.testsRun) - self.assertEqual(1, len(result.errors)) - self.failIf(result.wasSuccessful()) - - def test_setUpError(self): - class ErrorTest(TestCase): - ran = False - def setUp(self): - 1/0 - def test_foo(s): - s.ran = True - test = ErrorTest('test_foo') - result = pyunit.TestResult() - test.run(result) - - self.failIf(test.ran) - self.assertEqual(1, result.testsRun) - self.assertEqual(1, len(result.errors)) - self.failIf(result.wasSuccessful()) - - def test_tracebackFromFailure(self): - """ - Errors added through the L{PyUnitResultAdapter} have the same traceback - information as if there were no adapter at all. - """ - try: - 1/0 - except ZeroDivisionError: - exc_info = sys.exc_info() - f = Failure() - pyresult = pyunit.TestResult() - result = PyUnitResultAdapter(pyresult) - result.addError(self, f) - self.assertEqual(pyresult.errors[0][1], - ''.join(traceback.format_exception(*exc_info))) - - - def test_traceback(self): - """ - As test_tracebackFromFailure, but covering more code. - """ - class ErrorTest(TestCase): - exc_info = None - def test_foo(self): - try: - 1/0 - except ZeroDivisionError: - self.exc_info = sys.exc_info() - raise - test = ErrorTest('test_foo') - result = pyunit.TestResult() - test.run(result) - - # We can't test that the tracebacks are equal, because Trial's - # machinery inserts a few extra frames on the top and we don't really - # want to trim them off without an extremely good reason. - # - # So, we just test that the result's stack ends with the the - # exception's stack. - - expected_stack = ''.join(traceback.format_tb(test.exc_info[2])) - observed_stack = '\n'.join(result.errors[0][1].splitlines()[:-1]) - - self.assertEqual(expected_stack.strip(), - observed_stack[-len(expected_stack):].strip()) - - - def test_tracebackFromCleanFailure(self): - """ - Errors added through the L{PyUnitResultAdapter} have the same - traceback information as if there were no adapter at all, even - if the Failure that held the information has been cleaned. - """ - try: - 1/0 - except ZeroDivisionError: - exc_info = sys.exc_info() - f = Failure() - f.cleanFailure() - pyresult = pyunit.TestResult() - result = PyUnitResultAdapter(pyresult) - result.addError(self, f) - self.assertEqual(pyresult.errors[0][1], - ''.join(traceback.format_exception(*exc_info))) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_reporter.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_reporter.py deleted file mode 100755 index e5bf848b..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_reporter.py +++ /dev/null @@ -1,1650 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. -# -# Maintainer: Jonathan Lange - -""" -Tests for L{twisted.trial.reporter}. -""" -from __future__ import division - -import errno, sys, os, re, StringIO -from inspect import getmro - -from twisted.internet.utils import suppressWarnings -from twisted.python import log -from twisted.python.failure import Failure -from twisted.trial import itrial, unittest, runner, reporter, util -from twisted.trial.reporter import UncleanWarningsReporterWrapper -from twisted.trial.test import erroneous -from twisted.trial.unittest import makeTodo, SkipTest, Todo -from twisted.trial.test import sample - - -class BrokenStream(object): - """ - Stream-ish object that raises a signal interrupt error. We use this to make - sure that Trial still manages to write what it needs to write. - """ - written = False - flushed = False - - def __init__(self, fObj): - self.fObj = fObj - - def write(self, s): - if self.written: - return self.fObj.write(s) - self.written = True - raise IOError(errno.EINTR, "Interrupted write") - - def flush(self): - if self.flushed: - return self.fObj.flush() - self.flushed = True - raise IOError(errno.EINTR, "Interrupted flush") - - -class StringTest(unittest.TestCase): - def stringComparison(self, expect, output): - output = filter(None, output) - self.failUnless(len(expect) <= len(output), - "Must have more observed than expected" - "lines %d < %d" % (len(output), len(expect))) - REGEX_PATTERN_TYPE = type(re.compile('')) - for line_number, (exp, out) in enumerate(zip(expect, output)): - if exp is None: - continue - elif isinstance(exp, str): - self.assertSubstring(exp, out, "Line %d: %r not in %r" - % (line_number, exp, out)) - elif isinstance(exp, REGEX_PATTERN_TYPE): - self.failUnless(exp.match(out), - "Line %d: %r did not match string %r" - % (line_number, exp.pattern, out)) - else: - raise TypeError("don't know what to do with object %r" - % (exp,)) - - -class TestTestResult(unittest.TestCase): - def setUp(self): - self.result = reporter.TestResult() - - def test_pyunitAddError(self): - # pyunit passes an exc_info tuple directly to addError - try: - raise RuntimeError('foo') - except RuntimeError, excValue: - self.result.addError(self, sys.exc_info()) - failure = self.result.errors[0][1] - self.assertEqual(excValue, failure.value) - self.assertEqual(RuntimeError, failure.type) - - def test_pyunitAddFailure(self): - # pyunit passes an exc_info tuple directly to addFailure - try: - raise self.failureException('foo') - except self.failureException, excValue: - self.result.addFailure(self, sys.exc_info()) - failure = self.result.failures[0][1] - self.assertEqual(excValue, failure.value) - self.assertEqual(self.failureException, failure.type) - - -class TestReporterRealtime(TestTestResult): - def setUp(self): - output = StringIO.StringIO() - self.result = reporter.Reporter(output, realtime=True) - - -class TestErrorReporting(StringTest): - doubleSeparator = re.compile(r'^=+$') - - def setUp(self): - self.loader = runner.TestLoader() - self.output = StringIO.StringIO() - self.result = reporter.Reporter(self.output) - - def getOutput(self, suite): - result = self.getResult(suite) - result.done() - return self.output.getvalue() - - def getResult(self, suite): - suite.run(self.result) - return self.result - - def test_formatErroredMethod(self): - """ - A test method which runs and has an error recorded against it is - reported in the output stream with the I{ERROR} tag along with a summary - of what error was reported and the ID of the test. - """ - cls = erroneous.SynchronousTestFailureInSetUp - suite = self.loader.loadClass(cls) - output = self.getOutput(suite).splitlines() - match = [ - self.doubleSeparator, - '[ERROR]', - 'Traceback (most recent call last):', - re.compile(r'^\s+File .*erroneous\.py., line \d+, in setUp$'), - re.compile(r'^\s+raise FoolishError, ' - r'.I am a broken setUp method.$'), - ('twisted.trial.test.erroneous.FoolishError: ' - 'I am a broken setUp method'), - '%s.%s.test_noop' % (cls.__module__, cls.__name__)] - self.stringComparison(match, output) - - - def test_formatFailedMethod(self): - """ - A test method which runs and has a failure recorded against it is - reported in the output stream with the I{FAIL} tag along with a summary - of what failure was reported and the ID of the test. - """ - suite = self.loader.loadMethod(erroneous.TestRegularFail.test_fail) - output = self.getOutput(suite).splitlines() - match = [ - self.doubleSeparator, - '[FAIL]', - 'Traceback (most recent call last):', - re.compile(r'^\s+File .*erroneous\.py., line \d+, in test_fail$'), - re.compile(r'^\s+self\.fail\("I fail"\)$'), - 'twisted.trial.unittest.FailTest: I fail', - 'twisted.trial.test.erroneous.TestRegularFail.test_fail', - ] - self.stringComparison(match, output) - - - def test_doctestError(self): - """ - A problem encountered while running a doctest is reported in the output - stream with a I{FAIL} or I{ERROR} tag along with a summary of what - problem was encountered and the ID of the test. - """ - from twisted.trial.test import erroneous - suite = unittest.decorate( - self.loader.loadDoctests(erroneous), itrial.ITestCase) - output = self.getOutput(suite) - path = 'twisted.trial.test.erroneous.unexpectedException' - for substring in ['1/0', 'ZeroDivisionError', - 'Exception raised:', path]: - self.assertSubstring(substring, output) - self.failUnless(re.search('Fail(ed|ure in) example:', output), - "Couldn't match 'Failure in example: ' " - "or 'Failed example: '") - expect = [self.doubleSeparator, - re.compile(r'\[(ERROR|FAIL)\]')] - self.stringComparison(expect, output.splitlines()) - - - def test_hiddenException(self): - """ - Check that errors in C{DelayedCall}s get reported, even if the - test already has a failure. - - Only really necessary for testing the deprecated style of tests that - use iterate() directly. See - L{erroneous.DelayedCall.testHiddenException} for more details. - """ - test = erroneous.DelayedCall('testHiddenException') - output = self.getOutput(test).splitlines() - match = [ - self.doubleSeparator, - '[FAIL]', - 'Traceback (most recent call last):', - re.compile(r'^\s+File .*erroneous\.py., line \d+, in ' - 'testHiddenException$'), - re.compile(r'^\s+self\.fail\("Deliberate failure to mask the ' - 'hidden exception"\)$'), - 'twisted.trial.unittest.FailTest: ' - 'Deliberate failure to mask the hidden exception', - 'twisted.trial.test.erroneous.DelayedCall.testHiddenException', - self.doubleSeparator, - '[ERROR]', - 'Traceback (most recent call last):', - re.compile(r'^\s+File .* in runUntilCurrent'), - re.compile(r'^\s+.*'), - re.compile('^\s+File .*erroneous\.py", line \d+, in go'), - re.compile('^\s+raise RuntimeError\(self.hiddenExceptionMsg\)'), - 'exceptions.RuntimeError: something blew up', - 'twisted.trial.test.erroneous.DelayedCall.testHiddenException', - ] - self.stringComparison(match, output) - - - -class TestUncleanWarningWrapperErrorReporting(TestErrorReporting): - """ - Tests that the L{UncleanWarningsReporterWrapper} can sufficiently proxy - IReporter failure and error reporting methods to a L{reporter.Reporter}. - """ - def setUp(self): - self.loader = runner.TestLoader() - self.output = StringIO.StringIO() - self.result = UncleanWarningsReporterWrapper( - reporter.Reporter(self.output)) - - - -class TracebackHandling(unittest.TestCase): - def getErrorFrames(self, test): - stream = StringIO.StringIO() - result = reporter.Reporter(stream) - test.run(result) - bads = result.failures + result.errors - assert len(bads) == 1 - assert bads[0][0] == test - return result._trimFrames(bads[0][1].frames) - - def checkFrames(self, observedFrames, expectedFrames): - for observed, expected in zip(observedFrames, expectedFrames): - self.assertEqual(observed[0], expected[0]) - observedSegs = os.path.splitext(observed[1])[0].split(os.sep) - expectedSegs = expected[1].split('/') - self.assertEqual(observedSegs[-len(expectedSegs):], - expectedSegs) - self.assertEqual(len(observedFrames), len(expectedFrames)) - - def test_basic(self): - test = erroneous.TestRegularFail('test_fail') - frames = self.getErrorFrames(test) - self.checkFrames(frames, - [('test_fail', 'twisted/trial/test/erroneous')]) - - def test_subroutine(self): - test = erroneous.TestRegularFail('test_subfail') - frames = self.getErrorFrames(test) - self.checkFrames(frames, - [('test_subfail', 'twisted/trial/test/erroneous'), - ('subroutine', 'twisted/trial/test/erroneous')]) - - def test_deferred(self): - test = erroneous.TestFailureInDeferredChain('test_fail') - frames = self.getErrorFrames(test) - self.checkFrames(frames, - [('_later', 'twisted/trial/test/erroneous')]) - - def test_noFrames(self): - result = reporter.Reporter(None) - self.assertEqual([], result._trimFrames([])) - - def test_oneFrame(self): - result = reporter.Reporter(None) - self.assertEqual(['fake frame'], result._trimFrames(['fake frame'])) - - -class FormatFailures(StringTest): - def setUp(self): - try: - raise RuntimeError('foo') - except RuntimeError: - self.f = Failure() - self.f.frames = [ - ['foo', 'foo/bar.py', 5, [('x', 5)], [('y', 'orange')]], - ['qux', 'foo/bar.py', 10, [('a', 'two')], [('b', 'MCMXCIX')]] - ] - self.stream = StringIO.StringIO() - self.result = reporter.Reporter(self.stream) - - def test_formatDefault(self): - tb = self.result._formatFailureTraceback(self.f) - self.stringComparison([ - 'Traceback (most recent call last):', - ' File "foo/bar.py", line 5, in foo', - re.compile(r'^\s*$'), - ' File "foo/bar.py", line 10, in qux', - re.compile(r'^\s*$'), - 'RuntimeError: foo'], tb.splitlines()) - - def test_formatString(self): - tb = ''' - File "twisted/trial/unittest.py", line 256, in failUnlessSubstring - return self.failUnlessIn(substring, astring, msg) -exceptions.TypeError: iterable argument required - -''' - expected = ''' - File "twisted/trial/unittest.py", line 256, in failUnlessSubstring - return self.failUnlessIn(substring, astring, msg) -exceptions.TypeError: iterable argument required -''' - formatted = self.result._formatFailureTraceback(tb) - self.assertEqual(expected, formatted) - - def test_mutation(self): - frames = self.f.frames[:] - # The call shouldn't mutate the frames. - self.result._formatFailureTraceback(self.f) - self.assertEqual(self.f.frames, frames) - - -class PyunitTestNames(unittest.TestCase): - def setUp(self): - self.stream = StringIO.StringIO() - self.test = sample.PyunitTest('test_foo') - - def test_verboseReporter(self): - result = reporter.VerboseTextReporter(self.stream) - result.startTest(self.test) - output = self.stream.getvalue() - self.assertEqual( - output, 'twisted.trial.test.sample.PyunitTest.test_foo ... ') - - def test_treeReporter(self): - result = reporter.TreeReporter(self.stream) - result.startTest(self.test) - output = self.stream.getvalue() - output = output.splitlines()[-1].strip() - self.assertEqual(output, result.getDescription(self.test) + ' ...') - - def test_getDescription(self): - result = reporter.TreeReporter(self.stream) - output = result.getDescription(self.test) - self.assertEqual(output, 'test_foo') - - - def test_minimalReporter(self): - """ - The summary of L{reporter.MinimalReporter} is a simple list of numbers, - indicating how many tests ran, how many failed etc. - - The numbers represents: - * the run time of the tests - * the number of tests run, printed 2 times for legacy reasons - * the number of errors - * the number of failures - * the number of skips - """ - result = reporter.MinimalReporter(self.stream) - self.test.run(result) - result._printSummary() - output = self.stream.getvalue().strip().split(' ') - self.assertEqual(output[1:], ['1', '1', '0', '0', '0']) - - - def test_minimalReporterTime(self): - """ - L{reporter.MinimalReporter} reports the time to run the tests as first - data in its output. - """ - times = [1.0, 1.2, 1.5, 1.9] - result = reporter.MinimalReporter(self.stream) - result._getTime = lambda: times.pop(0) - self.test.run(result) - result._printSummary() - output = self.stream.getvalue().strip().split(' ') - timer = output[0] - self.assertEqual(timer, "0.7") - - - def test_emptyMinimalReporter(self): - """ - The summary of L{reporter.MinimalReporter} is a list of zeroes when no - test is actually run. - """ - result = reporter.MinimalReporter(self.stream) - result._printSummary() - output = self.stream.getvalue().strip().split(' ') - self.assertEqual(output, ['0', '0', '0', '0', '0', '0']) - - - -class TestDirtyReactor(unittest.TestCase): - """ - The trial script has an option to treat L{DirtyReactorAggregateError}s as - warnings, as a migration tool for test authors. It causes a wrapper to be - placed around reporters that replaces L{DirtyReactorAggregatErrors} with - warnings. - """ - - def setUp(self): - self.dirtyError = Failure( - util.DirtyReactorAggregateError(['foo'], ['bar'])) - self.output = StringIO.StringIO() - self.test = TestDirtyReactor('test_errorByDefault') - - - def test_errorByDefault(self): - """ - L{DirtyReactorAggregateError}s are reported as errors with the default - Reporter. - """ - result = reporter.Reporter(stream=self.output) - result.addError(self.test, self.dirtyError) - self.assertEqual(len(result.errors), 1) - self.assertEqual(result.errors[0][1], self.dirtyError) - - - def test_warningsEnabled(self): - """ - L{DirtyReactorAggregateError}s are reported as warnings when using - the L{UncleanWarningsReporterWrapper}. - """ - result = UncleanWarningsReporterWrapper( - reporter.Reporter(stream=self.output)) - self.assertWarns(UserWarning, self.dirtyError.getErrorMessage(), - reporter.__file__, - result.addError, self.test, self.dirtyError) - - - def test_warningsMaskErrors(self): - """ - L{DirtyReactorAggregateError}s are I{not} reported as errors if the - L{UncleanWarningsReporterWrapper} is used. - """ - result = UncleanWarningsReporterWrapper( - reporter.Reporter(stream=self.output)) - self.assertWarns(UserWarning, self.dirtyError.getErrorMessage(), - reporter.__file__, - result.addError, self.test, self.dirtyError) - self.assertEqual(result._originalReporter.errors, []) - - - def test_dealsWithThreeTuples(self): - """ - Some annoying stuff can pass three-tuples to addError instead of - Failures (like PyUnit). The wrapper, of course, handles this case, - since it is a part of L{twisted.trial.itrial.IReporter}! But it does - not convert L{DirtyReactorAggregateError} to warnings in this case, - because nobody should be passing those in the form of three-tuples. - """ - result = UncleanWarningsReporterWrapper( - reporter.Reporter(stream=self.output)) - result.addError(self.test, - (self.dirtyError.type, self.dirtyError.value, None)) - self.assertEqual(len(result._originalReporter.errors), 1) - self.assertEqual(result._originalReporter.errors[0][1].type, - self.dirtyError.type) - self.assertEqual(result._originalReporter.errors[0][1].value, - self.dirtyError.value) - - - -class TrialTestNames(unittest.TestCase): - - def setUp(self): - self.stream = StringIO.StringIO() - self.test = sample.FooTest('test_foo') - - def test_verboseReporter(self): - result = reporter.VerboseTextReporter(self.stream) - result.startTest(self.test) - output = self.stream.getvalue() - self.assertEqual(output, self.test.id() + ' ... ') - - def test_treeReporter(self): - result = reporter.TreeReporter(self.stream) - result.startTest(self.test) - output = self.stream.getvalue() - output = output.splitlines()[-1].strip() - self.assertEqual(output, result.getDescription(self.test) + ' ...') - - def test_treeReporterWithDocstrings(self): - """A docstring""" - result = reporter.TreeReporter(self.stream) - self.assertEqual(result.getDescription(self), - 'test_treeReporterWithDocstrings') - - def test_getDescription(self): - result = reporter.TreeReporter(self.stream) - output = result.getDescription(self.test) - self.assertEqual(output, "test_foo") - - -class TestSkip(unittest.TestCase): - """ - Tests for L{reporter.Reporter}'s handling of skips. - """ - def setUp(self): - self.stream = StringIO.StringIO() - self.result = reporter.Reporter(self.stream) - self.test = sample.FooTest('test_foo') - - def _getSkips(self, result): - """ - Get the number of skips that happened to a reporter. - """ - return len(result.skips) - - def test_accumulation(self): - self.result.addSkip(self.test, 'some reason') - self.assertEqual(self._getSkips(self.result), 1) - - def test_success(self): - self.result.addSkip(self.test, 'some reason') - self.assertEqual(True, self.result.wasSuccessful()) - - - def test_summary(self): - """ - The summary of a successful run with skips indicates that the test - suite passed and includes the number of skips. - """ - self.result.addSkip(self.test, 'some reason') - self.result.done() - output = self.stream.getvalue().splitlines()[-1] - prefix = 'PASSED ' - self.failUnless(output.startswith(prefix)) - self.assertEqual(output[len(prefix):].strip(), '(skips=1)') - - - def test_basicErrors(self): - """ - The output at the end of a test run with skips includes the reasons - for skipping those tests. - """ - self.result.addSkip(self.test, 'some reason') - self.result.done() - output = self.stream.getvalue().splitlines()[3] - self.assertEqual(output.strip(), 'some reason') - - - def test_booleanSkip(self): - """ - Tests can be skipped without specifying a reason by setting the 'skip' - attribute to True. When this happens, the test output includes 'True' - as the reason. - """ - self.result.addSkip(self.test, True) - self.result.done() - output = self.stream.getvalue().splitlines()[3] - self.assertEqual(output, 'True') - - - def test_exceptionSkip(self): - """ - Skips can be raised as errors. When this happens, the error is - included in the summary at the end of the test suite. - """ - try: - 1/0 - except Exception, e: - error = e - self.result.addSkip(self.test, error) - self.result.done() - output = '\n'.join(self.stream.getvalue().splitlines()[3:5]).strip() - self.assertEqual(output, str(e)) - - -class UncleanWarningSkipTest(TestSkip): - """ - Tests for skips on a L{reporter.Reporter} wrapped by an - L{UncleanWarningsReporterWrapper}. - """ - def setUp(self): - TestSkip.setUp(self) - self.result = UncleanWarningsReporterWrapper(self.result) - - def _getSkips(self, result): - """ - Get the number of skips that happened to a reporter inside of an - unclean warnings reporter wrapper. - """ - return len(result._originalReporter.skips) - - - -class TodoTest(unittest.TestCase): - """ - Tests for L{reporter.Reporter}'s handling of todos. - """ - - def setUp(self): - self.stream = StringIO.StringIO() - self.result = reporter.Reporter(self.stream) - self.test = sample.FooTest('test_foo') - - - def _getTodos(self, result): - """ - Get the number of todos that happened to a reporter. - """ - return len(result.expectedFailures) - - - def _getUnexpectedSuccesses(self, result): - """ - Get the number of unexpected successes that happened to a reporter. - """ - return len(result.unexpectedSuccesses) - - - def test_accumulation(self): - """ - L{reporter.Reporter} accumulates the expected failures that it - is notified of. - """ - self.result.addExpectedFailure(self.test, Failure(Exception()), - makeTodo('todo!')) - self.assertEqual(self._getTodos(self.result), 1) - - - def test_success(self): - """ - A test run is still successful even if there are expected failures. - """ - self.result.addExpectedFailure(self.test, Failure(Exception()), - makeTodo('todo!')) - self.assertEqual(True, self.result.wasSuccessful()) - - - def test_unexpectedSuccess(self): - """ - A test which is marked as todo but succeeds will have an unexpected - success reported to its result. A test run is still successful even - when this happens. - """ - self.result.addUnexpectedSuccess(self.test, makeTodo("Heya!")) - self.assertEqual(True, self.result.wasSuccessful()) - self.assertEqual(self._getUnexpectedSuccesses(self.result), 1) - - - def test_summary(self): - """ - The reporter's C{printSummary} method should print the number of - expected failures that occured. - """ - self.result.addExpectedFailure(self.test, Failure(Exception()), - makeTodo('some reason')) - self.result.done() - output = self.stream.getvalue().splitlines()[-1] - prefix = 'PASSED ' - self.failUnless(output.startswith(prefix)) - self.assertEqual(output[len(prefix):].strip(), - '(expectedFailures=1)') - - - def test_basicErrors(self): - """ - The reporter's L{printErrors} method should include the value of the - Todo. - """ - self.result.addExpectedFailure(self.test, Failure(Exception()), - makeTodo('some reason')) - self.result.done() - output = self.stream.getvalue().splitlines()[3].strip() - self.assertEqual(output, "Reason: 'some reason'") - - - def test_booleanTodo(self): - """ - Booleans CAN'T be used as the value of a todo. Maybe this sucks. This - is a test for current behavior, not a requirement. - """ - self.result.addExpectedFailure(self.test, Failure(Exception()), - makeTodo(True)) - self.assertRaises(Exception, self.result.done) - - - def test_exceptionTodo(self): - """ - The exception for expected failures should be shown in the - C{printErrors} output. - """ - try: - 1/0 - except Exception, e: - error = e - self.result.addExpectedFailure(self.test, Failure(error), - makeTodo("todo!")) - self.result.done() - output = '\n'.join(self.stream.getvalue().splitlines()[3:]).strip() - self.assertTrue(str(e) in output) - - - -class UncleanWarningTodoTest(TodoTest): - """ - Tests for L{UncleanWarningsReporterWrapper}'s handling of todos. - """ - - def setUp(self): - TodoTest.setUp(self) - self.result = UncleanWarningsReporterWrapper(self.result) - - - def _getTodos(self, result): - """ - Get the number of todos that happened to a reporter inside of an - unclean warnings reporter wrapper. - """ - return len(result._originalReporter.expectedFailures) - - - def _getUnexpectedSuccesses(self, result): - """ - Get the number of unexpected successes that happened to a reporter - inside of an unclean warnings reporter wrapper. - """ - return len(result._originalReporter.unexpectedSuccesses) - - - -class MockColorizer: - """ - Used by TestTreeReporter to make sure that output is colored correctly. - """ - - def __init__(self, stream): - self.log = [] - - - def write(self, text, color): - self.log.append((color, text)) - - - -class TestTreeReporter(unittest.TestCase): - def setUp(self): - self.test = sample.FooTest('test_foo') - self.stream = StringIO.StringIO() - self.result = reporter.TreeReporter(self.stream) - self.result._colorizer = MockColorizer(self.stream) - self.log = self.result._colorizer.log - - def makeError(self): - try: - 1/0 - except ZeroDivisionError: - f = Failure() - return f - - def test_cleanupError(self): - """ - Run cleanupErrors and check that the output is correct, and colored - correctly. - """ - f = self.makeError() - self.result.cleanupErrors(f) - color, text = self.log[0] - self.assertEqual(color.strip(), self.result.ERROR) - self.assertEqual(text.strip(), 'cleanup errors') - color, text = self.log[1] - self.assertEqual(color.strip(), self.result.ERROR) - self.assertEqual(text.strip(), '[ERROR]') - test_cleanupError = suppressWarnings( - test_cleanupError, - util.suppress(category=reporter.BrokenTestCaseWarning), - util.suppress(category=DeprecationWarning)) - - - def test_upDownError(self): - """ - Run upDownError and check that the output is correct and colored - correctly. - """ - self.result.upDownError("method", None, None, False) - color, text = self.log[0] - self.assertEqual(color.strip(), self.result.ERROR) - self.assertEqual(text.strip(), 'method') - test_upDownError = suppressWarnings( - test_upDownError, - util.suppress(category=DeprecationWarning, - message="upDownError is deprecated in Twisted 8.0.")) - - - def test_summaryColoredSuccess(self): - """ - The summary in case of success should have a good count of successes - and be colored properly. - """ - self.result.addSuccess(self.test) - self.result.done() - self.assertEqual(self.log[1], (self.result.SUCCESS, 'PASSED')) - self.assertEqual( - self.stream.getvalue().splitlines()[-1].strip(), "(successes=1)") - - - def test_summaryColoredFailure(self): - """ - The summary in case of failure should have a good count of errors - and be colored properly. - """ - try: - raise RuntimeError('foo') - except RuntimeError: - self.result.addError(self, sys.exc_info()) - self.result.done() - self.assertEqual(self.log[1], (self.result.FAILURE, 'FAILED')) - self.assertEqual( - self.stream.getvalue().splitlines()[-1].strip(), "(errors=1)") - - - def test_getPrelude(self): - """ - The tree needs to get the segments of the test ID that correspond - to the module and class that it belongs to. - """ - self.assertEqual( - ['foo.bar', 'baz'], - self.result._getPreludeSegments('foo.bar.baz.qux')) - self.assertEqual( - ['foo', 'bar'], - self.result._getPreludeSegments('foo.bar.baz')) - self.assertEqual( - ['foo'], - self.result._getPreludeSegments('foo.bar')) - self.assertEqual([], self.result._getPreludeSegments('foo')) - - - def test_groupResults(self): - """ - If two different tests have the same error, L{Reporter._groupResults} - includes them together in one of the tuples in the list it returns. - """ - try: - raise RuntimeError('foo') - except RuntimeError: - self.result.addError(self, sys.exc_info()) - self.result.addError(self.test, sys.exc_info()) - try: - raise RuntimeError('bar') - except RuntimeError: - extra = sample.FooTest('test_bar') - self.result.addError(extra, sys.exc_info()) - self.result.done() - grouped = self.result._groupResults( - self.result.errors, self.result._formatFailureTraceback) - self.assertEqual(grouped[0][1], [self, self.test]) - self.assertEqual(grouped[1][1], [extra]) - - - def test_printResults(self): - """ - L{Reporter._printResults} uses the results list and formatter callable - passed to it to produce groups of results to write to its output stream. - """ - def formatter(n): - return str(n) + '\n' - first = sample.FooTest('test_foo') - second = sample.FooTest('test_bar') - third = sample.PyunitTest('test_foo') - self.result._printResults( - 'FOO', [(first, 1), (second, 1), (third, 2)], formatter) - self.assertEqual( - self.stream.getvalue(), - "%(double separator)s\n" - "FOO\n" - "1\n" - "\n" - "%(first)s\n" - "%(second)s\n" - "%(double separator)s\n" - "FOO\n" - "2\n" - "\n" - "%(third)s\n" % { - 'double separator': self.result._doubleSeparator, - 'first': first.id(), - 'second': second.id(), - 'third': third.id(), - }) - - - -class TestReporterInterface(unittest.TestCase): - """ - Tests for the bare interface of a trial reporter. - - Subclass this test case and provide a different 'resultFactory' to test - that a particular reporter implementation will work with the rest of - Trial. - - @cvar resultFactory: A callable that returns a reporter to be tested. The - callable must take the same parameters as L{reporter.Reporter}. - """ - - resultFactory = reporter.Reporter - - def setUp(self): - self.test = sample.FooTest('test_foo') - self.stream = StringIO.StringIO() - self.publisher = log.LogPublisher() - self.result = self.resultFactory(self.stream, publisher=self.publisher) - - - def test_shouldStopInitiallyFalse(self): - """ - shouldStop is False to begin with. - """ - self.assertEqual(False, self.result.shouldStop) - - - def test_shouldStopTrueAfterStop(self): - """ - shouldStop becomes True soon as someone calls stop(). - """ - self.result.stop() - self.assertEqual(True, self.result.shouldStop) - - - def test_wasSuccessfulInitiallyTrue(self): - """ - wasSuccessful() is True when there have been no results reported. - """ - self.assertEqual(True, self.result.wasSuccessful()) - - - def test_wasSuccessfulTrueAfterSuccesses(self): - """ - wasSuccessful() is True when there have been only successes, False - otherwise. - """ - self.result.addSuccess(self.test) - self.assertEqual(True, self.result.wasSuccessful()) - - - def test_wasSuccessfulFalseAfterErrors(self): - """ - wasSuccessful() becomes False after errors have been reported. - """ - try: - 1 / 0 - except ZeroDivisionError: - self.result.addError(self.test, sys.exc_info()) - self.assertEqual(False, self.result.wasSuccessful()) - - - def test_wasSuccessfulFalseAfterFailures(self): - """ - wasSuccessful() becomes False after failures have been reported. - """ - try: - self.fail("foo") - except self.failureException: - self.result.addFailure(self.test, sys.exc_info()) - self.assertEqual(False, self.result.wasSuccessful()) - - - -class TestReporter(TestReporterInterface): - """ - Tests for the base L{reporter.Reporter} class. - """ - - def setUp(self): - TestReporterInterface.setUp(self) - self._timer = 0 - self.result._getTime = self._getTime - - - def _getTime(self): - self._timer += 1 - return self._timer - - - def test_startStop(self): - self.result.startTest(self.test) - self.result.stopTest(self.test) - self.assertTrue(self.result._lastTime > 0) - self.assertEqual(self.result.testsRun, 1) - self.assertEqual(self.result.wasSuccessful(), True) - - - def test_brokenStream(self): - """ - Test that the reporter safely writes to its stream. - """ - result = self.resultFactory(stream=BrokenStream(self.stream)) - result._writeln("Hello") - self.assertEqual(self.stream.getvalue(), 'Hello\n') - self.stream.truncate(0) - result._writeln("Hello %s!", 'World') - self.assertEqual(self.stream.getvalue(), 'Hello World!\n') - - - def test_printErrorsDeprecated(self): - """ - L{IReporter.printErrors} was deprecated in Twisted 8.0. - """ - def f(): - self.result.printErrors() - self.assertWarns( - DeprecationWarning, "printErrors is deprecated in Twisted 8.0.", - __file__, f) - - - def test_printSummaryDeprecated(self): - """ - L{IReporter.printSummary} was deprecated in Twisted 8.0. - """ - def f(): - self.result.printSummary() - self.assertWarns( - DeprecationWarning, "printSummary is deprecated in Twisted 8.0.", - __file__, f) - - - def test_writeDeprecated(self): - """ - L{IReporter.write} was deprecated in Twisted 8.0. - """ - def f(): - self.result.write("") - self.assertWarns( - DeprecationWarning, "write is deprecated in Twisted 8.0.", - __file__, f) - - - def test_writelnDeprecated(self): - """ - L{IReporter.writeln} was deprecated in Twisted 8.0. - """ - def f(): - self.result.writeln("") - self.assertWarns( - DeprecationWarning, "writeln is deprecated in Twisted 8.0.", - __file__, f) - - - def test_separatorDeprecated(self): - """ - L{IReporter.separator} was deprecated in Twisted 8.0. - """ - def f(): - return self.result.separator - self.assertWarns( - DeprecationWarning, "separator is deprecated in Twisted 8.0.", - __file__, f) - - - def test_streamDeprecated(self): - """ - L{IReporter.stream} was deprecated in Twisted 8.0. - """ - def f(): - return self.result.stream - self.assertWarns( - DeprecationWarning, "stream is deprecated in Twisted 8.0.", - __file__, f) - - - def test_upDownErrorDeprecated(self): - """ - L{IReporter.upDownError} was deprecated in Twisted 8.0. - """ - def f(): - self.result.upDownError(None, None, None, None) - self.assertWarns( - DeprecationWarning, "upDownError is deprecated in Twisted 8.0.", - __file__, f) - - - def test_warning(self): - """ - L{reporter.Reporter} observes warnings emitted by the Twisted log - system and writes them to its output stream. - """ - message = RuntimeWarning("some warning text") - category = 'exceptions.RuntimeWarning' - filename = "path/to/some/file.py" - lineno = 71 - self.publisher.msg( - warning=message, category=category, - filename=filename, lineno=lineno) - self.assertEqual( - self.stream.getvalue(), - "%s:%d: %s: %s\n" % ( - filename, lineno, category.split('.')[-1], message)) - - - def test_duplicateWarningSuppressed(self): - """ - A warning emitted twice within a single test is only written to the - stream once. - """ - # Emit the warning and assert that it shows up - self.test_warning() - # Emit the warning again and assert that the stream still only has one - # warning on it. - self.test_warning() - - - def test_warningEmittedForNewTest(self): - """ - A warning emitted again after a new test has started is written to the - stream again. - """ - test = self.__class__('test_warningEmittedForNewTest') - self.result.startTest(test) - - # Clear whatever startTest wrote to the stream - self.stream.seek(0) - self.stream.truncate() - - # Emit a warning (and incidentally, assert that it was emitted) - self.test_warning() - - # Clean up from the first warning to simplify the rest of the - # assertions. - self.stream.seek(0) - self.stream.truncate() - - # Stop the first test and start another one (it just happens to be the - # same one, but that doesn't matter) - self.result.stopTest(test) - self.result.startTest(test) - - # Clean up the stopTest/startTest output - self.stream.seek(0) - self.stream.truncate() - - # Emit the warning again and make sure it shows up - self.test_warning() - - - def test_stopObserving(self): - """ - L{reporter.Reporter} stops observing log events when its C{done} method - is called. - """ - self.result.done() - self.stream.seek(0) - self.stream.truncate() - self.publisher.msg( - warning=RuntimeWarning("some message"), - category='exceptions.RuntimeWarning', - filename="file/name.py", lineno=17) - self.assertEqual(self.stream.getvalue(), "") - - - -class TestSafeStream(unittest.TestCase): - def test_safe(self): - """ - Test that L{reporter.SafeStream} successfully write to its original - stream even if an interrupt happens during the write. - """ - stream = StringIO.StringIO() - broken = BrokenStream(stream) - safe = reporter.SafeStream(broken) - safe.write("Hello") - self.assertEqual(stream.getvalue(), "Hello") - - - -class TestSubunitReporter(TestReporterInterface): - """ - Tests for the subunit reporter. - - This just tests that the subunit reporter implements the basic interface. - """ - - resultFactory = reporter.SubunitReporter - - - def setUp(self): - if reporter.TestProtocolClient is None: - raise SkipTest( - "Subunit not installed, cannot test SubunitReporter") - TestReporterInterface.setUp(self) - - - def assertForwardsToSubunit(self, methodName, *args, **kwargs): - """ - Assert that 'methodName' on L{SubunitReporter} forwards to the - equivalent method on subunit. - - Checks that the return value from subunit is returned from the - L{SubunitReporter} and that the reporter writes the same data to its - stream as subunit does to its own. - - Assumes that the method on subunit has the same name as the method on - L{SubunitReporter}. - """ - stream = StringIO.StringIO() - subunitClient = reporter.TestProtocolClient(stream) - subunitReturn = getattr(subunitClient, methodName)(*args, **kwargs) - subunitOutput = stream.getvalue() - reporterReturn = getattr(self.result, methodName)(*args, **kwargs) - self.assertEqual(subunitReturn, reporterReturn) - self.assertEqual(subunitOutput, self.stream.getvalue()) - - - def removeMethod(self, klass, methodName): - """ - Remove 'methodName' from 'klass'. - - If 'klass' does not have a method named 'methodName', then - 'removeMethod' succeeds silently. - - If 'klass' does have a method named 'methodName', then it is removed - using delattr. Also, methods of the same name are removed from all - base classes of 'klass', thus removing the method entirely. - - @param klass: The class to remove the method from. - @param methodName: The name of the method to remove. - """ - method = getattr(klass, methodName, None) - if method is None: - return - for base in getmro(klass): - try: - delattr(base, methodName) - except (AttributeError, TypeError): - break - else: - self.addCleanup(setattr, base, methodName, method) - - - def test_subunitWithoutAddExpectedFailureInstalled(self): - """ - Some versions of subunit don't have "addExpectedFailure". For these - versions, we report expected failures as successes. - """ - self.removeMethod(reporter.TestProtocolClient, 'addExpectedFailure') - try: - 1 / 0 - except ZeroDivisionError: - self.result.addExpectedFailure(self.test, sys.exc_info(), "todo") - expectedFailureOutput = self.stream.getvalue() - self.stream.truncate(0) - self.result.addSuccess(self.test) - successOutput = self.stream.getvalue() - self.assertEqual(successOutput, expectedFailureOutput) - - - def test_subunitWithoutAddSkipInstalled(self): - """ - Some versions of subunit don't have "addSkip". For these versions, we - report skips as successes. - """ - self.removeMethod(reporter.TestProtocolClient, 'addSkip') - self.result.addSkip(self.test, "reason") - skipOutput = self.stream.getvalue() - self.stream.truncate(0) - self.result.addSuccess(self.test) - successOutput = self.stream.getvalue() - self.assertEqual(successOutput, skipOutput) - - - def test_addExpectedFailurePassedThrough(self): - """ - Some versions of subunit have "addExpectedFailure". For these - versions, when we call 'addExpectedFailure' on the test result, we - pass the error and test through to the subunit client. - """ - addExpectedFailureCalls = [] - def addExpectedFailure(test, error): - addExpectedFailureCalls.append((test, error)) - - # Provide our own addExpectedFailure, whether or not the locally - # installed subunit has addExpectedFailure. - self.result._subunit.addExpectedFailure = addExpectedFailure - try: - 1 / 0 - except ZeroDivisionError: - exc_info = sys.exc_info() - self.result.addExpectedFailure(self.test, exc_info, 'todo') - self.assertEqual(addExpectedFailureCalls, [(self.test, exc_info)]) - - - def test_addSkipSendsSubunitAddSkip(self): - """ - Some versions of subunit have "addSkip". For these versions, when we - call 'addSkip' on the test result, we pass the test and reason through - to the subunit client. - """ - addSkipCalls = [] - def addSkip(test, reason): - addSkipCalls.append((test, reason)) - - # Provide our own addSkip, whether or not the locally-installed - # subunit has addSkip. - self.result._subunit.addSkip = addSkip - self.result.addSkip(self.test, 'reason') - self.assertEqual(addSkipCalls, [(self.test, 'reason')]) - - - def test_doneDoesNothing(self): - """ - The subunit reporter doesn't need to print out a summary -- the stream - of results is everything. Thus, done() does nothing. - """ - self.result.done() - self.assertEqual('', self.stream.getvalue()) - - - def test_startTestSendsSubunitStartTest(self): - """ - SubunitReporter.startTest() sends the subunit 'startTest' message. - """ - self.assertForwardsToSubunit('startTest', self.test) - - - def test_stopTestSendsSubunitStopTest(self): - """ - SubunitReporter.stopTest() sends the subunit 'stopTest' message. - """ - self.assertForwardsToSubunit('stopTest', self.test) - - - def test_addSuccessSendsSubunitAddSuccess(self): - """ - SubunitReporter.addSuccess() sends the subunit 'addSuccess' message. - """ - self.assertForwardsToSubunit('addSuccess', self.test) - - - def test_addErrorSendsSubunitAddError(self): - """ - SubunitReporter.addError() sends the subunit 'addError' message. - """ - try: - 1 / 0 - except ZeroDivisionError: - error = sys.exc_info() - self.assertForwardsToSubunit('addError', self.test, error) - - - def test_addFailureSendsSubunitAddFailure(self): - """ - SubunitReporter.addFailure() sends the subunit 'addFailure' message. - """ - try: - self.fail('hello') - except self.failureException: - failure = sys.exc_info() - self.assertForwardsToSubunit('addFailure', self.test, failure) - - - def test_addUnexpectedSuccessSendsSubunitAddSuccess(self): - """ - SubunitReporter.addFailure() sends the subunit 'addSuccess' message, - since subunit doesn't model unexpected success. - """ - stream = StringIO.StringIO() - subunitClient = reporter.TestProtocolClient(stream) - subunitClient.addSuccess(self.test) - subunitOutput = stream.getvalue() - self.result.addUnexpectedSuccess(self.test, 'todo') - self.assertEqual(subunitOutput, self.stream.getvalue()) - - - def test_loadTimeErrors(self): - """ - Load-time errors are reported like normal errors. - """ - test = runner.TestLoader().loadByName('doesntexist') - test.run(self.result) - output = self.stream.getvalue() - # Just check that 'doesntexist' is in the output, rather than - # assembling the expected stack trace. - self.assertIn('doesntexist', output) - - - -class TestSubunitReporterNotInstalled(unittest.TestCase): - """ - Test behaviour when the subunit reporter is not installed. - """ - - def test_subunitNotInstalled(self): - """ - If subunit is not installed, TestProtocolClient will be None, and - SubunitReporter will raise an error when you try to construct it. - """ - stream = StringIO.StringIO() - self.patch(reporter, 'TestProtocolClient', None) - e = self.assertRaises(Exception, reporter.SubunitReporter, stream) - self.assertEqual("Subunit not available", str(e)) - - - -class TestTimingReporter(TestReporter): - resultFactory = reporter.TimingTextReporter - - - -class LoggingReporter(reporter.Reporter): - """ - Simple reporter that stores the last test that was passed to it. - """ - - def __init__(self, *args, **kwargs): - reporter.Reporter.__init__(self, *args, **kwargs) - self.test = None - - def addError(self, test, error): - self.test = test - - def addExpectedFailure(self, test, failure, todo): - self.test = test - - def addFailure(self, test, failure): - self.test = test - - def addSkip(self, test, skip): - self.test = test - - def addUnexpectedSuccess(self, test, todo): - self.test = test - - def startTest(self, test): - self.test = test - - def stopTest(self, test): - self.test = test - - - -class TestAdaptedReporter(unittest.TestCase): - """ - L{reporter._AdaptedReporter} is a reporter wrapper that wraps all of the - tests it receives before passing them on to the original reporter. - """ - - def setUp(self): - self.wrappedResult = self.getWrappedResult() - - - def _testAdapter(self, test): - return test.id() - - - def assertWrapped(self, wrappedResult, test): - self.assertEqual(wrappedResult._originalReporter.test, self._testAdapter(test)) - - - def getFailure(self, exceptionInstance): - """ - Return a L{Failure} from raising the given exception. - - @param exceptionInstance: The exception to raise. - @return: L{Failure} - """ - try: - raise exceptionInstance - except: - return Failure() - - - def getWrappedResult(self): - result = LoggingReporter() - return reporter._AdaptedReporter(result, self._testAdapter) - - - def test_addError(self): - """ - C{addError} wraps its test with the provided adapter. - """ - self.wrappedResult.addError(self, self.getFailure(RuntimeError())) - self.assertWrapped(self.wrappedResult, self) - - - def test_addFailure(self): - """ - C{addFailure} wraps its test with the provided adapter. - """ - self.wrappedResult.addFailure(self, self.getFailure(AssertionError())) - self.assertWrapped(self.wrappedResult, self) - - - def test_addSkip(self): - """ - C{addSkip} wraps its test with the provided adapter. - """ - self.wrappedResult.addSkip(self, self.getFailure(SkipTest('no reason'))) - self.assertWrapped(self.wrappedResult, self) - - - def test_startTest(self): - """ - C{startTest} wraps its test with the provided adapter. - """ - self.wrappedResult.startTest(self) - self.assertWrapped(self.wrappedResult, self) - - - def test_stopTest(self): - """ - C{stopTest} wraps its test with the provided adapter. - """ - self.wrappedResult.stopTest(self) - self.assertWrapped(self.wrappedResult, self) - - - def test_addExpectedFailure(self): - """ - C{addExpectedFailure} wraps its test with the provided adapter. - """ - self.wrappedResult.addExpectedFailure( - self, self.getFailure(RuntimeError()), Todo("no reason")) - self.assertWrapped(self.wrappedResult, self) - - - def test_addUnexpectedSuccess(self): - """ - C{addUnexpectedSuccess} wraps its test with the provided adapter. - """ - self.wrappedResult.addUnexpectedSuccess(self, Todo("no reason")) - self.assertWrapped(self.wrappedResult, self) - - - -class FakeStream(object): - """ - A fake stream which C{isatty} method returns some predictable. - - @ivar tty: returned value of C{isatty}. - @type tty: C{bool} - """ - - def __init__(self, tty=True): - self.tty = tty - - - def isatty(self): - return self.tty - - - -class AnsiColorizerTests(unittest.TestCase): - """ - Tests for L{reporter._AnsiColorizer}. - """ - - def setUp(self): - self.savedModules = sys.modules.copy() - - - def tearDown(self): - sys.modules.clear() - sys.modules.update(self.savedModules) - - - def test_supportedStdOutTTY(self): - """ - L{reporter._AnsiColorizer.supported} returns C{False} if the given - stream is not a TTY. - """ - self.assertFalse(reporter._AnsiColorizer.supported(FakeStream(False))) - - - def test_supportedNoCurses(self): - """ - L{reporter._AnsiColorizer.supported} returns C{False} if the curses - module can't be imported. - """ - sys.modules['curses'] = None - self.assertFalse(reporter._AnsiColorizer.supported(FakeStream())) - - - def test_supportedSetupTerm(self): - """ - L{reporter._AnsiColorizer.supported} returns C{True} if - C{curses.tigetnum} returns more than 2 supported colors. It only tries - to call C{curses.setupterm} if C{curses.tigetnum} previously failed - with a C{curses.error}. - """ - class fakecurses(object): - error = RuntimeError - setUp = 0 - - def setupterm(self): - self.setUp += 1 - - def tigetnum(self, value): - if self.setUp: - return 3 - else: - raise self.error() - - sys.modules['curses'] = fakecurses() - self.assertTrue(reporter._AnsiColorizer.supported(FakeStream())) - self.assertTrue(reporter._AnsiColorizer.supported(FakeStream())) - - self.assertEqual(sys.modules['curses'].setUp, 1) - - - def test_supportedTigetNumWrongError(self): - """ - L{reporter._AnsiColorizer.supported} returns C{False} and doesn't try - to call C{curses.setupterm} if C{curses.tigetnum} returns something - different than C{curses.error}. - """ - class fakecurses(object): - error = RuntimeError - - def tigetnum(self, value): - raise ValueError() - - sys.modules['curses'] = fakecurses() - self.assertFalse(reporter._AnsiColorizer.supported(FakeStream())) - - - def test_supportedTigetNumNotEnoughColor(self): - """ - L{reporter._AnsiColorizer.supported} returns C{False} if - C{curses.tigetnum} returns less than 2 supported colors. - """ - class fakecurses(object): - error = RuntimeError - - def tigetnum(self, value): - return 1 - - sys.modules['curses'] = fakecurses() - self.assertFalse(reporter._AnsiColorizer.supported(FakeStream())) - - - def test_supportedTigetNumErrors(self): - """ - L{reporter._AnsiColorizer.supported} returns C{False} if - C{curses.tigetnum} raises an error, and calls C{curses.setupterm} once. - """ - class fakecurses(object): - error = RuntimeError - setUp = 0 - - def setupterm(self): - self.setUp += 1 - - def tigetnum(self, value): - raise self.error() - - sys.modules['curses'] = fakecurses() - self.assertFalse(reporter._AnsiColorizer.supported(FakeStream())) - self.assertEqual(sys.modules['curses'].setUp, 1) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_runner.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_runner.py deleted file mode 100755 index 12fcc866..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_runner.py +++ /dev/null @@ -1,1034 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. -# -# Maintainer: Jonathan Lange -# Author: Robert Collins - - -import StringIO, os, sys -from zope.interface import implements -from zope.interface.verify import verifyObject - -from twisted.trial.itrial import IReporter, ITestCase -from twisted.trial import unittest, runner, reporter, util -from twisted.python import failure, log, reflect, filepath -from twisted.python.filepath import FilePath -from twisted.scripts import trial -from twisted.plugins import twisted_trial -from twisted import plugin -from twisted.internet import defer - - -pyunit = __import__('unittest') - - -class CapturingDebugger(object): - - def __init__(self): - self._calls = [] - - def runcall(self, *args, **kwargs): - self._calls.append('runcall') - args[0](*args[1:], **kwargs) - - - -class CapturingReporter(object): - """ - Reporter that keeps a log of all actions performed on it. - """ - - implements(IReporter) - - stream = None - tbformat = None - args = None - separator = None - testsRun = None - - def __init__(self, stream=None, tbformat=None, rterrors=None, - publisher=None): - """ - Create a capturing reporter. - """ - self._calls = [] - self.shouldStop = False - self._stream = stream - self._tbformat = tbformat - self._rterrors = rterrors - self._publisher = publisher - - - def startTest(self, method): - """ - Report the beginning of a run of a single test method - @param method: an object that is adaptable to ITestMethod - """ - self._calls.append('startTest') - - - def stopTest(self, method): - """ - Report the status of a single test method - @param method: an object that is adaptable to ITestMethod - """ - self._calls.append('stopTest') - - - def cleanupErrors(self, errs): - """called when the reactor has been left in a 'dirty' state - @param errs: a list of L{twisted.python.failure.Failure}s - """ - self._calls.append('cleanupError') - - - def addSuccess(self, test): - self._calls.append('addSuccess') - - - def done(self): - """ - Do nothing. These tests don't care about done. - """ - - - -class TrialRunnerTestsMixin: - """ - Mixin defining tests for L{runner.TrialRunner}. - """ - def tearDown(self): - self.runner._tearDownLogFile() - - - def test_empty(self): - """ - Empty test method, used by the other tests. - """ - - - def _getObservers(self): - return log.theLogPublisher.observers - - - def test_addObservers(self): - """ - Any log system observers L{TrialRunner.run} adds are removed by the - time it returns. - """ - originalCount = len(self._getObservers()) - self.runner.run(self.test) - newCount = len(self._getObservers()) - self.assertEqual(newCount, originalCount) - - - def test_logFileAlwaysActive(self): - """ - Test that a new file is opened on each run. - """ - oldSetUpLogFile = self.runner._setUpLogFile - l = [] - def setUpLogFile(): - oldSetUpLogFile() - l.append(self.runner._logFileObserver) - self.runner._setUpLogFile = setUpLogFile - self.runner.run(self.test) - self.runner.run(self.test) - self.assertEqual(len(l), 2) - self.failIf(l[0] is l[1], "Should have created a new file observer") - - - def test_logFileGetsClosed(self): - """ - Test that file created is closed during the run. - """ - oldSetUpLogFile = self.runner._setUpLogFile - l = [] - def setUpLogFile(): - oldSetUpLogFile() - l.append(self.runner._logFileObject) - self.runner._setUpLogFile = setUpLogFile - self.runner.run(self.test) - self.assertEqual(len(l), 1) - self.failUnless(l[0].closed) - - - -class TestTrialRunner(TrialRunnerTestsMixin, unittest.TestCase): - """ - Tests for L{runner.TrialRunner} with the feature to turn unclean errors - into warnings disabled. - """ - def setUp(self): - self.stream = StringIO.StringIO() - self.runner = runner.TrialRunner(CapturingReporter, stream=self.stream) - self.test = TestTrialRunner('test_empty') - - - def test_publisher(self): - """ - The reporter constructed by L{runner.TrialRunner} is passed - L{twisted.python.log} as the value for the C{publisher} parameter. - """ - result = self.runner._makeResult() - self.assertIdentical(result._publisher, log) - - - -class TrialRunnerWithUncleanWarningsReporter(TrialRunnerTestsMixin, - unittest.TestCase): - """ - Tests for the TrialRunner's interaction with an unclean-error suppressing - reporter. - """ - - def setUp(self): - self.stream = StringIO.StringIO() - self.runner = runner.TrialRunner(CapturingReporter, stream=self.stream, - uncleanWarnings=True) - self.test = TestTrialRunner('test_empty') - - - -class DryRunMixin(object): - - suppress = [util.suppress( - category=DeprecationWarning, - message="Test visitors deprecated in Twisted 8.0")] - - - def setUp(self): - self.log = [] - self.stream = StringIO.StringIO() - self.runner = runner.TrialRunner(CapturingReporter, - runner.TrialRunner.DRY_RUN, - stream=self.stream) - self.makeTestFixtures() - - - def makeTestFixtures(self): - """ - Set C{self.test} and C{self.suite}, where C{self.suite} is an empty - TestSuite. - """ - - - def test_empty(self): - """ - If there are no tests, the reporter should not receive any events to - report. - """ - result = self.runner.run(runner.TestSuite()) - self.assertEqual(result._calls, []) - - - def test_singleCaseReporting(self): - """ - If we are running a single test, check the reporter starts, passes and - then stops the test during a dry run. - """ - result = self.runner.run(self.test) - self.assertEqual(result._calls, ['startTest', 'addSuccess', 'stopTest']) - - - def test_testsNotRun(self): - """ - When we are doing a dry run, the tests should not actually be run. - """ - self.runner.run(self.test) - self.assertEqual(self.log, []) - - - -class DryRunTest(DryRunMixin, unittest.TestCase): - """ - Check that 'dry run' mode works well with Trial tests. - """ - def makeTestFixtures(self): - class MockTest(unittest.TestCase): - def test_foo(test): - self.log.append('test_foo') - self.test = MockTest('test_foo') - self.suite = runner.TestSuite() - - - -class PyUnitDryRunTest(DryRunMixin, unittest.TestCase): - """ - Check that 'dry run' mode works well with stdlib unittest tests. - """ - def makeTestFixtures(self): - class PyunitCase(pyunit.TestCase): - def test_foo(self): - pass - self.test = PyunitCase('test_foo') - self.suite = pyunit.TestSuite() - - - -class TestRunner(unittest.TestCase): - def setUp(self): - self.config = trial.Options() - # whitebox hack a reporter in, because plugins are CACHED and will - # only reload if the FILE gets changed. - - parts = reflect.qual(CapturingReporter).split('.') - package = '.'.join(parts[:-1]) - klass = parts[-1] - plugins = [twisted_trial._Reporter( - "Test Helper Reporter", - package, - description="Utility for unit testing.", - longOpt="capturing", - shortOpt=None, - klass=klass)] - - - # XXX There should really be a general way to hook the plugin system - # for tests. - def getPlugins(iface, *a, **kw): - self.assertEqual(iface, IReporter) - return plugins + list(self.original(iface, *a, **kw)) - - self.original = plugin.getPlugins - plugin.getPlugins = getPlugins - - self.standardReport = ['startTest', 'addSuccess', 'stopTest', - 'startTest', 'addSuccess', 'stopTest', - 'startTest', 'addSuccess', 'stopTest', - 'startTest', 'addSuccess', 'stopTest', - 'startTest', 'addSuccess', 'stopTest', - 'startTest', 'addSuccess', 'stopTest', - 'startTest', 'addSuccess', 'stopTest', - 'startTest', 'addSuccess', 'stopTest', - 'startTest', 'addSuccess', 'stopTest', - 'startTest', 'addSuccess', 'stopTest'] - - - def tearDown(self): - plugin.getPlugins = self.original - - - def parseOptions(self, args): - self.config.parseOptions(args) - - - def getRunner(self): - r = trial._makeRunner(self.config) - r.stream = StringIO.StringIO() - # XXX The runner should always take care of cleaning this up itself. - # It's not clear why this is necessary. The runner always tears down - # its log file. - self.addCleanup(r._tearDownLogFile) - # XXX The runner should always take care of cleaning this up itself as - # well. It's necessary because TrialRunner._setUpTestdir might raise - # an exception preventing Reporter.done from being run, leaving the - # observer added by Reporter.__init__ still present in the system. - # Something better needs to happen inside - # TrialRunner._runWithoutDecoration to remove the need for this cludge. - r._log = log.LogPublisher() - return r - - - def test_runner_can_get_reporter(self): - self.parseOptions([]) - result = self.config['reporter'] - runner = self.getRunner() - self.assertEqual(result, runner._makeResult().__class__) - - - def test_runner_get_result(self): - self.parseOptions([]) - runner = self.getRunner() - result = runner._makeResult() - self.assertEqual(result.__class__, self.config['reporter']) - - - def test_uncleanWarningsOffByDefault(self): - """ - By default Trial sets the 'uncleanWarnings' option on the runner to - False. This means that dirty reactor errors will be reported as - errors. See L{test_reporter.TestDirtyReactor}. - """ - self.parseOptions([]) - runner = self.getRunner() - self.assertNotIsInstance(runner._makeResult(), - reporter.UncleanWarningsReporterWrapper) - - - def test_getsUncleanWarnings(self): - """ - Specifying '--unclean-warnings' on the trial command line will cause - reporters to be wrapped in a device which converts unclean errors to - warnings. See L{test_reporter.TestDirtyReactor} for implications. - """ - self.parseOptions(['--unclean-warnings']) - runner = self.getRunner() - self.assertIsInstance(runner._makeResult(), - reporter.UncleanWarningsReporterWrapper) - - - def test_runner_working_directory(self): - self.parseOptions(['--temp-directory', 'some_path']) - runner = self.getRunner() - self.assertEqual(runner.workingDirectory, 'some_path') - - - def test_concurrentImplicitWorkingDirectory(self): - """ - If no working directory is explicitly specified and the default - working directory is in use by another runner, L{TrialRunner.run} - selects a different default working directory to use. - """ - self.parseOptions([]) - - # Make sure we end up with the same working directory after this test - # as we had before it. - self.addCleanup(os.chdir, os.getcwd()) - - # Make a new directory and change into it. This isolates us from state - # that other tests might have dumped into this process's temp - # directory. - runDirectory = FilePath(self.mktemp()) - runDirectory.makedirs() - os.chdir(runDirectory.path) - - firstRunner = self.getRunner() - secondRunner = self.getRunner() - - where = {} - - class ConcurrentCase(unittest.TestCase): - def test_first(self): - """ - Start a second test run which will have a default working - directory which is the same as the working directory of the - test run already in progress. - """ - # Change the working directory to the value it had before this - # test suite was started. - where['concurrent'] = subsequentDirectory = os.getcwd() - os.chdir(runDirectory.path) - self.addCleanup(os.chdir, subsequentDirectory) - - secondRunner.run(ConcurrentCase('test_second')) - - def test_second(self): - """ - Record the working directory for later analysis. - """ - where['record'] = os.getcwd() - - result = firstRunner.run(ConcurrentCase('test_first')) - bad = result.errors + result.failures - if bad: - self.fail(bad[0][1]) - self.assertEqual( - where, { - 'concurrent': runDirectory.child('_trial_temp').path, - 'record': runDirectory.child('_trial_temp-1').path}) - - - def test_concurrentExplicitWorkingDirectory(self): - """ - If a working directory which is already in use is explicitly specified, - L{TrialRunner.run} raises L{_WorkingDirectoryBusy}. - """ - self.parseOptions(['--temp-directory', os.path.abspath(self.mktemp())]) - - initialDirectory = os.getcwd() - self.addCleanup(os.chdir, initialDirectory) - - firstRunner = self.getRunner() - secondRunner = self.getRunner() - - class ConcurrentCase(unittest.TestCase): - def test_concurrent(self): - """ - Try to start another runner in the same working directory and - assert that it raises L{_WorkingDirectoryBusy}. - """ - self.assertRaises( - util._WorkingDirectoryBusy, - secondRunner.run, ConcurrentCase('test_failure')) - - def test_failure(self): - """ - Should not be called, always fails. - """ - self.fail("test_failure should never be called.") - - result = firstRunner.run(ConcurrentCase('test_concurrent')) - bad = result.errors + result.failures - if bad: - self.fail(bad[0][1]) - - - def test_runner_normal(self): - self.parseOptions(['--temp-directory', self.mktemp(), - '--reporter', 'capturing', - 'twisted.trial.test.sample']) - my_runner = self.getRunner() - loader = runner.TestLoader() - suite = loader.loadByName('twisted.trial.test.sample', True) - result = my_runner.run(suite) - self.assertEqual(self.standardReport, result._calls) - - - def test_runner_debug(self): - self.parseOptions(['--reporter', 'capturing', - '--debug', 'twisted.trial.test.sample']) - my_runner = self.getRunner() - debugger = CapturingDebugger() - def get_debugger(): - return debugger - my_runner._getDebugger = get_debugger - loader = runner.TestLoader() - suite = loader.loadByName('twisted.trial.test.sample', True) - result = my_runner.run(suite) - self.assertEqual(self.standardReport, result._calls) - self.assertEqual(['runcall'], debugger._calls) - - - -class RemoveSafelyTests(unittest.TestCase): - """ - Tests for L{_removeSafely}. - """ - def test_removeSafelyNoTrialMarker(self): - """ - If a path doesn't contain a node named C{"_trial_marker"}, that path is - not removed by L{runner._removeSafely} and a L{runner._NoTrialMarker} - exception is raised instead. - """ - directory = self.mktemp() - os.mkdir(directory) - dirPath = filepath.FilePath(directory) - self.assertRaises(util._NoTrialMarker, util._removeSafely, dirPath) - - - def test_removeSafelyRemoveFailsMoveSucceeds(self): - """ - If an L{OSError} is raised while removing a path in - L{runner._removeSafely}, an attempt is made to move the path to a new - name. - """ - def dummyRemove(): - """ - Raise an C{OSError} to emulate the branch of L{runner._removeSafely} - in which path removal fails. - """ - raise OSError() - - # Patch stdout so we can check the print statements in _removeSafely - out = StringIO.StringIO() - self.patch(sys, 'stdout', out) - - # Set up a trial directory with a _trial_marker - directory = self.mktemp() - os.mkdir(directory) - dirPath = filepath.FilePath(directory) - dirPath.child('_trial_marker').touch() - # Ensure that path.remove() raises an OSError - dirPath.remove = dummyRemove - - util._removeSafely(dirPath) - self.assertIn("could not remove FilePath", out.getvalue()) - - - def test_removeSafelyRemoveFailsMoveFails(self): - """ - If an L{OSError} is raised while removing a path in - L{runner._removeSafely}, an attempt is made to move the path to a new - name. If that attempt fails, the L{OSError} is re-raised. - """ - def dummyRemove(): - """ - Raise an C{OSError} to emulate the branch of L{runner._removeSafely} - in which path removal fails. - """ - raise OSError("path removal failed") - - def dummyMoveTo(path): - """ - Raise an C{OSError} to emulate the branch of L{runner._removeSafely} - in which path movement fails. - """ - raise OSError("path movement failed") - - # Patch stdout so we can check the print statements in _removeSafely - out = StringIO.StringIO() - self.patch(sys, 'stdout', out) - - # Set up a trial directory with a _trial_marker - directory = self.mktemp() - os.mkdir(directory) - dirPath = filepath.FilePath(directory) - dirPath.child('_trial_marker').touch() - - # Ensure that path.remove() and path.moveTo() both raise OSErrors - dirPath.remove = dummyRemove - dirPath.moveTo = dummyMoveTo - - error = self.assertRaises(OSError, util._removeSafely, dirPath) - self.assertEqual(str(error), "path movement failed") - self.assertIn("could not remove FilePath", out.getvalue()) - - - -class TestTrialSuite(unittest.TestCase): - - def test_imports(self): - # FIXME, HTF do you test the reactor can be cleaned up ?!!! - from twisted.trial.runner import TrialSuite - - - - -class TestUntilFailure(unittest.TestCase): - class FailAfter(unittest.TestCase): - """ - A test case that fails when run 3 times in a row. - """ - count = [] - def test_foo(self): - self.count.append(None) - if len(self.count) == 3: - self.fail('Count reached 3') - - - def setUp(self): - TestUntilFailure.FailAfter.count = [] - self.test = TestUntilFailure.FailAfter('test_foo') - self.stream = StringIO.StringIO() - self.runner = runner.TrialRunner(reporter.Reporter, stream=self.stream) - - - def test_runUntilFailure(self): - """ - Test that the runUntilFailure method of the runner actually fail after - a few runs. - """ - result = self.runner.runUntilFailure(self.test) - self.assertEqual(result.testsRun, 1) - self.failIf(result.wasSuccessful()) - self.assertEqual(self._getFailures(result), 1) - - - def _getFailures(self, result): - """ - Get the number of failures that were reported to a result. - """ - return len(result.failures) - - - def test_runUntilFailureDecorate(self): - """ - C{runUntilFailure} doesn't decorate the tests uselessly: it does it one - time when run starts, but not at each turn. - """ - decorated = [] - def decorate(test, interface): - decorated.append((test, interface)) - return test - self.patch(unittest, "decorate", decorate) - result = self.runner.runUntilFailure(self.test) - self.assertEqual(result.testsRun, 1) - - self.assertEqual(len(decorated), 1) - self.assertEqual(decorated, [(self.test, ITestCase)]) - - - def test_runUntilFailureForceGCDecorate(self): - """ - C{runUntilFailure} applies the force-gc decoration after the standard - L{ITestCase} decoration, but only one time. - """ - decorated = [] - def decorate(test, interface): - decorated.append((test, interface)) - return test - self.patch(unittest, "decorate", decorate) - self.runner._forceGarbageCollection = True - result = self.runner.runUntilFailure(self.test) - self.assertEqual(result.testsRun, 1) - - self.assertEqual(len(decorated), 2) - self.assertEqual(decorated, - [(self.test, ITestCase), - (self.test, unittest._ForceGarbageCollectionDecorator)]) - - - -class UncleanUntilFailureTests(TestUntilFailure): - """ - Test that the run-until-failure feature works correctly with the unclean - error suppressor. - """ - - def setUp(self): - TestUntilFailure.setUp(self) - self.runner = runner.TrialRunner(reporter.Reporter, stream=self.stream, - uncleanWarnings=True) - - def _getFailures(self, result): - """ - Get the number of failures that were reported to a result that - is wrapped in an UncleanFailureWrapper. - """ - return len(result._originalReporter.failures) - - - -class BreakingSuite(runner.TestSuite): - """ - A L{TestSuite} that logs an error when it is run. - """ - - def run(self, result): - try: - raise RuntimeError("error that occurs outside of a test") - except RuntimeError: - log.err(failure.Failure()) - - - -class TestLoggedErrors(unittest.TestCase): - """ - It is possible for an error generated by a test to be logged I{outside} of - any test. The log observers constructed by L{TestCase} won't catch these - errors. Here we try to generate such errors and ensure they are reported to - a L{TestResult} object. - """ - - def tearDown(self): - self.flushLoggedErrors(RuntimeError) - - - def test_construct(self): - """ - Check that we can construct a L{runner.LoggedSuite} and that it - starts empty. - """ - suite = runner.LoggedSuite() - self.assertEqual(suite.countTestCases(), 0) - - - def test_capturesError(self): - """ - Chek that a L{LoggedSuite} reports any logged errors to its result. - """ - result = reporter.TestResult() - suite = runner.LoggedSuite([BreakingSuite()]) - suite.run(result) - self.assertEqual(len(result.errors), 1) - self.assertEqual(result.errors[0][0].id(), runner.NOT_IN_TEST) - self.failUnless(result.errors[0][1].check(RuntimeError)) - - - -class TestTestHolder(unittest.TestCase): - - def setUp(self): - self.description = "description" - self.holder = runner.TestHolder(self.description) - - - def test_holder(self): - """ - Check that L{runner.TestHolder} takes a description as a parameter - and that this description is returned by the C{id} and - C{shortDescription} methods. - """ - self.assertEqual(self.holder.id(), self.description) - self.assertEqual(self.holder.shortDescription(), self.description) - - - def test_holderImplementsITestCase(self): - """ - L{runner.TestHolder} implements L{ITestCase}. - """ - self.assertIdentical(self.holder, ITestCase(self.holder)) - self.assertTrue( - verifyObject(ITestCase, self.holder), - "%r claims to provide %r but does not do so correctly." - % (self.holder, ITestCase)) - - - def test_runsWithStandardResult(self): - """ - A L{runner.TestHolder} can run against the standard Python - C{TestResult}. - """ - result = pyunit.TestResult() - self.holder.run(result) - self.assertTrue(result.wasSuccessful()) - self.assertEqual(1, result.testsRun) - - - -class ErrorHolderTestsMixin(object): - """ - This mixin defines test methods which can be applied to a - L{runner.ErrorHolder} constructed with either a L{Failure} or a - C{exc_info}-style tuple. - - Subclass this and implement C{setUp} to create C{self.holder} referring to a - L{runner.ErrorHolder} instance and C{self.error} referring to a L{Failure} - which the holder holds. - """ - exceptionForTests = ZeroDivisionError('integer division or modulo by zero') - - class TestResultStub(object): - """ - Stub for L{TestResult}. - """ - def __init__(self): - self.errors = [] - - def startTest(self, test): - pass - - def stopTest(self, test): - pass - - def addError(self, test, error): - self.errors.append((test, error)) - - - def test_runsWithStandardResult(self): - """ - A L{runner.ErrorHolder} can run against the standard Python - C{TestResult}. - """ - result = pyunit.TestResult() - self.holder.run(result) - self.assertFalse(result.wasSuccessful()) - self.assertEqual(1, result.testsRun) - - - def test_run(self): - """ - L{runner.ErrorHolder} adds an error to the result when run. - """ - self.holder.run(self.result) - self.assertEqual( - self.result.errors, - [(self.holder, (self.error.type, self.error.value, self.error.tb))]) - - - def test_call(self): - """ - L{runner.ErrorHolder} adds an error to the result when called. - """ - self.holder(self.result) - self.assertEqual( - self.result.errors, - [(self.holder, (self.error.type, self.error.value, self.error.tb))]) - - - def test_countTestCases(self): - """ - L{runner.ErrorHolder.countTestCases} always returns 0. - """ - self.assertEqual(self.holder.countTestCases(), 0) - - - def test_repr(self): - """ - L{runner.ErrorHolder.__repr__} returns a string describing the error it - holds. - """ - self.assertEqual(repr(self.holder), - "<ErrorHolder description='description' " - "error=ZeroDivisionError('integer division or modulo by zero',)>") - - - -class FailureHoldingErrorHolderTests(ErrorHolderTestsMixin, TestTestHolder): - """ - Tests for L{runner.ErrorHolder} behaving similarly to L{runner.TestHolder} - when constructed with a L{Failure} representing its error. - """ - def setUp(self): - self.description = "description" - # make a real Failure so we can construct ErrorHolder() - try: - raise self.exceptionForTests - except ZeroDivisionError: - self.error = failure.Failure() - self.holder = runner.ErrorHolder(self.description, self.error) - self.result = self.TestResultStub() - - - -class ExcInfoHoldingErrorHolderTests(ErrorHolderTestsMixin, TestTestHolder): - """ - Tests for L{runner.ErrorHolder} behaving similarly to L{runner.TestHolder} - when constructed with a C{exc_info}-style tuple representing its error. - """ - def setUp(self): - self.description = "description" - # make a real Failure so we can construct ErrorHolder() - try: - raise self.exceptionForTests - except ZeroDivisionError: - exceptionInfo = sys.exc_info() - self.error = failure.Failure() - self.holder = runner.ErrorHolder(self.description, exceptionInfo) - self.result = self.TestResultStub() - - - -class TestMalformedMethod(unittest.TestCase): - """ - Test that trial manages when test methods don't have correct signatures. - """ - class ContainMalformed(unittest.TestCase): - """ - This TestCase holds malformed test methods that trial should handle. - """ - def test_foo(self, blah): - pass - def test_bar(): - pass - test_spam = defer.deferredGenerator(test_bar) - - def _test(self, method): - """ - Wrapper for one of the test method of L{ContainMalformed}. - """ - stream = StringIO.StringIO() - trialRunner = runner.TrialRunner(reporter.Reporter, stream=stream) - test = TestMalformedMethod.ContainMalformed(method) - result = trialRunner.run(test) - self.assertEqual(result.testsRun, 1) - self.failIf(result.wasSuccessful()) - self.assertEqual(len(result.errors), 1) - - def test_extraArg(self): - """ - Test when the method has extra (useless) arguments. - """ - self._test('test_foo') - - def test_noArg(self): - """ - Test when the method doesn't have even self as argument. - """ - self._test('test_bar') - - def test_decorated(self): - """ - Test a decorated method also fails. - """ - self._test('test_spam') - - - -class DestructiveTestSuiteTestCase(unittest.TestCase): - """ - Test for L{runner.DestructiveTestSuite}. - """ - - def test_basic(self): - """ - Thes destructive test suite should run the tests normally. - """ - called = [] - class MockTest(unittest.TestCase): - def test_foo(test): - called.append(True) - test = MockTest('test_foo') - result = reporter.TestResult() - suite = runner.DestructiveTestSuite([test]) - self.assertEqual(called, []) - suite.run(result) - self.assertEqual(called, [True]) - self.assertEqual(suite.countTestCases(), 0) - - - def test_shouldStop(self): - """ - Test the C{shouldStop} management: raising a C{KeyboardInterrupt} must - interrupt the suite. - """ - called = [] - class MockTest(unittest.TestCase): - def test_foo1(test): - called.append(1) - def test_foo2(test): - raise KeyboardInterrupt() - def test_foo3(test): - called.append(2) - result = reporter.TestResult() - loader = runner.TestLoader() - loader.suiteFactory = runner.DestructiveTestSuite - suite = loader.loadClass(MockTest) - self.assertEqual(called, []) - suite.run(result) - self.assertEqual(called, [1]) - # The last test shouldn't have been run - self.assertEqual(suite.countTestCases(), 1) - - - def test_cleanup(self): - """ - Checks that the test suite cleanups its tests during the run, so that - it ends empty. - """ - class MockTest(unittest.TestCase): - def test_foo(test): - pass - test = MockTest('test_foo') - result = reporter.TestResult() - suite = runner.DestructiveTestSuite([test]) - self.assertEqual(suite.countTestCases(), 1) - suite.run(result) - self.assertEqual(suite.countTestCases(), 0) - - - -class TestRunnerDeprecation(unittest.TestCase): - - class FakeReporter(reporter.Reporter): - """ - Fake reporter that does *not* implement done() but *does* implement - printErrors, separator, printSummary, stream, write and writeln - without deprecations. - """ - - done = None - separator = None - stream = None - - def printErrors(self, *args): - pass - - def printSummary(self, *args): - pass - - def write(self, *args): - pass - - def writeln(self, *args): - pass - - - def test_reporterDeprecations(self): - """ - The runner emits a warning if it is using a result that doesn't - implement 'done'. - """ - trialRunner = runner.TrialRunner(None) - result = self.FakeReporter() - trialRunner._makeResult = lambda: result - def f(): - # We have to use a pyunit test, otherwise we'll get deprecation - # warnings about using iterate() in a test. - trialRunner.run(pyunit.TestCase('id')) - self.assertWarns( - DeprecationWarning, - "%s should implement done() but doesn't. Falling back to " - "printErrors() and friends." % reflect.qual(result.__class__), - __file__, f) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_script.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_script.py deleted file mode 100755 index a8d489d5..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_script.py +++ /dev/null @@ -1,443 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -import gc -import StringIO, sys, types - -from twisted.trial import unittest, runner -from twisted.scripts import trial -from twisted.python import util -from twisted.python.compat import set -from twisted.python.filepath import FilePath - -from twisted.trial.test.test_loader import testNames - -pyunit = __import__('unittest') - - -def sibpath(filename): - """ - For finding files in twisted/trial/test - """ - return util.sibpath(__file__, filename) - - - -class ForceGarbageCollection(unittest.TestCase): - """ - Tests for the --force-gc option. - """ - - def setUp(self): - self.config = trial.Options() - self.log = [] - self.patch(gc, 'collect', self.collect) - test = pyunit.FunctionTestCase(self.simpleTest) - self.test = runner.TestSuite([test, test]) - - - def simpleTest(self): - """ - A simple test method that records that it was run. - """ - self.log.append('test') - - - def collect(self): - """ - A replacement for gc.collect that logs calls to itself. - """ - self.log.append('collect') - - - def makeRunner(self): - """ - Return a L{runner.TrialRunner} object that is safe to use in tests. - """ - runner = trial._makeRunner(self.config) - runner.stream = StringIO.StringIO() - return runner - - - def test_forceGc(self): - """ - Passing the --force-gc option to the trial script forces the garbage - collector to run before and after each test. - """ - self.config['force-gc'] = True - self.config.postOptions() - runner = self.makeRunner() - runner.run(self.test) - self.assertEqual(self.log, ['collect', 'test', 'collect', - 'collect', 'test', 'collect']) - - - def test_unforceGc(self): - """ - By default, no garbage collection is forced. - """ - self.config.postOptions() - runner = self.makeRunner() - runner.run(self.test) - self.assertEqual(self.log, ['test', 'test']) - - - -class TestSuiteUsed(unittest.TestCase): - """ - Check the category of tests suite used by the loader. - """ - - def setUp(self): - """ - Create a trial configuration object. - """ - self.config = trial.Options() - - - def test_defaultSuite(self): - """ - By default, the loader should use L{runner.DestructiveTestSuite} - """ - loader = trial._getLoader(self.config) - self.assertEqual(loader.suiteFactory, runner.DestructiveTestSuite) - - - def test_untilFailureSuite(self): - """ - The C{until-failure} configuration uses the L{runner.TestSuite} to keep - instances alive across runs. - """ - self.config['until-failure'] = True - loader = trial._getLoader(self.config) - self.assertEqual(loader.suiteFactory, runner.TestSuite) - - - -class TestModuleTest(unittest.TestCase): - def setUp(self): - self.config = trial.Options() - - def tearDown(self): - self.config = None - - def test_testNames(self): - """ - Check that the testNames helper method accurately collects the - names of tests in suite. - """ - self.assertEqual(testNames(self), [self.id()]) - - def assertSuitesEqual(self, test1, names): - loader = runner.TestLoader() - names1 = testNames(test1) - names2 = testNames(runner.TestSuite(map(loader.loadByName, names))) - names1.sort() - names2.sort() - self.assertEqual(names1, names2) - - def test_baseState(self): - self.assertEqual(0, len(self.config['tests'])) - - def test_testmoduleOnModule(self): - """ - Check that --testmodule loads a suite which contains the tests - referred to in test-case-name inside its parameter. - """ - self.config.opt_testmodule(sibpath('moduletest.py')) - self.assertSuitesEqual(trial._getSuite(self.config), - ['twisted.trial.test.test_test_visitor']) - - def test_testmoduleTwice(self): - """ - When the same module is specified with two --testmodule flags, it - should only appear once in the suite. - """ - self.config.opt_testmodule(sibpath('moduletest.py')) - self.config.opt_testmodule(sibpath('moduletest.py')) - self.assertSuitesEqual(trial._getSuite(self.config), - ['twisted.trial.test.test_test_visitor']) - - def test_testmoduleOnSourceAndTarget(self): - """ - If --testmodule is specified twice, once for module A and once for - a module which refers to module A, then make sure module A is only - added once. - """ - self.config.opt_testmodule(sibpath('moduletest.py')) - self.config.opt_testmodule(sibpath('test_test_visitor.py')) - self.assertSuitesEqual(trial._getSuite(self.config), - ['twisted.trial.test.test_test_visitor']) - - def test_testmoduleOnSelfModule(self): - """ - When given a module that refers to *itself* in the test-case-name - variable, check that --testmodule only adds the tests once. - """ - self.config.opt_testmodule(sibpath('moduleself.py')) - self.assertSuitesEqual(trial._getSuite(self.config), - ['twisted.trial.test.moduleself']) - - def test_testmoduleOnScript(self): - """ - Check that --testmodule loads tests referred to in test-case-name - buffer variables. - """ - self.config.opt_testmodule(sibpath('scripttest.py')) - self.assertSuitesEqual(trial._getSuite(self.config), - ['twisted.trial.test.test_test_visitor', - 'twisted.trial.test.test_class']) - - def test_testmoduleOnNonexistentFile(self): - """ - Check that --testmodule displays a meaningful error message when - passed a non-existent filename. - """ - buffy = StringIO.StringIO() - stderr, sys.stderr = sys.stderr, buffy - filename = 'test_thisbetternoteverexist.py' - try: - self.config.opt_testmodule(filename) - self.assertEqual(0, len(self.config['tests'])) - self.assertEqual("File %r doesn't exist\n" % (filename,), - buffy.getvalue()) - finally: - sys.stderr = stderr - - def test_testmoduleOnEmptyVars(self): - """ - Check that --testmodule adds no tests to the suite for modules - which lack test-case-name buffer variables. - """ - self.config.opt_testmodule(sibpath('novars.py')) - self.assertEqual(0, len(self.config['tests'])) - - def test_testmoduleOnModuleName(self): - """ - Check that --testmodule does *not* support module names as arguments - and that it displays a meaningful error message. - """ - buffy = StringIO.StringIO() - stderr, sys.stderr = sys.stderr, buffy - moduleName = 'twisted.trial.test.test_script' - try: - self.config.opt_testmodule(moduleName) - self.assertEqual(0, len(self.config['tests'])) - self.assertEqual("File %r doesn't exist\n" % (moduleName,), - buffy.getvalue()) - finally: - sys.stderr = stderr - - def test_parseLocalVariable(self): - declaration = '-*- test-case-name: twisted.trial.test.test_tests -*-' - localVars = trial._parseLocalVariables(declaration) - self.assertEqual({'test-case-name': - 'twisted.trial.test.test_tests'}, - localVars) - - def test_trailingSemicolon(self): - declaration = '-*- test-case-name: twisted.trial.test.test_tests; -*-' - localVars = trial._parseLocalVariables(declaration) - self.assertEqual({'test-case-name': - 'twisted.trial.test.test_tests'}, - localVars) - - def test_parseLocalVariables(self): - declaration = ('-*- test-case-name: twisted.trial.test.test_tests; ' - 'foo: bar -*-') - localVars = trial._parseLocalVariables(declaration) - self.assertEqual({'test-case-name': - 'twisted.trial.test.test_tests', - 'foo': 'bar'}, - localVars) - - def test_surroundingGuff(self): - declaration = ('## -*- test-case-name: ' - 'twisted.trial.test.test_tests -*- #') - localVars = trial._parseLocalVariables(declaration) - self.assertEqual({'test-case-name': - 'twisted.trial.test.test_tests'}, - localVars) - - def test_invalidLine(self): - self.failUnlessRaises(ValueError, trial._parseLocalVariables, - 'foo') - - def test_invalidDeclaration(self): - self.failUnlessRaises(ValueError, trial._parseLocalVariables, - '-*- foo -*-') - self.failUnlessRaises(ValueError, trial._parseLocalVariables, - '-*- foo: bar; qux -*-') - self.failUnlessRaises(ValueError, trial._parseLocalVariables, - '-*- foo: bar: baz; qux: qax -*-') - - def test_variablesFromFile(self): - localVars = trial.loadLocalVariables(sibpath('moduletest.py')) - self.assertEqual({'test-case-name': - 'twisted.trial.test.test_test_visitor'}, - localVars) - - def test_noVariablesInFile(self): - localVars = trial.loadLocalVariables(sibpath('novars.py')) - self.assertEqual({}, localVars) - - def test_variablesFromScript(self): - localVars = trial.loadLocalVariables(sibpath('scripttest.py')) - self.assertEqual( - {'test-case-name': ('twisted.trial.test.test_test_visitor,' - 'twisted.trial.test.test_class')}, - localVars) - - def test_getTestModules(self): - modules = trial.getTestModules(sibpath('moduletest.py')) - self.assertEqual(modules, ['twisted.trial.test.test_test_visitor']) - - def test_getTestModules_noVars(self): - modules = trial.getTestModules(sibpath('novars.py')) - self.assertEqual(len(modules), 0) - - def test_getTestModules_multiple(self): - modules = trial.getTestModules(sibpath('scripttest.py')) - self.assertEqual(set(modules), - set(['twisted.trial.test.test_test_visitor', - 'twisted.trial.test.test_class'])) - - def test_looksLikeTestModule(self): - for filename in ['test_script.py', 'twisted/trial/test/test_script.py']: - self.failUnless(trial.isTestFile(filename), - "%r should be a test file" % (filename,)) - for filename in ['twisted/trial/test/moduletest.py', - sibpath('scripttest.py'), sibpath('test_foo.bat')]: - self.failIf(trial.isTestFile(filename), - "%r should *not* be a test file" % (filename,)) - - -class WithoutModuleTests(unittest.TestCase): - """ - Test the C{without-module} flag. - """ - - def setUp(self): - """ - Create a L{trial.Options} object to be used in the tests, and save - C{sys.modules}. - """ - self.config = trial.Options() - self.savedModules = dict(sys.modules) - - - def tearDown(self): - """ - Restore C{sys.modules}. - """ - for module in ('imaplib', 'smtplib'): - if module in self.savedModules: - sys.modules[module] = self.savedModules[module] - else: - sys.modules.pop(module, None) - - - def _checkSMTP(self): - """ - Try to import the C{smtplib} module, and return it. - """ - import smtplib - return smtplib - - - def _checkIMAP(self): - """ - Try to import the C{imaplib} module, and return it. - """ - import imaplib - return imaplib - - - def test_disableOneModule(self): - """ - Check that after disabling a module, it can't be imported anymore. - """ - self.config.parseOptions(["--without-module", "smtplib"]) - self.assertRaises(ImportError, self._checkSMTP) - # Restore sys.modules - del sys.modules["smtplib"] - # Then the function should succeed - self.assertIsInstance(self._checkSMTP(), types.ModuleType) - - - def test_disableMultipleModules(self): - """ - Check that several modules can be disabled at once. - """ - self.config.parseOptions(["--without-module", "smtplib,imaplib"]) - self.assertRaises(ImportError, self._checkSMTP) - self.assertRaises(ImportError, self._checkIMAP) - # Restore sys.modules - del sys.modules["smtplib"] - del sys.modules["imaplib"] - # Then the functions should succeed - self.assertIsInstance(self._checkSMTP(), types.ModuleType) - self.assertIsInstance(self._checkIMAP(), types.ModuleType) - - - def test_disableAlreadyImportedModule(self): - """ - Disabling an already imported module should produce a warning. - """ - self.assertIsInstance(self._checkSMTP(), types.ModuleType) - self.assertWarns(RuntimeWarning, - "Module 'smtplib' already imported, disabling anyway.", - trial.__file__, - self.config.parseOptions, ["--without-module", "smtplib"]) - self.assertRaises(ImportError, self._checkSMTP) - - - -class CoverageTests(unittest.TestCase): - """ - Tests for the I{coverage} option. - """ - if getattr(sys, 'gettrace', None) is None: - skip = ( - "Cannot test trace hook installation without inspection API.") - - def setUp(self): - """ - Arrange for the current trace hook to be restored when the - test is complete. - """ - self.addCleanup(sys.settrace, sys.gettrace()) - - - def test_tracerInstalled(self): - """ - L{trial.Options} handles C{"--coverage"} by installing a trace - hook to record coverage information. - """ - options = trial.Options() - options.parseOptions(["--coverage"]) - self.assertEqual(sys.gettrace(), options.tracer.globaltrace) - - - def test_coverdirDefault(self): - """ - L{trial.Options.coverdir} returns a L{FilePath} based on the default - for the I{temp-directory} option if that option is not specified. - """ - options = trial.Options() - self.assertEqual( - options.coverdir(), - FilePath(".").descendant([options["temp-directory"], "coverage"])) - - - def test_coverdirOverridden(self): - """ - If a value is specified for the I{temp-directory} option, - L{trial.Options.coverdir} returns a child of that path. - """ - path = self.mktemp() - options = trial.Options() - options.parseOptions(["--temp-directory", path]) - self.assertEqual( - options.coverdir(), FilePath(path).child("coverage")) - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_test_visitor.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_test_visitor.py deleted file mode 100755 index b5c3484e..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_test_visitor.py +++ /dev/null @@ -1,82 +0,0 @@ -from twisted.trial import unittest -from twisted.trial.runner import TestSuite, suiteVisit - -pyunit = __import__('unittest') - - - -class MockVisitor(object): - def __init__(self): - self.calls = [] - - - def __call__(self, testCase): - self.calls.append(testCase) - - - -class TestTestVisitor(unittest.TestCase): - def setUp(self): - self.visitor = MockVisitor() - - - def test_visitCase(self): - """ - Test that C{visit} works for a single test case. - """ - testCase = TestTestVisitor('test_visitCase') - testCase.visit(self.visitor) - self.assertEqual(self.visitor.calls, [testCase]) - - - def test_visitSuite(self): - """ - Test that C{visit} hits all tests in a suite. - """ - tests = [TestTestVisitor('test_visitCase'), - TestTestVisitor('test_visitSuite')] - testSuite = TestSuite(tests) - testSuite.visit(self.visitor) - self.assertEqual(self.visitor.calls, tests) - - - def test_visitEmptySuite(self): - """ - Test that C{visit} on an empty suite hits nothing. - """ - TestSuite().visit(self.visitor) - self.assertEqual(self.visitor.calls, []) - - - def test_visitNestedSuite(self): - """ - Test that C{visit} recurses through suites. - """ - tests = [TestTestVisitor('test_visitCase'), - TestTestVisitor('test_visitSuite')] - testSuite = TestSuite([TestSuite([test]) for test in tests]) - testSuite.visit(self.visitor) - self.assertEqual(self.visitor.calls, tests) - - - def test_visitPyunitSuite(self): - """ - Test that C{suiteVisit} visits stdlib unittest suites - """ - test = TestTestVisitor('test_visitPyunitSuite') - suite = pyunit.TestSuite([test]) - suiteVisit(suite, self.visitor) - self.assertEqual(self.visitor.calls, [test]) - - - def test_visitPyunitCase(self): - """ - Test that a stdlib test case in a suite gets visited. - """ - class PyunitCase(pyunit.TestCase): - def test_foo(self): - pass - test = PyunitCase('test_foo') - TestSuite([test]).visit(self.visitor) - self.assertEqual( - [call.id() for call in self.visitor.calls], [test.id()]) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_testcase.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_testcase.py deleted file mode 100755 index 4b24f3a1..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_testcase.py +++ /dev/null @@ -1,68 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Direct unit tests for L{twisted.trial.unittest.SynchronousTestCase} and -L{twisted.trial.unittest.TestCase}. -""" - -from twisted.trial.unittest import SynchronousTestCase, TestCase - - -class TestCaseMixin(object): - """ - L{TestCase} tests. - """ - def setUp(self): - """ - Create a couple instances of C{MyTestCase}, each for the same test - method, to be used in the test methods of this class. - """ - self.first = self.MyTestCase('test_1') - self.second = self.MyTestCase('test_1') - - - def test_equality(self): - """ - In order for one test method to be runnable twice, two TestCase - instances with the same test method name must not compare as equal. - """ - self.assertTrue(self.first == self.first) - self.assertTrue(self.first != self.second) - self.assertFalse(self.first == self.second) - - - def test_hashability(self): - """ - In order for one test method to be runnable twice, two TestCase - instances with the same test method name should not have the same - hash value. - """ - container = {} - container[self.first] = None - container[self.second] = None - self.assertEqual(len(container), 2) - - - -class SynchronousTestCaseTests(TestCaseMixin, SynchronousTestCase): - class MyTestCase(SynchronousTestCase): - """ - Some test methods which can be used to test behaviors of - L{SynchronousTestCase}. - """ - def test_1(self): - pass - - - -# Yes, subclass SynchronousTestCase again. There are no interesting behaviors -# of self being tested below, only of self.MyTestCase. -class AsynchronousTestCaseTests(TestCaseMixin, SynchronousTestCase): - class MyTestCase(TestCase): - """ - Some test methods which can be used to test behaviors of - L{TestCase}. - """ - def test_1(self): - pass diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_tests.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_tests.py deleted file mode 100755 index 8192544d..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_tests.py +++ /dev/null @@ -1,1379 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for the behaviour of unit tests. - -Many tests in this module follow a simple pattern. A mixin is defined which -includes test methods for a certain feature. The mixin is inherited from twice, -once by a class also inheriting from SynchronousTestCase and once from a class -inheriting from TestCase. These two subclasses are named like -I{SynchronousFooTests} and I{AsynchronousFooTests}, where I{Foo} is related to -the name of the mixin. - -This pattern allows the same tests to be applied to the two base test case -classes trial provides, ensuring their behavior is the same. - -Most new tests should be added in this pattern. Tests for functionality which -is intentionally only provided by TestCase, not SynchronousTestCase, is excepted -of course. -""" - -import gc, StringIO, sys, weakref - -from twisted.internet import defer, reactor -from twisted.trial import unittest, runner, reporter, util -from twisted.trial.test import erroneous, suppression -from twisted.trial.test.test_reporter import LoggingReporter - - -class ResultsTestMixin(object): - """ - Provide useful APIs for test cases that are about test cases. - """ - def loadSuite(self, suite): - """ - Load tests from the given test case class and create a new reporter to - use for running it. - """ - self.loader = runner.TestLoader() - self.suite = self.loader.loadClass(suite) - self.reporter = reporter.TestResult() - - - def test_setUp(self): - self.failUnless(self.reporter.wasSuccessful()) - self.assertEqual(self.reporter.errors, []) - self.assertEqual(self.reporter.failures, []) - self.assertEqual(self.reporter.skips, []) - - - def assertCount(self, numTests): - self.assertEqual(self.suite.countTestCases(), numTests) - self.suite(self.reporter) - self.assertEqual(self.reporter.testsRun, numTests) - - - -class SuccessMixin(object): - """ - Tests for the reporting of successful tests. - """ - def setUp(self): - self.result = reporter.TestResult() - - - def test_successful(self): - """ - A successful test, used by other tests. - """ - - - def assertSuccessful(self, test, result): - self.assertEqual(result.successes, 1) - self.assertEqual(result.failures, []) - self.assertEqual(result.errors, []) - self.assertEqual(result.expectedFailures, []) - self.assertEqual(result.unexpectedSuccesses, []) - self.assertEqual(result.skips, []) - - - def test_successfulIsReported(self): - """ - Test that when a successful test is run, it is reported as a success, - and not as any other kind of result. - """ - test = self.__class__('test_successful') - test.run(self.result) - self.assertSuccessful(test, self.result) - - - def test_defaultIsSuccessful(self): - """ - The test case type can be instantiated with no arguments, run, and - reported as being successful. - """ - test = self.__class__() - test.run(self.result) - self.assertSuccessful(test, self.result) - - - def test_noReference(self): - """ - Test that no reference is kept on a successful test. - """ - test = self.__class__('test_successful') - ref = weakref.ref(test) - test.run(self.result) - self.assertSuccessful(test, self.result) - del test - gc.collect() - self.assertIdentical(ref(), None) - - - -class SynchronousSuccessTests(SuccessMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - - - -class AsynchronousSuccessTests(SuccessMixin, unittest.TestCase): - """ - See module docstring. - """ - - - -class SkipMethodsMixin(ResultsTestMixin): - """ - Tests for the reporting of skipping tests. - """ - def setUp(self): - self.loadSuite(self.Skipping) - - - def test_counting(self): - self.assertCount(3) - - - def test_results(self): - """ - Running a suite in which all methods are individually set to skip - produces a successful result with no recorded errors or failures, all - the skipped methods recorded as skips, and no methods recorded as - successes. - """ - self.suite(self.reporter) - self.assertTrue(self.reporter.wasSuccessful()) - self.assertEqual(self.reporter.errors, []) - self.assertEqual(self.reporter.failures, []) - self.assertEqual(len(self.reporter.skips), 3) - self.assertEqual(self.reporter.successes, 0) - - - def test_setUp(self): - """ - Running a suite in which all methods are skipped by C{setUp} raising - L{SkipTest} produces a successful result with no recorded errors or - failures, all skipped methods recorded as skips, and no methods recorded - as successes. - """ - self.loadSuite(self.SkippingSetUp) - self.suite(self.reporter) - self.assertTrue(self.reporter.wasSuccessful()) - self.assertEqual(self.reporter.errors, []) - self.assertEqual(self.reporter.failures, []) - self.assertEqual(len(self.reporter.skips), 2) - self.assertEqual(self.reporter.successes, 0) - - - def test_reasons(self): - self.suite(self.reporter) - prefix = 'test_' - # whiteboxing reporter - for test, reason in self.reporter.skips: - self.assertEqual(test.shortDescription()[len(prefix):], - str(reason)) - - - def test_deprecatedSkipWithoutReason(self): - """ - If a test method raises L{SkipTest} with no reason, a deprecation - warning is emitted. - """ - self.loadSuite(self.DeprecatedReasonlessSkip) - self.suite(self.reporter) - warnings = self.flushWarnings([ - self.DeprecatedReasonlessSkip.test_1]) - self.assertEqual(1, len(warnings)) - self.assertEqual(DeprecationWarning, warnings[0]['category']) - self.assertEqual( - "Do not raise unittest.SkipTest with no arguments! Give a reason " - "for skipping tests!", - warnings[0]['message']) - - - -class SynchronousSkipMethodTests(SkipMethodsMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - SynchronousSkipping as Skipping, - SynchronousSkippingSetUp as SkippingSetUp, - SynchronousDeprecatedReasonlessSkip as DeprecatedReasonlessSkip) - - - -class AsynchronousSkipMethodTests(SkipMethodsMixin, unittest.TestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - AsynchronousSkipping as Skipping, - AsynchronousSkippingSetUp as SkippingSetUp, - AsynchronousDeprecatedReasonlessSkip as DeprecatedReasonlessSkip) - - - - -class SkipClassesMixin(ResultsTestMixin): - """ - Test the class skipping features of L{twisted.trial.unittest.TestCase}. - """ - def setUp(self): - self.loadSuite(self.SkippedClass) - self.SkippedClass._setUpRan = False - - - def test_counting(self): - """ - Skipped test methods still contribute to the total test count. - """ - self.assertCount(4) - - - def test_setUpRan(self): - """ - The C{setUp} method is not called if the class is set to skip. - """ - self.suite(self.reporter) - self.assertFalse(self.SkippedClass._setUpRan) - - - def test_results(self): - """ - Skipped test methods don't cause C{wasSuccessful} to return C{False}, - nor do they contribute to the C{errors} or C{failures} of the reporter, - or to the count of successes. They do, however, add elements to the - reporter's C{skips} list. - """ - self.suite(self.reporter) - self.assertTrue(self.reporter.wasSuccessful()) - self.assertEqual(self.reporter.errors, []) - self.assertEqual(self.reporter.failures, []) - self.assertEqual(len(self.reporter.skips), 4) - self.assertEqual(self.reporter.successes, 0) - - - def test_reasons(self): - """ - Test methods which raise L{unittest.SkipTest} or have their C{skip} - attribute set to something are skipped. - """ - self.suite(self.reporter) - expectedReasons = ['class', 'skip2', 'class', 'class'] - # whitebox reporter - reasonsGiven = [reason for test, reason in self.reporter.skips] - self.assertEqual(expectedReasons, reasonsGiven) - - - -class SynchronousSkipClassTests(SkipClassesMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - SynchronousSkippedClass as SkippedClass) - - - -class AsynchronousSkipClassTests(SkipClassesMixin, unittest.TestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - AsynchronousSkippedClass as SkippedClass) - - - -class TodoMixin(ResultsTestMixin): - """ - Tests for the individual test method I{expected failure} features of - L{twisted.trial.unittest.TestCase}. - """ - def setUp(self): - self.loadSuite(self.Todo) - - - def test_counting(self): - self.assertCount(3) - - - def test_results(self): - """ - Running a suite in which all methods are individually marked as expected - to fail produces a successful result with no recorded errors, failures, - or skips, all methods which fail and were expected to fail recorded as - C{expectedFailures}, and all methods which pass but which were expected - to fail recorded as C{unexpectedSuccesses}. Additionally, no tests are - recorded as successes. - """ - self.suite(self.reporter) - self.assertTrue(self.reporter.wasSuccessful()) - self.assertEqual(self.reporter.errors, []) - self.assertEqual(self.reporter.failures, []) - self.assertEqual(self.reporter.skips, []) - self.assertEqual(len(self.reporter.expectedFailures), 2) - self.assertEqual(len(self.reporter.unexpectedSuccesses), 1) - self.assertEqual(self.reporter.successes, 0) - - - def test_expectedFailures(self): - self.suite(self.reporter) - expectedReasons = ['todo1', 'todo2'] - reasonsGiven = [ r.reason - for t, e, r in self.reporter.expectedFailures ] - self.assertEqual(expectedReasons, reasonsGiven) - - - def test_unexpectedSuccesses(self): - self.suite(self.reporter) - expectedReasons = ['todo3'] - reasonsGiven = [ r.reason - for t, r in self.reporter.unexpectedSuccesses ] - self.assertEqual(expectedReasons, reasonsGiven) - - - def test_expectedSetUpFailure(self): - """ - C{setUp} is excluded from the failure expectation defined by a C{todo} - attribute on a test method. - """ - self.loadSuite(self.SetUpTodo) - self.suite(self.reporter) - self.assertFalse(self.reporter.wasSuccessful()) - self.assertEqual(len(self.reporter.errors), 1) - self.assertEqual(self.reporter.failures, []) - self.assertEqual(self.reporter.skips, []) - self.assertEqual(len(self.reporter.expectedFailures), 0) - self.assertEqual(len(self.reporter.unexpectedSuccesses), 0) - self.assertEqual(self.reporter.successes, 0) - - - def test_expectedTearDownFailure(self): - """ - C{tearDown} is excluded from the failure expectation defined by a C{todo} - attribute on a test method. - """ - self.loadSuite(self.TearDownTodo) - self.suite(self.reporter) - self.assertFalse(self.reporter.wasSuccessful()) - self.assertEqual(len(self.reporter.errors), 1) - self.assertEqual(self.reporter.failures, []) - self.assertEqual(self.reporter.skips, []) - self.assertEqual(len(self.reporter.expectedFailures), 0) - # This seems strange, since tearDown raised an exception. However, the - # test method did complete without error. The tearDown error is - # reflected in the errors list, checked above. - self.assertEqual(len(self.reporter.unexpectedSuccesses), 1) - self.assertEqual(self.reporter.successes, 0) - - - -class SynchronousTodoTests(TodoMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - SynchronousTodo as Todo, - SynchronousSetUpTodo as SetUpTodo, - SynchronousTearDownTodo as TearDownTodo) - - - -class AsynchronousTodoTests(TodoMixin, unittest.TestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - AsynchronousTodo as Todo, - AsynchronousSetUpTodo as SetUpTodo, - AsynchronousTearDownTodo as TearDownTodo) - - - -class ClassTodoMixin(ResultsTestMixin): - """ - Tests for the class-wide I{expected failure} features of - L{twisted.trial.unittest.TestCase}. - """ - def setUp(self): - self.loadSuite(self.TodoClass) - - def test_counting(self): - self.assertCount(4) - - - def test_results(self): - """ - Running a suite in which an entire class is marked as expected to fail - produces a successful result with no recorded errors, failures, or - skips, all methods which fail and were expected to fail recorded as - C{expectedFailures}, and all methods which pass but which were expected - to fail recorded as C{unexpectedSuccesses}. Additionally, no tests are - recorded as successes. - """ - self.suite(self.reporter) - self.assertTrue(self.reporter.wasSuccessful()) - self.assertEqual(self.reporter.errors, []) - self.assertEqual(self.reporter.failures, []) - self.assertEqual(self.reporter.skips, []) - self.assertEqual(len(self.reporter.expectedFailures), 2) - self.assertEqual(len(self.reporter.unexpectedSuccesses), 2) - self.assertEqual(self.reporter.successes, 0) - - - def test_expectedFailures(self): - self.suite(self.reporter) - expectedReasons = ['method', 'class'] - reasonsGiven = [ r.reason - for t, e, r in self.reporter.expectedFailures ] - self.assertEqual(expectedReasons, reasonsGiven) - - def test_unexpectedSuccesses(self): - self.suite(self.reporter) - expectedReasons = ['method', 'class'] - reasonsGiven = [ r.reason - for t, r in self.reporter.unexpectedSuccesses ] - self.assertEqual(expectedReasons, reasonsGiven) - - - -class SynchronousClassTodoTests(ClassTodoMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - SynchronousTodoClass as TodoClass) - - - -class AsynchronousClassTodoTests(ClassTodoMixin, unittest.TestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - AsynchronousTodoClass as TodoClass) - - - -class StrictTodoMixin(ResultsTestMixin): - """ - Tests for the I{expected failure} features of - L{twisted.trial.unittest.TestCase} in which the exact failure which is - expected is indicated. - """ - def setUp(self): - self.loadSuite(self.StrictTodo) - - def test_counting(self): - self.assertCount(7) - - - def test_results(self): - """ - A test method which is marked as expected to fail with a particular - exception is only counted as an expected failure if it does fail with - that exception, not if it fails with some other exception. - """ - self.suite(self.reporter) - self.assertFalse(self.reporter.wasSuccessful()) - self.assertEqual(len(self.reporter.errors), 2) - self.assertEqual(len(self.reporter.failures), 1) - self.assertEqual(len(self.reporter.expectedFailures), 3) - self.assertEqual(len(self.reporter.unexpectedSuccesses), 1) - self.assertEqual(self.reporter.successes, 0) - self.assertEqual(self.reporter.skips, []) - - - def test_expectedFailures(self): - self.suite(self.reporter) - expectedReasons = ['todo1', 'todo2', 'todo5'] - reasonsGotten = [ r.reason - for t, e, r in self.reporter.expectedFailures ] - self.assertEqual(expectedReasons, reasonsGotten) - - - def test_unexpectedSuccesses(self): - self.suite(self.reporter) - expectedReasons = [([RuntimeError], 'todo7')] - reasonsGotten = [ (r.errors, r.reason) - for t, r in self.reporter.unexpectedSuccesses ] - self.assertEqual(expectedReasons, reasonsGotten) - - - -class SynchronousStrictTodoTests(StrictTodoMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - SynchronousStrictTodo as StrictTodo) - - - -class AsynchronousStrictTodoTests(StrictTodoMixin, unittest.TestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import ( - AsynchronousStrictTodo as StrictTodo) - - - -class TestReactorCleanup(unittest.TestCase): - """ - Tests for cleanup and reporting of reactor event sources left behind by test - methods. - """ - - def setUp(self): - self.result = reporter.Reporter(StringIO.StringIO()) - self.loader = runner.TestLoader() - - - def testLeftoverSockets(self): - """ - Trial reports a L{util.DirtyReactorAggregateError} if a test leaves - sockets behind. - """ - suite = self.loader.loadMethod( - erroneous.SocketOpenTest.test_socketsLeftOpen) - suite.run(self.result) - self.failIf(self.result.wasSuccessful()) - # socket cleanup happens at end of class's tests. - # all the tests in the class are successful, even if the suite - # fails - self.assertEqual(self.result.successes, 1) - failure = self.result.errors[0][1] - self.failUnless(failure.check(util.DirtyReactorAggregateError)) - - - def testLeftoverPendingCalls(self): - """ - Trial reports a L{util.DirtyReactorAggregateError} and fails the test - if a test leaves a L{DelayedCall} hanging. - """ - suite = erroneous.ReactorCleanupTests('test_leftoverPendingCalls') - suite.run(self.result) - self.failIf(self.result.wasSuccessful()) - failure = self.result.errors[0][1] - self.assertEqual(self.result.successes, 0) - self.failUnless(failure.check(util.DirtyReactorAggregateError)) - - - -class FixtureMixin(object): - """ - Tests for broken fixture helper methods (e.g. setUp, tearDown). - """ - - def setUp(self): - self.reporter = reporter.Reporter() - self.loader = runner.TestLoader() - - - def test_brokenSetUp(self): - """ - When setUp fails, the error is recorded in the result object. - """ - suite = self.loader.loadClass(self.TestFailureInSetUp) - suite.run(self.reporter) - self.assertTrue(len(self.reporter.errors) > 0) - self.assertIsInstance( - self.reporter.errors[0][1].value, erroneous.FoolishError) - self.assertEqual(0, self.reporter.successes) - - - def test_brokenTearDown(self): - """ - When tearDown fails, the error is recorded in the result object. - """ - suite = self.loader.loadClass(self.TestFailureInTearDown) - suite.run(self.reporter) - errors = self.reporter.errors - self.assertTrue(len(errors) > 0) - self.assertIsInstance(errors[0][1].value, erroneous.FoolishError) - self.assertEqual(0, self.reporter.successes) - - - -class SynchronousFixtureTest(FixtureMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - from twisted.trial.test.erroneous import ( - SynchronousTestFailureInSetUp as TestFailureInSetUp, - SynchronousTestFailureInTearDown as TestFailureInTearDown) - - - -class AsynchronousFixtureTest(FixtureMixin, unittest.TestCase): - """ - See module docstring. - """ - from twisted.trial.test.erroneous import ( - AsynchronousTestFailureInSetUp as TestFailureInSetUp, - AsynchronousTestFailureInTearDown as TestFailureInTearDown) - - - -class SuppressionMixin(object): - """ - Tests for the warning suppression features of - L{twisted.trial.unittest.SynchronousTestCase}. - """ - def runTests(self, suite): - suite.run(reporter.TestResult()) - - - def setUp(self): - self.loader = runner.TestLoader() - - - def _assertWarnings(self, warnings, which): - """ - Assert that a certain number of warnings with certain messages were - emitted in a certain order. - - @param warnings: A list of emitted warnings, as returned by - C{flushWarnings}. - - @param which: A list of strings giving warning messages that should - appear in C{warnings}. - - @raise self.failureException: If the warning messages given by C{which} - do not match the messages in the warning information in C{warnings}, - or if they do not appear in the same order. - """ - self.assertEqual( - [warning['message'] for warning in warnings], - which) - - - def test_setUpSuppression(self): - """ - Suppressions defined by the test method being run are applied to any - warnings emitted while running the C{setUp} fixture. - """ - self.runTests( - self.loader.loadMethod( - self.TestSetUpSuppression.testSuppressMethod)) - warningsShown = self.flushWarnings([ - self.TestSetUpSuppression._emit]) - self._assertWarnings( - warningsShown, - [suppression.CLASS_WARNING_MSG, suppression.MODULE_WARNING_MSG, - suppression.CLASS_WARNING_MSG, suppression.MODULE_WARNING_MSG]) - - - def test_tearDownSuppression(self): - """ - Suppressions defined by the test method being run are applied to any - warnings emitted while running the C{tearDown} fixture. - """ - self.runTests( - self.loader.loadMethod( - self.TestTearDownSuppression.testSuppressMethod)) - warningsShown = self.flushWarnings([ - self.TestTearDownSuppression._emit]) - self._assertWarnings( - warningsShown, - [suppression.CLASS_WARNING_MSG, suppression.MODULE_WARNING_MSG, - suppression.CLASS_WARNING_MSG, suppression.MODULE_WARNING_MSG]) - - - def test_suppressMethod(self): - """ - A suppression set on a test method prevents warnings emitted by that - test method which the suppression matches from being emitted. - """ - self.runTests(self.loader.loadMethod( - self.TestSuppression.testSuppressMethod)) - warningsShown = self.flushWarnings([ - self.TestSuppression._emit]) - self._assertWarnings( - warningsShown, - [suppression.CLASS_WARNING_MSG, suppression.MODULE_WARNING_MSG]) - - - def test_suppressClass(self): - """ - A suppression set on a L{SynchronousTestCase} subclass prevents warnings - emitted by any test methods defined on that class which match the - suppression from being emitted. - """ - self.runTests(self.loader.loadMethod( - self.TestSuppression.testSuppressClass)) - warningsShown = self.flushWarnings([ - self.TestSuppression._emit]) - self.assertEqual( - warningsShown[0]['message'], suppression.METHOD_WARNING_MSG) - self.assertEqual( - warningsShown[1]['message'], suppression.MODULE_WARNING_MSG) - self.assertEqual(len(warningsShown), 2) - - - def test_suppressModule(self): - """ - A suppression set on a module prevents warnings emitted by any test - mewthods defined in that module which match the suppression from being - emitted. - """ - self.runTests(self.loader.loadMethod( - self.TestSuppression2.testSuppressModule)) - warningsShown = self.flushWarnings([ - self.TestSuppression._emit]) - self.assertEqual( - warningsShown[0]['message'], suppression.METHOD_WARNING_MSG) - self.assertEqual( - warningsShown[1]['message'], suppression.CLASS_WARNING_MSG) - self.assertEqual(len(warningsShown), 2) - - - def test_overrideSuppressClass(self): - """ - The suppression set on a test method completely overrides a suppression - with wider scope; if it does not match a warning emitted by that test - method, the warning is emitted, even if a wider suppression matches. - """ - case = self.loader.loadMethod( - self.TestSuppression.testOverrideSuppressClass) - self.runTests(case) - warningsShown = self.flushWarnings([ - self.TestSuppression._emit]) - self.assertEqual( - warningsShown[0]['message'], suppression.METHOD_WARNING_MSG) - self.assertEqual( - warningsShown[1]['message'], suppression.CLASS_WARNING_MSG) - self.assertEqual( - warningsShown[2]['message'], suppression.MODULE_WARNING_MSG) - self.assertEqual(len(warningsShown), 3) - - - -class SynchronousSuppressionTest(SuppressionMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - from twisted.trial.test.suppression import ( - SynchronousTestSetUpSuppression as TestSetUpSuppression, - SynchronousTestTearDownSuppression as TestTearDownSuppression, - SynchronousTestSuppression as TestSuppression, - SynchronousTestSuppression2 as TestSuppression2) - - - -class AsynchronousSuppressionTest(SuppressionMixin, unittest.TestCase): - """ - See module docstring. - """ - from twisted.trial.test.suppression import ( - AsynchronousTestSetUpSuppression as TestSetUpSuppression, - AsynchronousTestTearDownSuppression as TestTearDownSuppression, - AsynchronousTestSuppression as TestSuppression, - AsynchronousTestSuppression2 as TestSuppression2) - - - -class GCMixin: - """ - I provide a few mock tests that log setUp, tearDown, test execution and - garbage collection. I'm used to test whether gc.collect gets called. - """ - - class BasicTest(unittest.TestCase): - def setUp(self): - self._log('setUp') - def test_foo(self): - self._log('test') - def tearDown(self): - self._log('tearDown') - - class ClassTest(unittest.TestCase): - def test_1(self): - self._log('test1') - def test_2(self): - self._log('test2') - - def _log(self, msg): - self._collectCalled.append(msg) - - def collect(self): - """Fake gc.collect""" - self._log('collect') - - def setUp(self): - self._collectCalled = [] - self.BasicTest._log = self.ClassTest._log = self._log - self._oldCollect = gc.collect - gc.collect = self.collect - - def tearDown(self): - gc.collect = self._oldCollect - - - -class TestGarbageCollectionDefault(GCMixin, unittest.SynchronousTestCase): - - def test_collectNotDefault(self): - """ - By default, tests should not force garbage collection. - """ - test = self.BasicTest('test_foo') - result = reporter.TestResult() - test.run(result) - self.assertEqual(self._collectCalled, ['setUp', 'test', 'tearDown']) - - - -class TestGarbageCollection(GCMixin, unittest.SynchronousTestCase): - - def test_collectCalled(self): - """ - test gc.collect is called before and after each test. - """ - test = TestGarbageCollection.BasicTest('test_foo') - test = unittest._ForceGarbageCollectionDecorator(test) - result = reporter.TestResult() - test.run(result) - self.assertEqual( - self._collectCalled, - ['collect', 'setUp', 'test', 'tearDown', 'collect']) - - - -class TestUnhandledDeferred(unittest.TestCase): - - def setUp(self): - from twisted.trial.test import weird - # test_unhandledDeferred creates a cycle. we need explicit control of gc - gc.disable() - self.test1 = unittest._ForceGarbageCollectionDecorator( - weird.TestBleeding('test_unhandledDeferred')) - - def test_isReported(self): - """ - Forcing garbage collection should cause unhandled Deferreds to be - reported as errors. - """ - result = reporter.TestResult() - self.test1(result) - self.assertEqual(len(result.errors), 1, - 'Unhandled deferred passed without notice') - - def test_doesntBleed(self): - """ - Forcing garbage collection in the test should mean that there are - no unreachable cycles immediately after the test completes. - """ - result = reporter.TestResult() - self.test1(result) - self.flushLoggedErrors() # test1 logs errors that get caught be us. - # test1 created unreachable cycle. - # it & all others should have been collected by now. - n = gc.collect() - self.assertEqual(n, 0, 'unreachable cycle still existed') - # check that last gc.collect didn't log more errors - x = self.flushLoggedErrors() - self.assertEqual(len(x), 0, 'Errors logged after gc.collect') - - def tearDown(self): - gc.collect() - gc.enable() - self.flushLoggedErrors() - - - -class AddCleanupMixin(object): - """ - Test the addCleanup method of TestCase. - """ - def setUp(self): - super(AddCleanupMixin, self).setUp() - self.result = reporter.TestResult() - self.test = self.AddCleanup() - - - def test_addCleanupCalledIfSetUpFails(self): - """ - Callables added with C{addCleanup} are run even if setUp fails. - """ - self.test.setUp = self.test.brokenSetUp - self.test.addCleanup(self.test.append, 'foo') - self.test.run(self.result) - self.assertEqual(['setUp', 'foo'], self.test.log) - - - def test_addCleanupCalledIfSetUpSkips(self): - """ - Callables added with C{addCleanup} are run even if setUp raises - L{SkipTest}. This allows test authors to reliably provide clean up - code using C{addCleanup}. - """ - self.test.setUp = self.test.skippingSetUp - self.test.addCleanup(self.test.append, 'foo') - self.test.run(self.result) - self.assertEqual(['setUp', 'foo'], self.test.log) - - - def test_addCleanupCalledInReverseOrder(self): - """ - Callables added with C{addCleanup} should be called before C{tearDown} - in reverse order of addition. - """ - self.test.addCleanup(self.test.append, "foo") - self.test.addCleanup(self.test.append, 'bar') - self.test.run(self.result) - self.assertEqual(['setUp', 'runTest', 'bar', 'foo', 'tearDown'], - self.test.log) - - - def test_errorInCleanupIsCaptured(self): - """ - Errors raised in cleanup functions should be treated like errors in - C{tearDown}. They should be added as errors and fail the test. Skips, - todos and failures are all treated as errors. - """ - self.test.addCleanup(self.test.fail, 'foo') - self.test.run(self.result) - self.failIf(self.result.wasSuccessful()) - self.assertEqual(1, len(self.result.errors)) - [(test, error)] = self.result.errors - self.assertEqual(test, self.test) - self.assertEqual(error.getErrorMessage(), 'foo') - - - def test_cleanupsContinueRunningAfterError(self): - """ - If a cleanup raises an error then that does not stop the other - cleanups from being run. - """ - self.test.addCleanup(self.test.append, 'foo') - self.test.addCleanup(self.test.fail, 'bar') - self.test.run(self.result) - self.assertEqual(['setUp', 'runTest', 'foo', 'tearDown'], - self.test.log) - self.assertEqual(1, len(self.result.errors)) - [(test, error)] = self.result.errors - self.assertEqual(test, self.test) - self.assertEqual(error.getErrorMessage(), 'bar') - - - def test_multipleErrorsReported(self): - """ - If more than one cleanup fails, then the test should fail with more - than one error. - """ - self.test.addCleanup(self.test.fail, 'foo') - self.test.addCleanup(self.test.fail, 'bar') - self.test.run(self.result) - self.assertEqual(['setUp', 'runTest', 'tearDown'], - self.test.log) - self.assertEqual(2, len(self.result.errors)) - [(test1, error1), (test2, error2)] = self.result.errors - self.assertEqual(test1, self.test) - self.assertEqual(test2, self.test) - self.assertEqual(error1.getErrorMessage(), 'bar') - self.assertEqual(error2.getErrorMessage(), 'foo') - - - -class SynchronousAddCleanupTests(AddCleanupMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import SynchronousAddCleanup as AddCleanup - - - -class AsynchronousAddCleanupTests(AddCleanupMixin, unittest.TestCase): - """ - See module docstring. - """ - from twisted.trial.test.skipping import AsynchronousAddCleanup as AddCleanup - - def test_addCleanupWaitsForDeferreds(self): - """ - If an added callable returns a L{Deferred}, then the test should wait - until that L{Deferred} has fired before running the next cleanup - method. - """ - def cleanup(message): - d = defer.Deferred() - reactor.callLater(0, d.callback, message) - return d.addCallback(self.test.append) - self.test.addCleanup(self.test.append, 'foo') - self.test.addCleanup(cleanup, 'bar') - self.test.run(self.result) - self.assertEqual(['setUp', 'runTest', 'bar', 'foo', 'tearDown'], - self.test.log) - - - -class SuiteClearingMixin(object): - """ - Tests for our extension that allows us to clear out a L{TestSuite}. - """ - def test_clearSuite(self): - """ - Calling L{unittest._clearSuite} on a populated L{TestSuite} removes - all tests. - """ - suite = unittest.TestSuite() - suite.addTest(self.TestCase()) - # Double check that the test suite actually has something in it. - self.assertEqual(1, suite.countTestCases()) - unittest._clearSuite(suite) - self.assertEqual(0, suite.countTestCases()) - - - def test_clearPyunitSuite(self): - """ - Calling L{unittest._clearSuite} on a populated standard library - L{TestSuite} removes all tests. - - This test is important since C{_clearSuite} operates by mutating - internal variables. - """ - pyunit = __import__('unittest') - suite = pyunit.TestSuite() - suite.addTest(self.TestCase()) - # Double check that the test suite actually has something in it. - self.assertEqual(1, suite.countTestCases()) - unittest._clearSuite(suite) - self.assertEqual(0, suite.countTestCases()) - - - -class SynchronousSuiteClearingTests(SuiteClearingMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - TestCase = unittest.SynchronousTestCase - - - -class AsynchronousSuiteClearingTests(SuiteClearingMixin, unittest.TestCase): - """ - See module docstring. - """ - TestCase = unittest.TestCase - - - -class TestDecoratorMixin(object): - """ - Tests for our test decoration features. - """ - def assertTestsEqual(self, observed, expected): - """ - Assert that the given decorated tests are equal. - """ - self.assertEqual(observed.__class__, expected.__class__, - "Different class") - observedOriginal = getattr(observed, '_originalTest', None) - expectedOriginal = getattr(expected, '_originalTest', None) - self.assertIdentical(observedOriginal, expectedOriginal) - if observedOriginal is expectedOriginal is None: - self.assertIdentical(observed, expected) - - - def assertSuitesEqual(self, observed, expected): - """ - Assert that the given test suites with decorated tests are equal. - """ - self.assertEqual(observed.__class__, expected.__class__, - "Different class") - self.assertEqual(len(observed._tests), len(expected._tests), - "Different number of tests.") - for observedTest, expectedTest in zip(observed._tests, - expected._tests): - if getattr(observedTest, '_tests', None) is not None: - self.assertSuitesEqual(observedTest, expectedTest) - else: - self.assertTestsEqual(observedTest, expectedTest) - - - def test_usesAdaptedReporterWithRun(self): - """ - For decorated tests, C{run} uses a result adapter that preserves the - test decoration for calls to C{addError}, C{startTest} and the like. - - See L{reporter._AdaptedReporter}. - """ - test = self.TestCase() - decoratedTest = unittest.TestDecorator(test) - result = LoggingReporter() - decoratedTest.run(result) - self.assertTestsEqual(result.test, decoratedTest) - - - def test_usesAdaptedReporterWithCall(self): - """ - For decorated tests, C{__call__} uses a result adapter that preserves - the test decoration for calls to C{addError}, C{startTest} and the - like. - - See L{reporter._AdaptedReporter}. - """ - test = self.TestCase() - decoratedTest = unittest.TestDecorator(test) - result = LoggingReporter() - decoratedTest(result) - self.assertTestsEqual(result.test, decoratedTest) - - - def test_decorateSingleTest(self): - """ - Calling L{decorate} on a single test case returns the test case - decorated with the provided decorator. - """ - test = self.TestCase() - decoratedTest = unittest.decorate(test, unittest.TestDecorator) - self.assertTestsEqual(unittest.TestDecorator(test), decoratedTest) - - - def test_decorateTestSuite(self): - """ - Calling L{decorate} on a test suite will return a test suite with - each test decorated with the provided decorator. - """ - test = self.TestCase() - suite = unittest.TestSuite([test]) - decoratedTest = unittest.decorate(suite, unittest.TestDecorator) - self.assertSuitesEqual( - decoratedTest, unittest.TestSuite([unittest.TestDecorator(test)])) - - - def test_decorateInPlaceMutatesOriginal(self): - """ - Calling L{decorate} on a test suite will mutate the original suite. - """ - test = self.TestCase() - suite = unittest.TestSuite([test]) - decoratedTest = unittest.decorate( - suite, unittest.TestDecorator) - self.assertSuitesEqual( - decoratedTest, unittest.TestSuite([unittest.TestDecorator(test)])) - self.assertSuitesEqual( - suite, unittest.TestSuite([unittest.TestDecorator(test)])) - - - def test_decorateTestSuiteReferences(self): - """ - When decorating a test suite in-place, the number of references to the - test objects in that test suite should stay the same. - - Previously, L{unittest.decorate} recreated a test suite, so the - original suite kept references to the test objects. This test is here - to ensure the problem doesn't reappear again. - """ - getrefcount = getattr(sys, 'getrefcount', None) - if getrefcount is None: - raise unittest.SkipTest( - "getrefcount not supported on this platform") - test = self.TestCase() - suite = unittest.TestSuite([test]) - count1 = getrefcount(test) - decoratedTest = unittest.decorate(suite, unittest.TestDecorator) - count2 = getrefcount(test) - self.assertEqual(count1, count2) - - - def test_decorateNestedTestSuite(self): - """ - Calling L{decorate} on a test suite with nested suites will return a - test suite that maintains the same structure, but with all tests - decorated. - """ - test = self.TestCase() - suite = unittest.TestSuite([unittest.TestSuite([test])]) - decoratedTest = unittest.decorate(suite, unittest.TestDecorator) - expected = unittest.TestSuite( - [unittest.TestSuite([unittest.TestDecorator(test)])]) - self.assertSuitesEqual(decoratedTest, expected) - - - def test_decorateDecoratedSuite(self): - """ - Calling L{decorate} on a test suite with already-decorated tests - decorates all of the tests in the suite again. - """ - test = self.TestCase() - decoratedTest = unittest.decorate(test, unittest.TestDecorator) - redecoratedTest = unittest.decorate(decoratedTest, - unittest.TestDecorator) - self.assertTestsEqual(redecoratedTest, - unittest.TestDecorator(decoratedTest)) - - - def test_decoratePreservesSuite(self): - """ - Tests can be in non-standard suites. L{decorate} preserves the - non-standard suites when it decorates the tests. - """ - test = self.TestCase() - suite = runner.DestructiveTestSuite([test]) - decorated = unittest.decorate(suite, unittest.TestDecorator) - self.assertSuitesEqual( - decorated, - runner.DestructiveTestSuite([unittest.TestDecorator(test)])) - - - -class SynchronousTestDecoratorTests(TestDecoratorMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - TestCase = unittest.SynchronousTestCase - - - -class AsynchronousTestDecoratorTests(TestDecoratorMixin, unittest.TestCase): - """ - See module docstring. - """ - TestCase = unittest.TestCase - - - -class MonkeyPatchMixin(object): - """ - Tests for the patch() helper method in L{unittest.TestCase}. - """ - def setUp(self): - self.originalValue = 'original' - self.patchedValue = 'patched' - self.objectToPatch = self.originalValue - self.test = self.TestCase() - - - def test_patch(self): - """ - Calling C{patch()} on a test monkey patches the specified object and - attribute. - """ - self.test.patch(self, 'objectToPatch', self.patchedValue) - self.assertEqual(self.objectToPatch, self.patchedValue) - - - def test_patchRestoredAfterRun(self): - """ - Any monkey patches introduced by a test using C{patch()} are reverted - after the test has run. - """ - self.test.patch(self, 'objectToPatch', self.patchedValue) - self.test.run(reporter.Reporter()) - self.assertEqual(self.objectToPatch, self.originalValue) - - - def test_revertDuringTest(self): - """ - C{patch()} return a L{monkey.MonkeyPatcher} object that can be used to - restore the original values before the end of the test. - """ - patch = self.test.patch(self, 'objectToPatch', self.patchedValue) - patch.restore() - self.assertEqual(self.objectToPatch, self.originalValue) - - - def test_revertAndRepatch(self): - """ - The returned L{monkey.MonkeyPatcher} object can re-apply the patch - during the test run. - """ - patch = self.test.patch(self, 'objectToPatch', self.patchedValue) - patch.restore() - patch.patch() - self.assertEqual(self.objectToPatch, self.patchedValue) - - - def test_successivePatches(self): - """ - Successive patches are applied and reverted just like a single patch. - """ - self.test.patch(self, 'objectToPatch', self.patchedValue) - self.assertEqual(self.objectToPatch, self.patchedValue) - self.test.patch(self, 'objectToPatch', 'second value') - self.assertEqual(self.objectToPatch, 'second value') - self.test.run(reporter.Reporter()) - self.assertEqual(self.objectToPatch, self.originalValue) - - - -class SynchronousMonkeyPatchTests(MonkeyPatchMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - TestCase = unittest.SynchronousTestCase - - - -class AsynchronousMonkeyPatchTests(MonkeyPatchMixin, unittest.TestCase): - """ - See module docstring. - """ - TestCase = unittest.TestCase - - - -class IterateTestsMixin(object): - """ - L{_iterateTests} returns a list of all test cases in a test suite or test - case. - """ - def test_iterateTestCase(self): - """ - L{_iterateTests} on a single test case returns a list containing that - test case. - """ - test = self.TestCase() - self.assertEqual([test], list(unittest._iterateTests(test))) - - - def test_iterateSingletonTestSuite(self): - """ - L{_iterateTests} on a test suite that contains a single test case - returns a list containing that test case. - """ - test = self.TestCase() - suite = runner.TestSuite([test]) - self.assertEqual([test], list(unittest._iterateTests(suite))) - - - def test_iterateNestedTestSuite(self): - """ - L{_iterateTests} returns tests that are in nested test suites. - """ - test = self.TestCase() - suite = runner.TestSuite([runner.TestSuite([test])]) - self.assertEqual([test], list(unittest._iterateTests(suite))) - - - def test_iterateIsLeftToRightDepthFirst(self): - """ - L{_iterateTests} returns tests in left-to-right, depth-first order. - """ - test = self.TestCase() - suite = runner.TestSuite([runner.TestSuite([test]), self]) - self.assertEqual([test, self], list(unittest._iterateTests(suite))) - - - -class SynchronousIterateTestsTests(IterateTestsMixin, unittest.SynchronousTestCase): - """ - See module docstring. - """ - TestCase = unittest.SynchronousTestCase - - - -class AsynchronousIterateTestsTests(IterateTestsMixin, unittest.TestCase): - """ - See module docstring. - """ - TestCase = unittest.TestCase diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_util.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_util.py deleted file mode 100755 index 9421c812..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_util.py +++ /dev/null @@ -1,584 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. -# - -""" -Tests for L{twisted.trial.util} -""" - -import os - -from zope.interface import implements - -from twisted.internet.interfaces import IProcessTransport -from twisted.internet import defer -from twisted.internet.base import DelayedCall - -from twisted.trial.unittest import SynchronousTestCase, TestCase -from twisted.trial import util -from twisted.trial.util import DirtyReactorAggregateError, _Janitor -from twisted.trial.test import packages, suppression - - - -class TestMktemp(SynchronousTestCase): - """ - Tests for L{TestCase.mktemp}, a helper function for creating temporary file - or directory names. - """ - def test_name(self): - """ - The path name returned by C{mktemp} is directly beneath a directory - which identifies the test method which created the name. - """ - name = self.mktemp() - dirs = os.path.dirname(name).split(os.sep)[:-1] - self.assertEqual( - dirs, ['twisted.trial.test.test_util', 'TestMktemp', 'test_name']) - - - def test_unique(self): - """ - Repeated calls to C{mktemp} return different values. - """ - name = self.mktemp() - self.assertNotEqual(name, self.mktemp()) - - - def test_created(self): - """ - The directory part of the path name returned by C{mktemp} exists. - """ - name = self.mktemp() - dirname = os.path.dirname(name) - self.assertTrue(os.path.exists(dirname)) - self.assertFalse(os.path.exists(name)) - - - def test_location(self): - """ - The path returned by C{mktemp} is beneath the current working directory. - """ - path = os.path.abspath(self.mktemp()) - self.assertTrue(path.startswith(os.getcwd())) - - - -class TestIntrospection(SynchronousTestCase): - def test_containers(self): - """ - When pased a test case, L{util.getPythonContainers} returns a list - including the test case and the module the test case is defined in. - """ - parents = util.getPythonContainers( - suppression.SynchronousTestSuppression2.testSuppressModule) - expected = [suppression.SynchronousTestSuppression2, suppression] - for a, b in zip(parents, expected): - self.assertEqual(a, b) - - - -class TestFindObject(packages.SysPathManglingTest): - """ - Tests for L{twisted.trial.util.findObject} - """ - - def test_deprecation(self): - """ - Calling L{findObject} results in a deprecation warning - """ - util.findObject('') - warningsShown = self.flushWarnings() - self.assertEqual(len(warningsShown), 1) - self.assertIdentical(warningsShown[0]['category'], DeprecationWarning) - self.assertEqual(warningsShown[0]['message'], - "twisted.trial.util.findObject was deprecated " - "in Twisted 10.1.0: Please use " - "twisted.python.reflect.namedAny instead.") - - - def test_importPackage(self): - package1 = util.findObject('package') - import package as package2 - self.assertEqual(package1, (True, package2)) - - def test_importModule(self): - test_sample2 = util.findObject('goodpackage.test_sample') - from goodpackage import test_sample - self.assertEqual((True, test_sample), test_sample2) - - def test_importError(self): - self.failUnlessRaises(ZeroDivisionError, - util.findObject, 'package.test_bad_module') - - def test_sophisticatedImportError(self): - self.failUnlessRaises(ImportError, - util.findObject, 'package2.test_module') - - def test_importNonexistentPackage(self): - self.assertEqual(util.findObject('doesntexist')[0], False) - - def test_findNonexistentModule(self): - self.assertEqual(util.findObject('package.doesntexist')[0], False) - - def test_findNonexistentObject(self): - self.assertEqual(util.findObject( - 'goodpackage.test_sample.doesnt')[0], False) - self.assertEqual(util.findObject( - 'goodpackage.test_sample.AlphabetTest.doesntexist')[0], False) - - def test_findObjectExist(self): - alpha1 = util.findObject('goodpackage.test_sample.AlphabetTest') - from goodpackage import test_sample - self.assertEqual(alpha1, (True, test_sample.AlphabetTest)) - - - -class TestRunSequentially(TestCase): - """ - Sometimes it is useful to be able to run an arbitrary list of callables, - one after the other. - - When some of those callables can return Deferreds, things become complex. - """ - - def test_emptyList(self): - """ - When asked to run an empty list of callables, runSequentially returns a - successful Deferred that fires an empty list. - """ - d = util._runSequentially([]) - d.addCallback(self.assertEqual, []) - return d - - - def test_singleSynchronousSuccess(self): - """ - When given a callable that succeeds without returning a Deferred, - include the return value in the results list, tagged with a SUCCESS - flag. - """ - d = util._runSequentially([lambda: None]) - d.addCallback(self.assertEqual, [(defer.SUCCESS, None)]) - return d - - - def test_singleSynchronousFailure(self): - """ - When given a callable that raises an exception, include a Failure for - that exception in the results list, tagged with a FAILURE flag. - """ - d = util._runSequentially([lambda: self.fail('foo')]) - def check(results): - [(flag, fail)] = results - fail.trap(self.failureException) - self.assertEqual(fail.getErrorMessage(), 'foo') - self.assertEqual(flag, defer.FAILURE) - return d.addCallback(check) - - - def test_singleAsynchronousSuccess(self): - """ - When given a callable that returns a successful Deferred, include the - result of the Deferred in the results list, tagged with a SUCCESS flag. - """ - d = util._runSequentially([lambda: defer.succeed(None)]) - d.addCallback(self.assertEqual, [(defer.SUCCESS, None)]) - return d - - - def test_singleAsynchronousFailure(self): - """ - When given a callable that returns a failing Deferred, include the - failure the results list, tagged with a FAILURE flag. - """ - d = util._runSequentially([lambda: defer.fail(ValueError('foo'))]) - def check(results): - [(flag, fail)] = results - fail.trap(ValueError) - self.assertEqual(fail.getErrorMessage(), 'foo') - self.assertEqual(flag, defer.FAILURE) - return d.addCallback(check) - - - def test_callablesCalledInOrder(self): - """ - Check that the callables are called in the given order, one after the - other. - """ - log = [] - deferreds = [] - - def append(value): - d = defer.Deferred() - log.append(value) - deferreds.append(d) - return d - - d = util._runSequentially([lambda: append('foo'), - lambda: append('bar')]) - - # runSequentially should wait until the Deferred has fired before - # running the second callable. - self.assertEqual(log, ['foo']) - deferreds[-1].callback(None) - self.assertEqual(log, ['foo', 'bar']) - - # Because returning created Deferreds makes jml happy. - deferreds[-1].callback(None) - return d - - - def test_continuesAfterError(self): - """ - If one of the callables raises an error, then runSequentially continues - to run the remaining callables. - """ - d = util._runSequentially([lambda: self.fail('foo'), lambda: 'bar']) - def check(results): - [(flag1, fail), (flag2, result)] = results - fail.trap(self.failureException) - self.assertEqual(flag1, defer.FAILURE) - self.assertEqual(fail.getErrorMessage(), 'foo') - self.assertEqual(flag2, defer.SUCCESS) - self.assertEqual(result, 'bar') - return d.addCallback(check) - - - def test_stopOnFirstError(self): - """ - If the C{stopOnFirstError} option is passed to C{runSequentially}, then - no further callables are called after the first exception is raised. - """ - d = util._runSequentially([lambda: self.fail('foo'), lambda: 'bar'], - stopOnFirstError=True) - def check(results): - [(flag1, fail)] = results - fail.trap(self.failureException) - self.assertEqual(flag1, defer.FAILURE) - self.assertEqual(fail.getErrorMessage(), 'foo') - return d.addCallback(check) - - - def test_stripFlags(self): - """ - If the C{stripFlags} option is passed to C{runSequentially} then the - SUCCESS / FAILURE flags are stripped from the output. Instead, the - Deferred fires a flat list of results containing only the results and - failures. - """ - d = util._runSequentially([lambda: self.fail('foo'), lambda: 'bar'], - stripFlags=True) - def check(results): - [fail, result] = results - fail.trap(self.failureException) - self.assertEqual(fail.getErrorMessage(), 'foo') - self.assertEqual(result, 'bar') - return d.addCallback(check) - test_stripFlags.todo = "YAGNI" - - - -class DirtyReactorAggregateErrorTest(SynchronousTestCase): - """ - Tests for the L{DirtyReactorAggregateError}. - """ - - def test_formatDelayedCall(self): - """ - Delayed calls are formatted nicely. - """ - error = DirtyReactorAggregateError(["Foo", "bar"]) - self.assertEqual(str(error), - """\ -Reactor was unclean. -DelayedCalls: (set twisted.internet.base.DelayedCall.debug = True to debug) -Foo -bar""") - - - def test_formatSelectables(self): - """ - Selectables are formatted nicely. - """ - error = DirtyReactorAggregateError([], ["selectable 1", "selectable 2"]) - self.assertEqual(str(error), - """\ -Reactor was unclean. -Selectables: -selectable 1 -selectable 2""") - - - def test_formatDelayedCallsAndSelectables(self): - """ - Both delayed calls and selectables can appear in the same error. - """ - error = DirtyReactorAggregateError(["bleck", "Boozo"], - ["Sel1", "Sel2"]) - self.assertEqual(str(error), - """\ -Reactor was unclean. -DelayedCalls: (set twisted.internet.base.DelayedCall.debug = True to debug) -bleck -Boozo -Selectables: -Sel1 -Sel2""") - - - -class StubReactor(object): - """ - A reactor stub which contains enough functionality to be used with the - L{_Janitor}. - - @ivar iterations: A list of the arguments passed to L{iterate}. - @ivar removeAllCalled: Number of times that L{removeAll} was called. - @ivar selectables: The value that will be returned from L{removeAll}. - @ivar delayedCalls: The value to return from L{getDelayedCalls}. - """ - - def __init__(self, delayedCalls, selectables=None): - """ - @param delayedCalls: See L{StubReactor.delayedCalls}. - @param selectables: See L{StubReactor.selectables}. - """ - self.delayedCalls = delayedCalls - self.iterations = [] - self.removeAllCalled = 0 - if not selectables: - selectables = [] - self.selectables = selectables - - - def iterate(self, timeout=None): - """ - Increment C{self.iterations}. - """ - self.iterations.append(timeout) - - - def getDelayedCalls(self): - """ - Return C{self.delayedCalls}. - """ - return self.delayedCalls - - - def removeAll(self): - """ - Increment C{self.removeAllCalled} and return C{self.selectables}. - """ - self.removeAllCalled += 1 - return self.selectables - - - -class StubErrorReporter(object): - """ - A subset of L{twisted.trial.itrial.IReporter} which records L{addError} - calls. - - @ivar errors: List of two-tuples of (test, error) which were passed to - L{addError}. - """ - - def __init__(self): - self.errors = [] - - - def addError(self, test, error): - """ - Record parameters in C{self.errors}. - """ - self.errors.append((test, error)) - - - -class JanitorTests(SynchronousTestCase): - """ - Tests for L{_Janitor}! - """ - - def test_cleanPendingSpinsReactor(self): - """ - During pending-call cleanup, the reactor will be spun twice with an - instant timeout. This is not a requirement, it is only a test for - current behavior. Hopefully Trial will eventually not do this kind of - reactor stuff. - """ - reactor = StubReactor([]) - jan = _Janitor(None, None, reactor=reactor) - jan._cleanPending() - self.assertEqual(reactor.iterations, [0, 0]) - - - def test_cleanPendingCancelsCalls(self): - """ - During pending-call cleanup, the janitor cancels pending timed calls. - """ - def func(): - return "Lulz" - cancelled = [] - delayedCall = DelayedCall(300, func, (), {}, - cancelled.append, lambda x: None) - reactor = StubReactor([delayedCall]) - jan = _Janitor(None, None, reactor=reactor) - jan._cleanPending() - self.assertEqual(cancelled, [delayedCall]) - - - def test_cleanPendingReturnsDelayedCallStrings(self): - """ - The Janitor produces string representations of delayed calls from the - delayed call cleanup method. It gets the string representations - *before* cancelling the calls; this is important because cancelling the - call removes critical debugging information from the string - representation. - """ - delayedCall = DelayedCall(300, lambda: None, (), {}, - lambda x: None, lambda x: None, - seconds=lambda: 0) - delayedCallString = str(delayedCall) - reactor = StubReactor([delayedCall]) - jan = _Janitor(None, None, reactor=reactor) - strings = jan._cleanPending() - self.assertEqual(strings, [delayedCallString]) - - - def test_cleanReactorRemovesSelectables(self): - """ - The Janitor will remove selectables during reactor cleanup. - """ - reactor = StubReactor([]) - jan = _Janitor(None, None, reactor=reactor) - jan._cleanReactor() - self.assertEqual(reactor.removeAllCalled, 1) - - - def test_cleanReactorKillsProcesses(self): - """ - The Janitor will kill processes during reactor cleanup. - """ - class StubProcessTransport(object): - """ - A stub L{IProcessTransport} provider which records signals. - @ivar signals: The signals passed to L{signalProcess}. - """ - implements(IProcessTransport) - - def __init__(self): - self.signals = [] - - def signalProcess(self, signal): - """ - Append C{signal} to C{self.signals}. - """ - self.signals.append(signal) - - pt = StubProcessTransport() - reactor = StubReactor([], [pt]) - jan = _Janitor(None, None, reactor=reactor) - jan._cleanReactor() - self.assertEqual(pt.signals, ["KILL"]) - - - def test_cleanReactorReturnsSelectableStrings(self): - """ - The Janitor returns string representations of the selectables that it - cleaned up from the reactor cleanup method. - """ - class Selectable(object): - """ - A stub Selectable which only has an interesting string - representation. - """ - def __repr__(self): - return "(SELECTABLE!)" - - reactor = StubReactor([], [Selectable()]) - jan = _Janitor(None, None, reactor=reactor) - self.assertEqual(jan._cleanReactor(), ["(SELECTABLE!)"]) - - - def test_postCaseCleanupNoErrors(self): - """ - The post-case cleanup method will return True and not call C{addError} - on the result if there are no pending calls. - """ - reactor = StubReactor([]) - test = object() - reporter = StubErrorReporter() - jan = _Janitor(test, reporter, reactor=reactor) - self.assertTrue(jan.postCaseCleanup()) - self.assertEqual(reporter.errors, []) - - - def test_postCaseCleanupWithErrors(self): - """ - The post-case cleanup method will return False and call C{addError} on - the result with a L{DirtyReactorAggregateError} Failure if there are - pending calls. - """ - delayedCall = DelayedCall(300, lambda: None, (), {}, - lambda x: None, lambda x: None, - seconds=lambda: 0) - delayedCallString = str(delayedCall) - reactor = StubReactor([delayedCall], []) - test = object() - reporter = StubErrorReporter() - jan = _Janitor(test, reporter, reactor=reactor) - self.assertFalse(jan.postCaseCleanup()) - self.assertEqual(len(reporter.errors), 1) - self.assertEqual(reporter.errors[0][1].value.delayedCalls, - [delayedCallString]) - - - def test_postClassCleanupNoErrors(self): - """ - The post-class cleanup method will not call C{addError} on the result - if there are no pending calls or selectables. - """ - reactor = StubReactor([]) - test = object() - reporter = StubErrorReporter() - jan = _Janitor(test, reporter, reactor=reactor) - jan.postClassCleanup() - self.assertEqual(reporter.errors, []) - - - def test_postClassCleanupWithPendingCallErrors(self): - """ - The post-class cleanup method call C{addError} on the result with a - L{DirtyReactorAggregateError} Failure if there are pending calls. - """ - delayedCall = DelayedCall(300, lambda: None, (), {}, - lambda x: None, lambda x: None, - seconds=lambda: 0) - delayedCallString = str(delayedCall) - reactor = StubReactor([delayedCall], []) - test = object() - reporter = StubErrorReporter() - jan = _Janitor(test, reporter, reactor=reactor) - jan.postClassCleanup() - self.assertEqual(len(reporter.errors), 1) - self.assertEqual(reporter.errors[0][1].value.delayedCalls, - [delayedCallString]) - - - def test_postClassCleanupWithSelectableErrors(self): - """ - The post-class cleanup method call C{addError} on the result with a - L{DirtyReactorAggregateError} Failure if there are selectables. - """ - selectable = "SELECTABLE HERE" - reactor = StubReactor([], [selectable]) - test = object() - reporter = StubErrorReporter() - jan = _Janitor(test, reporter, reactor=reactor) - jan.postClassCleanup() - self.assertEqual(len(reporter.errors), 1) - self.assertEqual(reporter.errors[0][1].value.selectables, - [repr(selectable)]) - diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_warning.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_warning.py deleted file mode 100755 index 9ad16528..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_warning.py +++ /dev/null @@ -1,472 +0,0 @@ -# Copyright (c) Twisted Matrix Laboratories. -# See LICENSE for details. - -""" -Tests for Trial's interaction with the Python warning system. -""" - -import sys, warnings -from StringIO import StringIO - -from twisted.python.filepath import FilePath -from twisted.trial.unittest import ( - SynchronousTestCase, _collectWarnings, _setWarningRegistryToNone) -from twisted.trial.reporter import TestResult - -class Mask(object): - """ - Hide a test case definition from trial's automatic discovery mechanism. - """ - class MockTests(SynchronousTestCase): - """ - A test case which is used by L{FlushWarningsTests} to verify behavior - which cannot be verified by code inside a single test method. - """ - message = "some warning text" - category = UserWarning - - def test_unflushed(self): - """ - Generate a warning and don't flush it. - """ - warnings.warn(self.message, self.category) - - - def test_flushed(self): - """ - Generate a warning and flush it. - """ - warnings.warn(self.message, self.category) - self.assertEqual(len(self.flushWarnings()), 1) - - - -class FlushWarningsTests(SynchronousTestCase): - """ - Tests for C{flushWarnings}, an API for examining the warnings - emitted so far in a test. - """ - - def assertDictSubset(self, set, subset): - """ - Assert that all the keys present in C{subset} are also present in - C{set} and that the corresponding values are equal. - """ - for k, v in subset.iteritems(): - self.assertEqual(set[k], v) - - - def assertDictSubsets(self, sets, subsets): - """ - For each pair of corresponding elements in C{sets} and C{subsets}, - assert that the element from C{subsets} is a subset of the element from - C{sets}. - """ - self.assertEqual(len(sets), len(subsets)) - for a, b in zip(sets, subsets): - self.assertDictSubset(a, b) - - - def test_none(self): - """ - If no warnings are emitted by a test, C{flushWarnings} returns an empty - list. - """ - self.assertEqual(self.flushWarnings(), []) - - - def test_several(self): - """ - If several warnings are emitted by a test, C{flushWarnings} returns a - list containing all of them. - """ - firstMessage = "first warning message" - firstCategory = UserWarning - warnings.warn(message=firstMessage, category=firstCategory) - - secondMessage = "second warning message" - secondCategory = RuntimeWarning - warnings.warn(message=secondMessage, category=secondCategory) - - self.assertDictSubsets( - self.flushWarnings(), - [{'category': firstCategory, 'message': firstMessage}, - {'category': secondCategory, 'message': secondMessage}]) - - - def test_repeated(self): - """ - The same warning triggered twice from the same place is included twice - in the list returned by C{flushWarnings}. - """ - message = "the message" - category = RuntimeWarning - for i in range(2): - warnings.warn(message=message, category=category) - - self.assertDictSubsets( - self.flushWarnings(), - [{'category': category, 'message': message}] * 2) - - - def test_cleared(self): - """ - After a particular warning event has been returned by C{flushWarnings}, - it is not returned by subsequent calls. - """ - message = "the message" - category = RuntimeWarning - warnings.warn(message=message, category=category) - self.assertDictSubsets( - self.flushWarnings(), - [{'category': category, 'message': message}]) - self.assertEqual(self.flushWarnings(), []) - - - def test_unflushed(self): - """ - Any warnings emitted by a test which are not flushed are emitted to the - Python warning system. - """ - result = TestResult() - case = Mask.MockTests('test_unflushed') - case.run(result) - warningsShown = self.flushWarnings([Mask.MockTests.test_unflushed]) - self.assertEqual(warningsShown[0]['message'], 'some warning text') - self.assertIdentical(warningsShown[0]['category'], UserWarning) - - where = case.test_unflushed.im_func.func_code - filename = where.co_filename - # If someone edits MockTests.test_unflushed, the value added to - # firstlineno might need to change. - lineno = where.co_firstlineno + 4 - - self.assertEqual(warningsShown[0]['filename'], filename) - self.assertEqual(warningsShown[0]['lineno'], lineno) - - self.assertEqual(len(warningsShown), 1) - - - def test_flushed(self): - """ - Any warnings emitted by a test which are flushed are not emitted to the - Python warning system. - """ - result = TestResult() - case = Mask.MockTests('test_flushed') - output = StringIO() - monkey = self.patch(sys, 'stdout', output) - case.run(result) - monkey.restore() - self.assertEqual(output.getvalue(), "") - - - def test_warningsConfiguredAsErrors(self): - """ - If a warnings filter has been installed which turns warnings into - exceptions, tests have an error added to the reporter for them for each - unflushed warning. - """ - class CustomWarning(Warning): - pass - - result = TestResult() - case = Mask.MockTests('test_unflushed') - case.category = CustomWarning - - originalWarnings = warnings.filters[:] - try: - warnings.simplefilter('error') - case.run(result) - self.assertEqual(len(result.errors), 1) - self.assertIdentical(result.errors[0][0], case) - result.errors[0][1].trap(CustomWarning) - finally: - warnings.filters[:] = originalWarnings - - - def test_flushedWarningsConfiguredAsErrors(self): - """ - If a warnings filter has been installed which turns warnings into - exceptions, tests which emit those warnings but flush them do not have - an error added to the reporter. - """ - class CustomWarning(Warning): - pass - - result = TestResult() - case = Mask.MockTests('test_flushed') - case.category = CustomWarning - - originalWarnings = warnings.filters[:] - try: - warnings.simplefilter('error') - case.run(result) - self.assertEqual(result.errors, []) - finally: - warnings.filters[:] = originalWarnings - - - def test_multipleFlushes(self): - """ - Any warnings emitted after a call to C{flushWarnings} can be flushed by - another call to C{flushWarnings}. - """ - warnings.warn("first message") - self.assertEqual(len(self.flushWarnings()), 1) - warnings.warn("second message") - self.assertEqual(len(self.flushWarnings()), 1) - - - def test_filterOnOffendingFunction(self): - """ - The list returned by C{flushWarnings} includes only those - warnings which refer to the source of the function passed as the value - for C{offendingFunction}, if a value is passed for that parameter. - """ - firstMessage = "first warning text" - firstCategory = UserWarning - def one(): - warnings.warn(firstMessage, firstCategory, stacklevel=1) - - secondMessage = "some text" - secondCategory = RuntimeWarning - def two(): - warnings.warn(secondMessage, secondCategory, stacklevel=1) - - one() - two() - - self.assertDictSubsets( - self.flushWarnings(offendingFunctions=[one]), - [{'category': firstCategory, 'message': firstMessage}]) - self.assertDictSubsets( - self.flushWarnings(offendingFunctions=[two]), - [{'category': secondCategory, 'message': secondMessage}]) - - - def test_functionBoundaries(self): - """ - Verify that warnings emitted at the very edges of a function are still - determined to be emitted from that function. - """ - def warner(): - warnings.warn("first line warning") - warnings.warn("internal line warning") - warnings.warn("last line warning") - - warner() - self.assertEqual( - len(self.flushWarnings(offendingFunctions=[warner])), 3) - - - def test_invalidFilter(self): - """ - If an object which is neither a function nor a method is included in the - C{offendingFunctions} list, C{flushWarnings} raises L{ValueError}. Such - a call flushes no warnings. - """ - warnings.warn("oh no") - self.assertRaises(ValueError, self.flushWarnings, [None]) - self.assertEqual(len(self.flushWarnings()), 1) - - - def test_missingSource(self): - """ - Warnings emitted by a function the source code of which is not - available can still be flushed. - """ - package = FilePath(self.mktemp()).child('twisted_private_helper') - package.makedirs() - package.child('__init__.py').setContent('') - package.child('missingsourcefile.py').setContent(''' -import warnings -def foo(): - warnings.warn("oh no") -''') - sys.path.insert(0, package.parent().path) - self.addCleanup(sys.path.remove, package.parent().path) - from twisted_private_helper import missingsourcefile - self.addCleanup(sys.modules.pop, 'twisted_private_helper') - self.addCleanup(sys.modules.pop, missingsourcefile.__name__) - package.child('missingsourcefile.py').remove() - - missingsourcefile.foo() - self.assertEqual(len(self.flushWarnings([missingsourcefile.foo])), 1) - - - def test_renamedSource(self): - """ - Warnings emitted by a function defined in a file which has been renamed - since it was initially compiled can still be flushed. - - This is testing the code which specifically supports working around the - unfortunate behavior of CPython to write a .py source file name into - the .pyc files it generates and then trust that it is correct in - various places. If source files are renamed, .pyc files may not be - regenerated, but they will contain incorrect filenames. - """ - package = FilePath(self.mktemp()).child('twisted_private_helper') - package.makedirs() - package.child('__init__.py').setContent('') - package.child('module.py').setContent(''' -import warnings -def foo(): - warnings.warn("oh no") -''') - sys.path.insert(0, package.parent().path) - self.addCleanup(sys.path.remove, package.parent().path) - - # Import it to cause pycs to be generated - from twisted_private_helper import module - - # Clean up the state resulting from that import; we're not going to use - # this module, so it should go away. - del sys.modules['twisted_private_helper'] - del sys.modules[module.__name__] - - # Rename the source directory - package.moveTo(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__) - - # Generate the warning - module.foo() - - # Flush it - self.assertEqual(len(self.flushWarnings([module.foo])), 1) - - - -class FakeWarning(Warning): - pass - - - -class CollectWarningsTests(SynchronousTestCase): - """ - Tests for L{_collectWarnings}. - """ - def test_callsObserver(self): - """ - L{_collectWarnings} calls the observer with each emitted warning. - """ - firstMessage = "dummy calls observer warning" - secondMessage = firstMessage[::-1] - events = [] - def f(): - events.append('call') - warnings.warn(firstMessage) - warnings.warn(secondMessage) - events.append('returning') - - _collectWarnings(events.append, f) - - self.assertEqual(events[0], 'call') - self.assertEqual(events[1].message, firstMessage) - self.assertEqual(events[2].message, secondMessage) - self.assertEqual(events[3], 'returning') - self.assertEqual(len(events), 4) - - - def test_suppresses(self): - """ - Any warnings emitted by a call to a function passed to - L{_collectWarnings} are not actually emitted to the warning system. - """ - output = StringIO() - self.patch(sys, 'stdout', output) - _collectWarnings(lambda x: None, warnings.warn, "text") - self.assertEqual(output.getvalue(), "") - - - def test_callsFunction(self): - """ - L{_collectWarnings} returns the result of calling the callable passed to - it with the parameters given. - """ - arguments = [] - value = object() - - def f(*args, **kwargs): - arguments.append((args, kwargs)) - return value - - result = _collectWarnings(lambda x: None, f, 1, 'a', b=2, c='d') - self.assertEqual(arguments, [((1, 'a'), {'b': 2, 'c': 'd'})]) - self.assertIdentical(result, value) - - - def test_duplicateWarningCollected(self): - """ - Subsequent emissions of a warning from a particular source site can be - collected by L{_collectWarnings}. In particular, the per-module - emitted-warning cache should be bypassed (I{__warningregistry__}). - """ - # Make sure the worst case is tested: if __warningregistry__ isn't in a - # module's globals, then the warning system will add it and start using - # it to avoid emitting duplicate warnings. Delete __warningregistry__ - # to ensure that even modules which are first imported as a test is - # running still interact properly with the warning system. - global __warningregistry__ - del __warningregistry__ - - def f(): - warnings.warn("foo") - warnings.simplefilter('default') - f() - events = [] - _collectWarnings(events.append, f) - self.assertEqual(len(events), 1) - self.assertEqual(events[0].message, "foo") - self.assertEqual(len(self.flushWarnings()), 1) - - - def test_immutableObject(self): - """ - L{_collectWarnings}'s behavior is not altered by the presence of an - object which cannot have attributes set on it as a value in - C{sys.modules}. - """ - key = object() - sys.modules[key] = key - self.addCleanup(sys.modules.pop, key) - self.test_duplicateWarningCollected() - - - def test_setWarningRegistryChangeWhileIterating(self): - """ - If the dictionary passed to L{_setWarningRegistryToNone} changes size - partway through the process, C{_setWarningRegistryToNone} continues to - set C{__warningregistry__} to C{None} on the rest of the values anyway. - - - This might be caused by C{sys.modules} containing something that's not - really a module and imports things on setattr. py.test does this, as - does L{twisted.python.deprecate.deprecatedModuleAttribute}. - """ - d = {} - - class A(object): - def __init__(self, key): - self.__dict__['_key'] = key - - def __setattr__(self, value, item): - d[self._key] = None - - key1 = object() - key2 = object() - d[key1] = A(key2) - - key3 = object() - key4 = object() - d[key3] = A(key4) - - _setWarningRegistryToNone(d) - - # If both key2 and key4 were added, then both A instanced were - # processed. - self.assertEqual(set([key1, key2, key3, key4]), set(d.keys())) diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/weird.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/weird.py deleted file mode 100755 index 3533f56a..00000000 --- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/weird.py +++ /dev/null @@ -1,22 +0,0 @@ -from __future__ import division - -from twisted.trial import unittest -from twisted.internet import defer - -# Used in test_tests.TestUnhandledDeferred - -class TestBleeding(unittest.TestCase): - """This test creates an unhandled Deferred and leaves it in a cycle. - - The Deferred is left in a cycle so that the garbage collector won't pick it - up immediately. We were having some problems where unhandled Deferreds in - one test were failing random other tests. (See #1507, #1213) - """ - def test_unhandledDeferred(self): - try: - 1/0 - except ZeroDivisionError: - f = defer.fail() - # these two lines create the cycle. don't remove them - l = [f] - l.append(l) |