aboutsummaryrefslogtreecommitdiffstats
path: root/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial
diff options
context:
space:
mode:
Diffstat (limited to 'lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial')
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/__init__.py52
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/itrial.py251
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/reporter.py1245
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/runner.py861
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/__init__.py1
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/detests.py201
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/erroneous.py167
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite.py21
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite2.py21
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockcustomsuite3.py28
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/mockdoctest.py104
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/moduleself.py7
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/moduletest.py11
-rw-r--r--lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/notpython2
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/novars.py6
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/packages.py156
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/sample.py108
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/scripttest.py14
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/skipping.py268
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/suppression.py112
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_assertions.py1026
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_deferred.py220
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_doctest.py64
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_keyboard.py113
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_loader.py611
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_log.py235
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_output.py162
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_plugins.py46
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_pyunitcompat.py222
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_reporter.py1650
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_runner.py1034
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_script.py443
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_test_visitor.py82
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_testcase.py68
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_tests.py1379
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_util.py584
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/test_warning.py472
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/test/weird.py22
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/unittest.py1778
-rwxr-xr-xlib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/util.py430
40 files changed, 0 insertions, 14277 deletions
diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/__init__.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/__init__.py
deleted file mode 100755
index ad9423c1..00000000
--- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/__init__.py
+++ /dev/null
@@ -1,52 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-#
-# Maintainer: Jonathan Lange
-
-"""
-Asynchronous unit testing framework.
-
-Trial extends Python's builtin C{unittest} to provide support for asynchronous
-tests.
-
-Maintainer: Jonathan Lange
-
-Trial strives to be compatible with other Python xUnit testing frameworks.
-"Compatibility" is a difficult things to define. In practice, it means that:
-
- - L{twisted.trial.unittest.TestCase} objects should be able to be used by
- other test runners without those runners requiring special support for
- Trial tests.
-
- - Tests that subclass the standard library C{TestCase} and don't do anything
- "too weird" should be able to be discoverable and runnable by the Trial
- test runner without the authors of those tests having to jump through
- hoops.
-
- - Tests that implement the interface provided by the standard library
- C{TestCase} should be runnable by the Trial runner.
-
- - The Trial test runner and Trial L{unittest.TestCase} objects ought to be
- able to use standard library C{TestResult} objects, and third party
- C{TestResult} objects based on the standard library.
-
-This list is not necessarily exhaustive -- compatibility is hard to define.
-Contributors who discover more helpful ways of defining compatibility are
-encouraged to update this document.
-
-
-Examples:
-
-B{Timeouts} for tests should be implemented in the runner. If this is done,
-then timeouts could work for third-party TestCase objects as well as for
-L{twisted.trial.unittest.TestCase} objects. Further, Twisted C{TestCase}
-objects will run in other runners without timing out.
-See U{http://twistedmatrix.com/trac/ticket/2675}.
-
-Running tests in a temporary directory should be a feature of the test case,
-because often tests themselves rely on this behaviour. If the feature is
-implemented in the runner, then tests will change behaviour (possibly
-breaking) when run in a different test runner. Further, many tests don't even
-care about the filesystem.
-See U{http://twistedmatrix.com/trac/ticket/2916}.
-"""
diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/itrial.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/itrial.py
deleted file mode 100755
index d92884c2..00000000
--- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/itrial.py
+++ /dev/null
@@ -1,251 +0,0 @@
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Interfaces for Trial.
-
-Maintainer: Jonathan Lange
-"""
-
-import zope.interface as zi
-from zope.interface import Attribute
-
-
-class ITestCase(zi.Interface):
- """
- The interface that a test case must implement in order to be used in Trial.
- """
-
- failureException = zi.Attribute(
- "The exception class that is raised by failed assertions")
-
-
- def __call__(result):
- """
- Run the test. Should always do exactly the same thing as run().
- """
-
-
- def countTestCases():
- """
- Return the number of tests in this test case. Usually 1.
- """
-
-
- def id():
- """
- Return a unique identifier for the test, usually the fully-qualified
- Python name.
- """
-
-
- def run(result):
- """
- Run the test, storing the results in C{result}.
-
- @param result: A L{TestResult}.
- """
-
-
- def shortDescription():
- """
- Return a short description of the test.
- """
-
-
-
-class IReporter(zi.Interface):
- """
- I report results from a run of a test suite.
- """
-
- stream = zi.Attribute(
- "Deprecated in Twisted 8.0. "
- "The io-stream that this reporter will write to")
- tbformat = zi.Attribute("Either 'default', 'brief', or 'verbose'")
- args = zi.Attribute(
- "Additional string argument passed from the command line")
- shouldStop = zi.Attribute(
- """
- A boolean indicating that this reporter would like the test run to stop.
- """)
- separator = Attribute(
- "Deprecated in Twisted 8.0. "
- "A value which will occasionally be passed to the L{write} method.")
- testsRun = Attribute(
- """
- The number of tests that seem to have been run according to this
- reporter.
- """)
-
-
- def startTest(method):
- """
- Report the beginning of a run of a single test method.
-
- @param method: an object that is adaptable to ITestMethod
- """
-
-
- def stopTest(method):
- """
- Report the status of a single test method
-
- @param method: an object that is adaptable to ITestMethod
- """
-
-
- def startSuite(name):
- """
- Deprecated in Twisted 8.0.
-
- Suites which wish to appear in reporter output should call this
- before running their tests.
- """
-
-
- def endSuite(name):
- """
- Deprecated in Twisted 8.0.
-
- Called at the end of a suite, if and only if that suite has called
- C{startSuite}.
- """
-
-
- def cleanupErrors(errs):
- """
- Deprecated in Twisted 8.0.
-
- Called when the reactor has been left in a 'dirty' state
-
- @param errs: a list of L{twisted.python.failure.Failure}s
- """
-
-
- def upDownError(userMeth, warn=True, printStatus=True):
- """
- Deprecated in Twisted 8.0.
-
- Called when an error occurs in a setUp* or tearDown* method
-
- @param warn: indicates whether or not the reporter should emit a
- warning about the error
- @type warn: Boolean
- @param printStatus: indicates whether or not the reporter should
- print the name of the method and the status
- message appropriate for the type of error
- @type printStatus: Boolean
- """
-
-
- def addSuccess(test):
- """
- Record that test passed.
- """
-
-
- def addError(test, error):
- """
- Record that a test has raised an unexpected exception.
-
- @param test: The test that has raised an error.
- @param error: The error that the test raised. It will either be a
- three-tuple in the style of C{sys.exc_info()} or a
- L{Failure<twisted.python.failure.Failure>} object.
- """
-
-
- def addFailure(test, failure):
- """
- Record that a test has failed with the given failure.
-
- @param test: The test that has failed.
- @param failure: The failure that the test failed with. It will
- either be a three-tuple in the style of C{sys.exc_info()}
- or a L{Failure<twisted.python.failure.Failure>} object.
- """
-
-
- def addExpectedFailure(test, failure, todo):
- """
- Record that the given test failed, and was expected to do so.
-
- @type test: L{pyunit.TestCase}
- @param test: The test which this is about.
- @type error: L{failure.Failure}
- @param error: The error which this test failed with.
- @type todo: L{unittest.Todo}
- @param todo: The reason for the test's TODO status.
- """
-
-
- def addUnexpectedSuccess(test, todo):
- """
- Record that the given test failed, and was expected to do so.
-
- @type test: L{pyunit.TestCase}
- @param test: The test which this is about.
- @type todo: L{unittest.Todo}
- @param todo: The reason for the test's TODO status.
- """
-
-
- def addSkip(test, reason):
- """
- Record that a test has been skipped for the given reason.
-
- @param test: The test that has been skipped.
- @param reason: An object that the test case has specified as the reason
- for skipping the test.
- """
-
-
- def printSummary():
- """
- Deprecated in Twisted 8.0, use L{done} instead.
-
- Present a summary of the test results.
- """
-
-
- def printErrors():
- """
- Deprecated in Twisted 8.0, use L{done} instead.
-
- Present the errors that have occured during the test run. This method
- will be called after all tests have been run.
- """
-
-
- def write(string):
- """
- Deprecated in Twisted 8.0, use L{done} instead.
-
- Display a string to the user, without appending a new line.
- """
-
-
- def writeln(string):
- """
- Deprecated in Twisted 8.0, use L{done} instead.
-
- Display a string to the user, appending a new line.
- """
-
- def wasSuccessful():
- """
- Return a boolean indicating whether all test results that were reported
- to this reporter were successful or not.
- """
-
-
- def done():
- """
- Called when the test run is complete.
-
- This gives the result object an opportunity to display a summary of
- information to the user. Once you have called C{done} on an
- L{IReporter} object, you should assume that the L{IReporter} object is
- no longer usable.
- """
diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/reporter.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/reporter.py
deleted file mode 100755
index 27067f8b..00000000
--- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/reporter.py
+++ /dev/null
@@ -1,1245 +0,0 @@
-# -*- test-case-name: twisted.trial.test.test_reporter -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-#
-# Maintainer: Jonathan Lange
-
-"""
-Defines classes that handle the results of tests.
-"""
-
-import sys, os
-import time
-import warnings
-
-from twisted.python.compat import set
-from twisted.python import reflect, log
-from twisted.python.components import proxyForInterface
-from twisted.python.failure import Failure
-from twisted.python.util import OrderedDict, untilConcludes
-from twisted.trial import itrial, util
-
-try:
- from subunit import TestProtocolClient
-except ImportError:
- TestProtocolClient = None
-from zope.interface import implements
-
-pyunit = __import__('unittest')
-
-
-class BrokenTestCaseWarning(Warning):
- """
- Emitted as a warning when an exception occurs in one of setUp or tearDown.
- """
-
-
-class SafeStream(object):
- """
- Wraps a stream object so that all C{write} calls are wrapped in
- L{untilConcludes}.
- """
-
- def __init__(self, original):
- self.original = original
-
- def __getattr__(self, name):
- return getattr(self.original, name)
-
- def write(self, *a, **kw):
- return untilConcludes(self.original.write, *a, **kw)
-
-
-class TestResult(pyunit.TestResult, object):
- """
- Accumulates the results of several L{twisted.trial.unittest.TestCase}s.
-
- @ivar successes: count the number of successes achieved by the test run.
- @type successes: C{int}
- """
- implements(itrial.IReporter)
-
- def __init__(self):
- super(TestResult, self).__init__()
- self.skips = []
- self.expectedFailures = []
- self.unexpectedSuccesses = []
- self.successes = 0
- self._timings = []
-
- def __repr__(self):
- return ('<%s run=%d errors=%d failures=%d todos=%d dones=%d skips=%d>'
- % (reflect.qual(self.__class__), self.testsRun,
- len(self.errors), len(self.failures),
- len(self.expectedFailures), len(self.skips),
- len(self.unexpectedSuccesses)))
-
- def _getTime(self):
- return time.time()
-
- def _getFailure(self, error):
- """
- Convert a C{sys.exc_info()}-style tuple to a L{Failure}, if necessary.
- """
- if isinstance(error, tuple):
- return Failure(error[1], error[0], error[2])
- return error
-
- def startTest(self, test):
- """
- This must be called before the given test is commenced.
-
- @type test: L{pyunit.TestCase}
- """
- super(TestResult, self).startTest(test)
- self._testStarted = self._getTime()
-
- def stopTest(self, test):
- """
- This must be called after the given test is completed.
-
- @type test: L{pyunit.TestCase}
- """
- super(TestResult, self).stopTest(test)
- self._lastTime = self._getTime() - self._testStarted
-
- def addFailure(self, test, fail):
- """
- Report a failed assertion for the given test.
-
- @type test: L{pyunit.TestCase}
- @type fail: L{Failure} or L{tuple}
- """
- self.failures.append((test, self._getFailure(fail)))
-
- def addError(self, test, error):
- """
- Report an error that occurred while running the given test.
-
- @type test: L{pyunit.TestCase}
- @type error: L{Failure} or L{tuple}
- """
- self.errors.append((test, self._getFailure(error)))
-
- def addSkip(self, test, reason):
- """
- Report that the given test was skipped.
-
- In Trial, tests can be 'skipped'. Tests are skipped mostly because there
- is some platform or configuration issue that prevents them from being
- run correctly.
-
- @type test: L{pyunit.TestCase}
- @type reason: L{str}
- """
- self.skips.append((test, reason))
-
- def addUnexpectedSuccess(self, test, todo):
- """Report that the given test succeeded against expectations.
-
- In Trial, tests can be marked 'todo'. That is, they are expected to fail.
- When a test that is expected to fail instead succeeds, it should call
- this method to report the unexpected success.
-
- @type test: L{pyunit.TestCase}
- @type todo: L{unittest.Todo}
- """
- # XXX - 'todo' should just be a string
- self.unexpectedSuccesses.append((test, todo))
-
- def addExpectedFailure(self, test, error, todo):
- """Report that the given test failed, and was expected to do so.
-
- In Trial, tests can be marked 'todo'. That is, they are expected to fail.
-
- @type test: L{pyunit.TestCase}
- @type error: L{Failure}
- @type todo: L{unittest.Todo}
- """
- # XXX - 'todo' should just be a string
- self.expectedFailures.append((test, error, todo))
-
- def addSuccess(self, test):
- """Report that the given test succeeded.
-
- @type test: L{pyunit.TestCase}
- """
- self.successes += 1
-
- def upDownError(self, method, error, warn, printStatus):
- warnings.warn("upDownError is deprecated in Twisted 8.0.",
- category=DeprecationWarning, stacklevel=3)
-
- def cleanupErrors(self, errs):
- """Report an error that occurred during the cleanup between tests.
- """
- warnings.warn("Cleanup errors are actual errors. Use addError. "
- "Deprecated in Twisted 8.0",
- category=DeprecationWarning, stacklevel=2)
-
- def startSuite(self, name):
- warnings.warn("startSuite deprecated in Twisted 8.0",
- category=DeprecationWarning, stacklevel=2)
-
- def endSuite(self, name):
- warnings.warn("endSuite deprecated in Twisted 8.0",
- category=DeprecationWarning, stacklevel=2)
-
-
- def done(self):
- """
- The test suite has finished running.
- """
-
-
-
-class TestResultDecorator(proxyForInterface(itrial.IReporter,
- "_originalReporter")):
- """
- Base class for TestResult decorators.
-
- @ivar _originalReporter: The wrapped instance of reporter.
- @type _originalReporter: A provider of L{itrial.IReporter}
- """
-
- implements(itrial.IReporter)
-
-
-
-class UncleanWarningsReporterWrapper(TestResultDecorator):
- """
- A wrapper for a reporter that converts L{util.DirtyReactorAggregateError}s
- to warnings.
- """
- implements(itrial.IReporter)
-
- def addError(self, test, error):
- """
- If the error is a L{util.DirtyReactorAggregateError}, instead of
- reporting it as a normal error, throw a warning.
- """
-
- if (isinstance(error, Failure)
- and error.check(util.DirtyReactorAggregateError)):
- warnings.warn(error.getErrorMessage())
- else:
- self._originalReporter.addError(test, error)
-
-
-
-class _AdaptedReporter(TestResultDecorator):
- """
- TestResult decorator that makes sure that addError only gets tests that
- have been adapted with a particular test adapter.
- """
-
- def __init__(self, original, testAdapter):
- """
- Construct an L{_AdaptedReporter}.
-
- @param original: An {itrial.IReporter}.
- @param testAdapter: A callable that returns an L{itrial.ITestCase}.
- """
- TestResultDecorator.__init__(self, original)
- self.testAdapter = testAdapter
-
-
- def addError(self, test, error):
- """
- See L{itrial.IReporter}.
- """
- test = self.testAdapter(test)
- return self._originalReporter.addError(test, error)
-
-
- def addExpectedFailure(self, test, failure, todo):
- """
- See L{itrial.IReporter}.
- """
- return self._originalReporter.addExpectedFailure(
- self.testAdapter(test), failure, todo)
-
-
- def addFailure(self, test, failure):
- """
- See L{itrial.IReporter}.
- """
- test = self.testAdapter(test)
- return self._originalReporter.addFailure(test, failure)
-
-
- def addSkip(self, test, skip):
- """
- See L{itrial.IReporter}.
- """
- test = self.testAdapter(test)
- return self._originalReporter.addSkip(test, skip)
-
-
- def addUnexpectedSuccess(self, test, todo):
- """
- See L{itrial.IReporter}.
- """
- test = self.testAdapter(test)
- return self._originalReporter.addUnexpectedSuccess(test, todo)
-
-
- def startTest(self, test):
- """
- See L{itrial.IReporter}.
- """
- return self._originalReporter.startTest(self.testAdapter(test))
-
-
- def stopTest(self, test):
- """
- See L{itrial.IReporter}.
- """
- return self._originalReporter.stopTest(self.testAdapter(test))
-
-
-
-class Reporter(TestResult):
- """
- A basic L{TestResult} with support for writing to a stream.
-
- @ivar _startTime: The time when the first test was started. It defaults to
- C{None}, which means that no test was actually launched.
- @type _startTime: C{float} or C{NoneType}
-
- @ivar _warningCache: A C{set} of tuples of warning message (file, line,
- text, category) which have already been written to the output stream
- during the currently executing test. This is used to avoid writing
- duplicates of the same warning to the output stream.
- @type _warningCache: C{set}
-
- @ivar _publisher: The log publisher which will be observed for warning
- events.
- @type _publisher: L{LogPublisher} (or another type sufficiently similar)
- """
-
- implements(itrial.IReporter)
-
- _separator = '-' * 79
- _doubleSeparator = '=' * 79
-
- def __init__(self, stream=sys.stdout, tbformat='default', realtime=False,
- publisher=None):
- super(Reporter, self).__init__()
- self._stream = SafeStream(stream)
- self.tbformat = tbformat
- self.realtime = realtime
- self._startTime = None
- self._warningCache = set()
-
- # Start observing log events so as to be able to report warnings.
- self._publisher = publisher
- if publisher is not None:
- publisher.addObserver(self._observeWarnings)
-
-
- def _observeWarnings(self, event):
- """
- Observe warning events and write them to C{self._stream}.
-
- This method is a log observer which will be registered with
- C{self._publisher.addObserver}.
-
- @param event: A C{dict} from the logging system. If it has a
- C{'warning'} key, a logged warning will be extracted from it and
- possibly written to C{self.stream}.
- """
- if 'warning' in event:
- key = (event['filename'], event['lineno'],
- event['category'].split('.')[-1],
- str(event['warning']))
- if key not in self._warningCache:
- self._warningCache.add(key)
- self._stream.write('%s:%s: %s: %s\n' % key)
-
-
- def stream(self):
- warnings.warn("stream is deprecated in Twisted 8.0.",
- category=DeprecationWarning, stacklevel=2)
- return self._stream
- stream = property(stream)
-
-
- def separator(self):
- warnings.warn("separator is deprecated in Twisted 8.0.",
- category=DeprecationWarning, stacklevel=2)
- return self._separator
- separator = property(separator)
-
-
- def startTest(self, test):
- """
- Called when a test begins to run. Records the time when it was first
- called and resets the warning cache.
-
- @param test: L{ITestCase}
- """
- super(Reporter, self).startTest(test)
- if self._startTime is None:
- self._startTime = self._getTime()
- self._warningCache = set()
-
-
- def addFailure(self, test, fail):
- """
- Called when a test fails. If L{realtime} is set, then it prints the
- error to the stream.
-
- @param test: L{ITestCase} that failed.
- @param fail: L{failure.Failure} containing the error.
- """
- super(Reporter, self).addFailure(test, fail)
- if self.realtime:
- fail = self.failures[-1][1] # guarantee it's a Failure
- self._write(self._formatFailureTraceback(fail))
-
-
- def addError(self, test, error):
- """
- Called when a test raises an error. If L{realtime} is set, then it
- prints the error to the stream.
-
- @param test: L{ITestCase} that raised the error.
- @param error: L{failure.Failure} containing the error.
- """
- error = self._getFailure(error)
- super(Reporter, self).addError(test, error)
- if self.realtime:
- error = self.errors[-1][1] # guarantee it's a Failure
- self._write(self._formatFailureTraceback(error))
-
-
- def write(self, format, *args):
- warnings.warn("write is deprecated in Twisted 8.0.",
- category=DeprecationWarning, stacklevel=2)
- self._write(format, *args)
-
-
- def _write(self, format, *args):
- """
- Safely write to the reporter's stream.
-
- @param format: A format string to write.
- @param *args: The arguments for the format string.
- """
- s = str(format)
- assert isinstance(s, type(''))
- if args:
- self._stream.write(s % args)
- else:
- self._stream.write(s)
- untilConcludes(self._stream.flush)
-
-
- def writeln(self, format, *args):
- warnings.warn("writeln is deprecated in Twisted 8.0.",
- category=DeprecationWarning, stacklevel=2)
- self._writeln(format, *args)
-
-
- def _writeln(self, format, *args):
- """
- Safely write a line to the reporter's stream. Newline is appended to
- the format string.
-
- @param format: A format string to write.
- @param *args: The arguments for the format string.
- """
- self._write(format, *args)
- self._write('\n')
-
-
- def upDownError(self, method, error, warn, printStatus):
- super(Reporter, self).upDownError(method, error, warn, printStatus)
- if warn:
- tbStr = self._formatFailureTraceback(error)
- log.msg(tbStr)
- msg = ("caught exception in %s, your TestCase is broken\n\n%s"
- % (method, tbStr))
- warnings.warn(msg, BrokenTestCaseWarning, stacklevel=2)
-
-
- def cleanupErrors(self, errs):
- super(Reporter, self).cleanupErrors(errs)
- warnings.warn("%s\n%s" % ("REACTOR UNCLEAN! traceback(s) follow: ",
- self._formatFailureTraceback(errs)),
- BrokenTestCaseWarning)
-
-
- def _trimFrames(self, frames):
- # when a SynchronousTestCase method fails synchronously, the stack looks
- # like this:
- # [0]: SynchronousTestCase._run
- # [1]: utils.runWithWarningsSuppressed
- # [2:-2]: code in the test method which failed
- # [-1]: unittst.fail
-
- # when a TestCase method fails synchronously, the stack looks like this:
- # [0]: defer.maybeDeferred()
- # [1]: utils.runWithWarningsSuppressed()
- # [2:-2]: code in the test method which failed
- # [-1]: unittest.fail
-
- # when a method fails inside a Deferred (i.e., when the test method
- # returns a Deferred, and that Deferred's errback fires), the stack
- # captured inside the resulting Failure looks like this:
- # [0]: defer.Deferred._runCallbacks
- # [1:-2]: code in the testmethod which failed
- # [-1]: unittest.fail
-
- # as a result, we want to trim either [maybeDeferred,runWWS] or
- # [Deferred._runCallbacks] or [SynchronousTestCase._run] from the front,
- # and trim the [unittest.fail] from the end.
-
- # There is also another case, when the test method is badly defined and
- # contains extra arguments.
-
- newFrames = list(frames)
-
- if len(frames) < 2:
- return newFrames
-
- firstMethod = newFrames[0][0]
- firstFile = os.path.splitext(os.path.basename(newFrames[0][1]))[0]
-
- secondMethod = newFrames[1][0]
- secondFile = os.path.splitext(os.path.basename(newFrames[1][1]))[0]
-
- supp = ("runWithWarningsSuppressed", "utils")
- syncCase = (("_run", "unittest"), supp)
- asyncCase = (("maybeDeferred", "defer"), supp)
-
- twoFrames = ((firstMethod, firstFile), (secondMethod, secondFile))
- if twoFrames in [syncCase, asyncCase]:
- newFrames = newFrames[2:]
- elif (firstMethod, firstFile) == ("_runCallbacks", "defer"):
- newFrames = newFrames[1:]
-
- if not newFrames:
- # The method fails before getting called, probably an argument problem
- return newFrames
-
- last = newFrames[-1]
- if (last[0].startswith('fail')
- and os.path.splitext(os.path.basename(last[1]))[0] == 'unittest'):
- newFrames = newFrames[:-1]
-
- return newFrames
-
-
- def _formatFailureTraceback(self, fail):
- if isinstance(fail, str):
- return fail.rstrip() + '\n'
- fail.frames, frames = self._trimFrames(fail.frames), fail.frames
- result = fail.getTraceback(detail=self.tbformat, elideFrameworkCode=True)
- fail.frames = frames
- return result
-
-
- def _groupResults(self, results, formatter):
- """
- Group tests together based on their results.
-
- @param results: An iterable of tuples of two or more elements. The
- first element of each tuple is a test case. The remaining
- elements describe the outcome of that test case.
-
- @param formatter: A callable which turns a test case result into a
- string. The elements after the first of the tuples in
- C{results} will be passed as positional arguments to
- C{formatter}.
-
- @return: A C{list} of two-tuples. The first element of each tuple
- is a unique string describing one result from at least one of
- the test cases in C{results}. The second element is a list of
- the test cases which had that result.
- """
- groups = OrderedDict()
- for content in results:
- case = content[0]
- outcome = content[1:]
- key = formatter(*outcome)
- groups.setdefault(key, []).append(case)
- return groups.items()
-
-
- def _printResults(self, flavor, errors, formatter):
- """
- Print a group of errors to the stream.
-
- @param flavor: A string indicating the kind of error (e.g. 'TODO').
- @param errors: A list of errors, often L{failure.Failure}s, but
- sometimes 'todo' errors.
- @param formatter: A callable that knows how to format the errors.
- """
- for reason, cases in self._groupResults(errors, formatter):
- self._writeln(self._doubleSeparator)
- self._writeln(flavor)
- self._write(reason)
- self._writeln('')
- for case in cases:
- self._writeln(case.id())
-
-
- def _printExpectedFailure(self, error, todo):
- return 'Reason: %r\n%s' % (todo.reason,
- self._formatFailureTraceback(error))
-
-
- def _printUnexpectedSuccess(self, todo):
- ret = 'Reason: %r\n' % (todo.reason,)
- if todo.errors:
- ret += 'Expected errors: %s\n' % (', '.join(todo.errors),)
- return ret
-
-
- def printErrors(self):
- """
- Print all of the non-success results in full to the stream.
- """
- warnings.warn("printErrors is deprecated in Twisted 8.0.",
- category=DeprecationWarning, stacklevel=2)
- self._printErrors()
-
-
- def _printErrors(self):
- """
- Print all of the non-success results to the stream in full.
- """
- self._write('\n')
- self._printResults('[SKIPPED]', self.skips, lambda x : '%s\n' % x)
- self._printResults('[TODO]', self.expectedFailures,
- self._printExpectedFailure)
- self._printResults('[FAIL]', self.failures,
- self._formatFailureTraceback)
- self._printResults('[ERROR]', self.errors,
- self._formatFailureTraceback)
- self._printResults('[SUCCESS!?!]', self.unexpectedSuccesses,
- self._printUnexpectedSuccess)
-
-
- def _getSummary(self):
- """
- Return a formatted count of tests status results.
- """
- summaries = []
- for stat in ("skips", "expectedFailures", "failures", "errors",
- "unexpectedSuccesses"):
- num = len(getattr(self, stat))
- if num:
- summaries.append('%s=%d' % (stat, num))
- if self.successes:
- summaries.append('successes=%d' % (self.successes,))
- summary = (summaries and ' ('+', '.join(summaries)+')') or ''
- return summary
-
-
- def printSummary(self):
- """
- Print a line summarising the test results to the stream.
- """
- warnings.warn("printSummary is deprecated in Twisted 8.0.",
- category=DeprecationWarning, stacklevel=2)
- self._printSummary()
-
-
- def _printSummary(self):
- """
- Print a line summarising the test results to the stream.
- """
- summary = self._getSummary()
- if self.wasSuccessful():
- status = "PASSED"
- else:
- status = "FAILED"
- self._write("%s%s\n", status, summary)
-
-
- def done(self):
- """
- Summarize the result of the test run.
-
- The summary includes a report of all of the errors, todos, skips and
- so forth that occurred during the run. It also includes the number of
- tests that were run and how long it took to run them (not including
- load time).
-
- Expects that L{_printErrors}, L{_writeln}, L{_write}, L{_printSummary}
- and L{_separator} are all implemented.
- """
- if self._publisher is not None:
- self._publisher.removeObserver(self._observeWarnings)
- self._printErrors()
- self._writeln(self._separator)
- if self._startTime is not None:
- self._writeln('Ran %d tests in %.3fs', self.testsRun,
- time.time() - self._startTime)
- self._write('\n')
- self._printSummary()
-
-
-
-class MinimalReporter(Reporter):
- """
- A minimalist reporter that prints only a summary of the test result, in
- the form of (timeTaken, #tests, #tests, #errors, #failures, #skips).
- """
-
- def _printErrors(self):
- """
- Don't print a detailed summary of errors. We only care about the
- counts.
- """
-
-
- def _printSummary(self):
- """
- Print out a one-line summary of the form:
- '%(runtime) %(number_of_tests) %(number_of_tests) %(num_errors)
- %(num_failures) %(num_skips)'
- """
- numTests = self.testsRun
- if self._startTime is not None:
- timing = self._getTime() - self._startTime
- else:
- timing = 0
- t = (timing, numTests, numTests,
- len(self.errors), len(self.failures), len(self.skips))
- self._writeln(' '.join(map(str, t)))
-
-
-
-class TextReporter(Reporter):
- """
- Simple reporter that prints a single character for each test as it runs,
- along with the standard Trial summary text.
- """
-
- def addSuccess(self, test):
- super(TextReporter, self).addSuccess(test)
- self._write('.')
-
-
- def addError(self, *args):
- super(TextReporter, self).addError(*args)
- self._write('E')
-
-
- def addFailure(self, *args):
- super(TextReporter, self).addFailure(*args)
- self._write('F')
-
-
- def addSkip(self, *args):
- super(TextReporter, self).addSkip(*args)
- self._write('S')
-
-
- def addExpectedFailure(self, *args):
- super(TextReporter, self).addExpectedFailure(*args)
- self._write('T')
-
-
- def addUnexpectedSuccess(self, *args):
- super(TextReporter, self).addUnexpectedSuccess(*args)
- self._write('!')
-
-
-
-class VerboseTextReporter(Reporter):
- """
- A verbose reporter that prints the name of each test as it is running.
-
- Each line is printed with the name of the test, followed by the result of
- that test.
- """
-
- # This is actually the bwverbose option
-
- def startTest(self, tm):
- self._write('%s ... ', tm.id())
- super(VerboseTextReporter, self).startTest(tm)
-
-
- def addSuccess(self, test):
- super(VerboseTextReporter, self).addSuccess(test)
- self._write('[OK]')
-
-
- def addError(self, *args):
- super(VerboseTextReporter, self).addError(*args)
- self._write('[ERROR]')
-
-
- def addFailure(self, *args):
- super(VerboseTextReporter, self).addFailure(*args)
- self._write('[FAILURE]')
-
-
- def addSkip(self, *args):
- super(VerboseTextReporter, self).addSkip(*args)
- self._write('[SKIPPED]')
-
-
- def addExpectedFailure(self, *args):
- super(VerboseTextReporter, self).addExpectedFailure(*args)
- self._write('[TODO]')
-
-
- def addUnexpectedSuccess(self, *args):
- super(VerboseTextReporter, self).addUnexpectedSuccess(*args)
- self._write('[SUCCESS!?!]')
-
-
- def stopTest(self, test):
- super(VerboseTextReporter, self).stopTest(test)
- self._write('\n')
-
-
-
-class TimingTextReporter(VerboseTextReporter):
- """
- Prints out each test as it is running, followed by the time taken for each
- test to run.
- """
-
- def stopTest(self, method):
- """
- Mark the test as stopped, and write the time it took to run the test
- to the stream.
- """
- super(TimingTextReporter, self).stopTest(method)
- self._write("(%.03f secs)\n" % self._lastTime)
-
-
-
-class _AnsiColorizer(object):
- """
- A colorizer is an object that loosely wraps around a stream, allowing
- callers to write text to the stream in a particular color.
-
- Colorizer classes must implement C{supported()} and C{write(text, color)}.
- """
- _colors = dict(black=30, red=31, green=32, yellow=33,
- blue=34, magenta=35, cyan=36, white=37)
-
- def __init__(self, stream):
- self.stream = stream
-
- def supported(cls, stream=sys.stdout):
- """
- A class method that returns True if the current platform supports
- coloring terminal output using this method. Returns False otherwise.
- """
- if not stream.isatty():
- return False # auto color only on TTYs
- try:
- import curses
- except ImportError:
- return False
- else:
- try:
- try:
- return curses.tigetnum("colors") > 2
- except curses.error:
- curses.setupterm()
- return curses.tigetnum("colors") > 2
- except:
- # guess false in case of error
- return False
- supported = classmethod(supported)
-
- def write(self, text, color):
- """
- Write the given text to the stream in the given color.
-
- @param text: Text to be written to the stream.
-
- @param color: A string label for a color. e.g. 'red', 'white'.
- """
- color = self._colors[color]
- self.stream.write('\x1b[%s;1m%s\x1b[0m' % (color, text))
-
-
-class _Win32Colorizer(object):
- """
- See _AnsiColorizer docstring.
- """
- def __init__(self, stream):
- from win32console import GetStdHandle, STD_OUTPUT_HANDLE, \
- FOREGROUND_RED, FOREGROUND_BLUE, FOREGROUND_GREEN, \
- FOREGROUND_INTENSITY
- red, green, blue, bold = (FOREGROUND_RED, FOREGROUND_GREEN,
- FOREGROUND_BLUE, FOREGROUND_INTENSITY)
- self.stream = stream
- self.screenBuffer = GetStdHandle(STD_OUTPUT_HANDLE)
- self._colors = {
- 'normal': red | green | blue,
- 'red': red | bold,
- 'green': green | bold,
- 'blue': blue | bold,
- 'yellow': red | green | bold,
- 'magenta': red | blue | bold,
- 'cyan': green | blue | bold,
- 'white': red | green | blue | bold
- }
-
- def supported(cls, stream=sys.stdout):
- try:
- import win32console
- screenBuffer = win32console.GetStdHandle(
- win32console.STD_OUTPUT_HANDLE)
- except ImportError:
- return False
- import pywintypes
- try:
- screenBuffer.SetConsoleTextAttribute(
- win32console.FOREGROUND_RED |
- win32console.FOREGROUND_GREEN |
- win32console.FOREGROUND_BLUE)
- except pywintypes.error:
- return False
- else:
- return True
- supported = classmethod(supported)
-
- def write(self, text, color):
- color = self._colors[color]
- self.screenBuffer.SetConsoleTextAttribute(color)
- self.stream.write(text)
- self.screenBuffer.SetConsoleTextAttribute(self._colors['normal'])
-
-
-class _NullColorizer(object):
- """
- See _AnsiColorizer docstring.
- """
- def __init__(self, stream):
- self.stream = stream
-
- def supported(cls, stream=sys.stdout):
- return True
- supported = classmethod(supported)
-
- def write(self, text, color):
- self.stream.write(text)
-
-
-
-class SubunitReporter(object):
- """
- Reports test output via Subunit.
-
- @ivar _subunit: The subunit protocol client that we are wrapping.
-
- @ivar _successful: An internal variable, used to track whether we have
- received only successful results.
-
- @since: 10.0
- """
- implements(itrial.IReporter)
-
-
- def __init__(self, stream=sys.stdout, tbformat='default',
- realtime=False, publisher=None):
- """
- Construct a L{SubunitReporter}.
-
- @param stream: A file-like object representing the stream to print
- output to. Defaults to stdout.
- @param tbformat: The format for tracebacks. Ignored, since subunit
- always uses Python's standard format.
- @param realtime: Whether or not to print exceptions in the middle
- of the test results. Ignored, since subunit always does this.
- @param publisher: The log publisher which will be preserved for
- reporting events. Ignored, as it's not relevant to subunit.
- """
- if TestProtocolClient is None:
- raise Exception("Subunit not available")
- self._subunit = TestProtocolClient(stream)
- self._successful = True
-
-
- def done(self):
- """
- Record that the entire test suite run is finished.
-
- We do nothing, since a summary clause is irrelevant to the subunit
- protocol.
- """
- pass
-
-
- def shouldStop(self):
- """
- Whether or not the test runner should stop running tests.
- """
- return self._subunit.shouldStop
- shouldStop = property(shouldStop)
-
-
- def stop(self):
- """
- Signal that the test runner should stop running tests.
- """
- return self._subunit.stop()
-
-
- def wasSuccessful(self):
- """
- Has the test run been successful so far?
-
- @return: C{True} if we have received no reports of errors or failures,
- C{False} otherwise.
- """
- # Subunit has a bug in its implementation of wasSuccessful, see
- # https://bugs.edge.launchpad.net/subunit/+bug/491090, so we can't
- # simply forward it on.
- return self._successful
-
-
- def startTest(self, test):
- """
- Record that C{test} has started.
- """
- return self._subunit.startTest(test)
-
-
- def stopTest(self, test):
- """
- Record that C{test} has completed.
- """
- return self._subunit.stopTest(test)
-
-
- def addSuccess(self, test):
- """
- Record that C{test} was successful.
- """
- return self._subunit.addSuccess(test)
-
-
- def addSkip(self, test, reason):
- """
- Record that C{test} was skipped for C{reason}.
-
- Some versions of subunit don't have support for addSkip. In those
- cases, the skip is reported as a success.
-
- @param test: A unittest-compatible C{TestCase}.
- @param reason: The reason for it being skipped. The C{str()} of this
- object will be included in the subunit output stream.
- """
- addSkip = getattr(self._subunit, 'addSkip', None)
- if addSkip is None:
- self.addSuccess(test)
- else:
- self._subunit.addSkip(test, reason)
-
-
- def addError(self, test, err):
- """
- Record that C{test} failed with an unexpected error C{err}.
-
- Also marks the run as being unsuccessful, causing
- L{SubunitReporter.wasSuccessful} to return C{False}.
- """
- self._successful = False
- return self._subunit.addError(
- test, util.excInfoOrFailureToExcInfo(err))
-
-
- def addFailure(self, test, err):
- """
- Record that C{test} failed an assertion with the error C{err}.
-
- Also marks the run as being unsuccessful, causing
- L{SubunitReporter.wasSuccessful} to return C{False}.
- """
- self._successful = False
- return self._subunit.addFailure(
- test, util.excInfoOrFailureToExcInfo(err))
-
-
- def addExpectedFailure(self, test, failure, todo):
- """
- Record an expected failure from a test.
-
- Some versions of subunit do not implement this. For those versions, we
- record a success.
- """
- failure = util.excInfoOrFailureToExcInfo(failure)
- addExpectedFailure = getattr(self._subunit, 'addExpectedFailure', None)
- if addExpectedFailure is None:
- self.addSuccess(test)
- else:
- addExpectedFailure(test, failure)
-
-
- def addUnexpectedSuccess(self, test, todo):
- """
- Record an unexpected success.
-
- Since subunit has no way of expressing this concept, we record a
- success on the subunit stream.
- """
- # Not represented in pyunit/subunit.
- self.addSuccess(test)
-
-
-
-class TreeReporter(Reporter):
- """
- Print out the tests in the form a tree.
-
- Tests are indented according to which class and module they belong.
- Results are printed in ANSI color.
- """
-
- currentLine = ''
- indent = ' '
- columns = 79
-
- FAILURE = 'red'
- ERROR = 'red'
- TODO = 'blue'
- SKIP = 'blue'
- TODONE = 'red'
- SUCCESS = 'green'
-
- def __init__(self, stream=sys.stdout, *args, **kwargs):
- super(TreeReporter, self).__init__(stream, *args, **kwargs)
- self._lastTest = []
- for colorizer in [_Win32Colorizer, _AnsiColorizer, _NullColorizer]:
- if colorizer.supported(stream):
- self._colorizer = colorizer(stream)
- break
-
- def getDescription(self, test):
- """
- Return the name of the method which 'test' represents. This is
- what gets displayed in the leaves of the tree.
-
- e.g. getDescription(TestCase('test_foo')) ==> test_foo
- """
- return test.id().split('.')[-1]
-
- def addSuccess(self, test):
- super(TreeReporter, self).addSuccess(test)
- self.endLine('[OK]', self.SUCCESS)
-
- def addError(self, *args):
- super(TreeReporter, self).addError(*args)
- self.endLine('[ERROR]', self.ERROR)
-
- def addFailure(self, *args):
- super(TreeReporter, self).addFailure(*args)
- self.endLine('[FAIL]', self.FAILURE)
-
- def addSkip(self, *args):
- super(TreeReporter, self).addSkip(*args)
- self.endLine('[SKIPPED]', self.SKIP)
-
- def addExpectedFailure(self, *args):
- super(TreeReporter, self).addExpectedFailure(*args)
- self.endLine('[TODO]', self.TODO)
-
- def addUnexpectedSuccess(self, *args):
- super(TreeReporter, self).addUnexpectedSuccess(*args)
- self.endLine('[SUCCESS!?!]', self.TODONE)
-
- def _write(self, format, *args):
- if args:
- format = format % args
- self.currentLine = format
- super(TreeReporter, self)._write(self.currentLine)
-
-
- def _getPreludeSegments(self, testID):
- """
- Return a list of all non-leaf segments to display in the tree.
-
- Normally this is the module and class name.
- """
- segments = testID.split('.')[:-1]
- if len(segments) == 0:
- return segments
- segments = [
- seg for seg in '.'.join(segments[:-1]), segments[-1]
- if len(seg) > 0]
- return segments
-
-
- def _testPrelude(self, testID):
- """
- Write the name of the test to the stream, indenting it appropriately.
-
- If the test is the first test in a new 'branch' of the tree, also
- write all of the parents in that branch.
- """
- segments = self._getPreludeSegments(testID)
- indentLevel = 0
- for seg in segments:
- if indentLevel < len(self._lastTest):
- if seg != self._lastTest[indentLevel]:
- self._write('%s%s\n' % (self.indent * indentLevel, seg))
- else:
- self._write('%s%s\n' % (self.indent * indentLevel, seg))
- indentLevel += 1
- self._lastTest = segments
-
-
- def cleanupErrors(self, errs):
- self._colorizer.write(' cleanup errors', self.ERROR)
- self.endLine('[ERROR]', self.ERROR)
- super(TreeReporter, self).cleanupErrors(errs)
-
- def upDownError(self, method, error, warn, printStatus):
- self._colorizer.write(" %s" % method, self.ERROR)
- if printStatus:
- self.endLine('[ERROR]', self.ERROR)
- super(TreeReporter, self).upDownError(method, error, warn, printStatus)
-
- def startTest(self, test):
- """
- Called when C{test} starts. Writes the tests name to the stream using
- a tree format.
- """
- self._testPrelude(test.id())
- self._write('%s%s ... ' % (self.indent * (len(self._lastTest)),
- self.getDescription(test)))
- super(TreeReporter, self).startTest(test)
-
-
- def endLine(self, message, color):
- """
- Print 'message' in the given color.
-
- @param message: A string message, usually '[OK]' or something similar.
- @param color: A string color, 'red', 'green' and so forth.
- """
- spaces = ' ' * (self.columns - len(self.currentLine) - len(message))
- super(TreeReporter, self)._write(spaces)
- self._colorizer.write(message, color)
- super(TreeReporter, self)._write("\n")
-
-
- def _printSummary(self):
- """
- Print a line summarising the test results to the stream, and color the
- status result.
- """
- summary = self._getSummary()
- if self.wasSuccessful():
- status = "PASSED"
- color = self.SUCCESS
- else:
- status = "FAILED"
- color = self.FAILURE
- self._colorizer.write(status, color)
- self._write("%s\n", summary)
diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/runner.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/runner.py
deleted file mode 100755
index 68663b5e..00000000
--- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/runner.py
+++ /dev/null
@@ -1,861 +0,0 @@
-# -*- test-case-name: twisted.trial.test.test_runner -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-A miscellany of code used to run Trial tests.
-
-Maintainer: Jonathan Lange
-"""
-
-__all__ = [
- 'suiteVisit', 'TestSuite',
-
- 'DestructiveTestSuite', 'DryRunVisitor',
- 'ErrorHolder', 'LoggedSuite', 'PyUnitTestCase',
- 'TestHolder', 'TestLoader', 'TrialRunner', 'TrialSuite',
-
- 'filenameToModule', 'isPackage', 'isPackageDirectory', 'isTestCase',
- 'name', 'samefile', 'NOT_IN_TEST',
- ]
-
-import pdb
-import os, types, warnings, sys, inspect, imp
-import doctest, time
-
-from twisted.python import reflect, log, failure, modules, filepath
-from twisted.python.compat import set
-
-from twisted.internet import defer
-from twisted.trial import util, unittest
-from twisted.trial.itrial import ITestCase
-from twisted.trial.reporter import UncleanWarningsReporterWrapper
-
-# These are imported so that they remain in the public API for t.trial.runner
-from twisted.trial.unittest import suiteVisit, TestSuite
-
-from zope.interface import implements
-
-pyunit = __import__('unittest')
-
-
-
-def isPackage(module):
- """Given an object return True if the object looks like a package"""
- if not isinstance(module, types.ModuleType):
- return False
- basename = os.path.splitext(os.path.basename(module.__file__))[0]
- return basename == '__init__'
-
-
-def isPackageDirectory(dirname):
- """Is the directory at path 'dirname' a Python package directory?
- Returns the name of the __init__ file (it may have a weird extension)
- if dirname is a package directory. Otherwise, returns False"""
- for ext in zip(*imp.get_suffixes())[0]:
- initFile = '__init__' + ext
- if os.path.exists(os.path.join(dirname, initFile)):
- return initFile
- return False
-
-
-def samefile(filename1, filename2):
- """
- A hacky implementation of C{os.path.samefile}. Used by L{filenameToModule}
- when the platform doesn't provide C{os.path.samefile}. Do not use this.
- """
- return os.path.abspath(filename1) == os.path.abspath(filename2)
-
-
-def filenameToModule(fn):
- """
- Given a filename, do whatever possible to return a module object matching
- that file.
-
- If the file in question is a module in Python path, properly import and
- return that module. Otherwise, load the source manually.
-
- @param fn: A filename.
- @return: A module object.
- @raise ValueError: If C{fn} does not exist.
- """
- if not os.path.exists(fn):
- raise ValueError("%r doesn't exist" % (fn,))
- try:
- ret = reflect.namedAny(reflect.filenameToModuleName(fn))
- except (ValueError, AttributeError):
- # Couldn't find module. The file 'fn' is not in PYTHONPATH
- return _importFromFile(fn)
- # ensure that the loaded module matches the file
- retFile = os.path.splitext(ret.__file__)[0] + '.py'
- # not all platforms (e.g. win32) have os.path.samefile
- same = getattr(os.path, 'samefile', samefile)
- if os.path.isfile(fn) and not same(fn, retFile):
- del sys.modules[ret.__name__]
- ret = _importFromFile(fn)
- return ret
-
-
-def _importFromFile(fn, moduleName=None):
- fn = _resolveDirectory(fn)
- if not moduleName:
- moduleName = os.path.splitext(os.path.split(fn)[-1])[0]
- if moduleName in sys.modules:
- return sys.modules[moduleName]
- fd = open(fn, 'r')
- try:
- module = imp.load_source(moduleName, fn, fd)
- finally:
- fd.close()
- return module
-
-
-def _resolveDirectory(fn):
- if os.path.isdir(fn):
- initFile = isPackageDirectory(fn)
- if initFile:
- fn = os.path.join(fn, initFile)
- else:
- raise ValueError('%r is not a package directory' % (fn,))
- return fn
-
-
-def _getMethodNameInClass(method):
- """
- Find the attribute name on the method's class which refers to the method.
-
- For some methods, notably decorators which have not had __name__ set correctly:
-
- getattr(method.im_class, method.__name__) != method
- """
- if getattr(method.im_class, method.__name__, object()) != method:
- for alias in dir(method.im_class):
- if getattr(method.im_class, alias, object()) == method:
- return alias
- return method.__name__
-
-
-class DestructiveTestSuite(TestSuite):
- """
- A test suite which remove the tests once run, to minimize memory usage.
- """
-
- def run(self, result):
- """
- Almost the same as L{TestSuite.run}, but with C{self._tests} being
- empty at the end.
- """
- while self._tests:
- if result.shouldStop:
- break
- test = self._tests.pop(0)
- test(result)
- return result
-
-
-
-# When an error occurs outside of any test, the user will see this string
-# in place of a test's name.
-NOT_IN_TEST = "<not in test>"
-
-
-
-class LoggedSuite(TestSuite):
- """
- Any errors logged in this suite will be reported to the L{TestResult}
- object.
- """
-
- def run(self, result):
- """
- Run the suite, storing all errors in C{result}. If an error is logged
- while no tests are running, then it will be added as an error to
- C{result}.
-
- @param result: A L{TestResult} object.
- """
- observer = unittest._logObserver
- observer._add()
- super(LoggedSuite, self).run(result)
- observer._remove()
- for error in observer.getErrors():
- result.addError(TestHolder(NOT_IN_TEST), error)
- observer.flushErrors()
-
-
-
-class PyUnitTestCase(object):
- """
- DEPRECATED in Twisted 8.0.
-
- This class decorates the pyunit.TestCase class, mainly to work around the
- differences between unittest in Python 2.3, 2.4, and 2.5. These
- differences are::
-
- - The way doctest unittests describe themselves
- - Where the implementation of TestCase.run is (used to be in __call__)
- - Where the test method name is kept (mangled-private or non-mangled
- private variable)
-
- It also implements visit, which we like.
- """
-
- def __init__(self, test):
- warnings.warn("Deprecated in Twisted 8.0.",
- category=DeprecationWarning)
- self._test = test
- test.id = self.id
-
- def id(self):
- cls = self._test.__class__
- tmn = getattr(self._test, '_TestCase__testMethodName', None)
- if tmn is None:
- # python2.5's 'unittest' module is more sensible; but different.
- tmn = self._test._testMethodName
- return (cls.__module__ + '.' + cls.__name__ + '.' +
- tmn)
-
- def __repr__(self):
- return 'PyUnitTestCase<%r>'%(self.id(),)
-
- def __call__(self, results):
- return self._test(results)
-
-
- def visit(self, visitor):
- """
- Call the given visitor with the original, standard library, test case
- that C{self} wraps. See L{unittest.TestCase.visit}.
-
- Deprecated in Twisted 8.0.
- """
- warnings.warn("Test visitors deprecated in Twisted 8.0",
- category=DeprecationWarning)
- visitor(self._test)
-
-
- def __getattr__(self, name):
- return getattr(self._test, name)
-
-
-
-class TrialSuite(TestSuite):
- """
- Suite to wrap around every single test in a C{trial} run. Used internally
- by Trial to set up things necessary for Trial tests to work, regardless of
- what context they are run in.
- """
-
- def __init__(self, tests=()):
- suite = LoggedSuite(tests)
- super(TrialSuite, self).__init__([suite])
-
-
- def _bail(self):
- from twisted.internet import reactor
- d = defer.Deferred()
- reactor.addSystemEventTrigger('after', 'shutdown',
- lambda: d.callback(None))
- reactor.fireSystemEvent('shutdown') # radix's suggestion
- # As long as TestCase does crap stuff with the reactor we need to
- # manually shutdown the reactor here, and that requires util.wait
- # :(
- # so that the shutdown event completes
- unittest.TestCase('mktemp')._wait(d)
-
- def run(self, result):
- try:
- TestSuite.run(self, result)
- finally:
- self._bail()
-
-
-def name(thing):
- """
- @param thing: an object from modules (instance of PythonModule,
- PythonAttribute), a TestCase subclass, or an instance of a TestCase.
- """
- if isTestCase(thing):
- # TestCase subclass
- theName = reflect.qual(thing)
- else:
- # thing from trial, or thing from modules.
- # this monstrosity exists so that modules' objects do not have to
- # implement id(). -jml
- try:
- theName = thing.id()
- except AttributeError:
- theName = thing.name
- return theName
-
-
-def isTestCase(obj):
- """
- @return: C{True} if C{obj} is a class that contains test cases, C{False}
- otherwise. Used to find all the tests in a module.
- """
- try:
- return issubclass(obj, pyunit.TestCase)
- except TypeError:
- return False
-
-
-
-class TestHolder(object):
- """
- Placeholder for a L{TestCase} inside a reporter. As far as a L{TestResult}
- is concerned, this looks exactly like a unit test.
- """
-
- implements(ITestCase)
-
- failureException = None
-
- def __init__(self, description):
- """
- @param description: A string to be displayed L{TestResult}.
- """
- self.description = description
-
-
- def __call__(self, result):
- return self.run(result)
-
-
- def id(self):
- return self.description
-
-
- def countTestCases(self):
- return 0
-
-
- def run(self, result):
- """
- This test is just a placeholder. Run the test successfully.
-
- @param result: The C{TestResult} to store the results in.
- @type result: L{twisted.trial.itrial.ITestResult}.
- """
- result.startTest(self)
- result.addSuccess(self)
- result.stopTest(self)
-
-
- def shortDescription(self):
- return self.description
-
-
-
-class ErrorHolder(TestHolder):
- """
- Used to insert arbitrary errors into a test suite run. Provides enough
- methods to look like a C{TestCase}, however, when it is run, it simply adds
- an error to the C{TestResult}. The most common use-case is for when a
- module fails to import.
- """
-
- def __init__(self, description, error):
- """
- @param description: A string used by C{TestResult}s to identify this
- error. Generally, this is the name of a module that failed to import.
-
- @param error: The error to be added to the result. Can be an `exc_info`
- tuple or a L{twisted.python.failure.Failure}.
- """
- super(ErrorHolder, self).__init__(description)
- self.error = util.excInfoOrFailureToExcInfo(error)
-
-
- def __repr__(self):
- return "<ErrorHolder description=%r error=%s%s>" % (
- # Format the exception type and arguments explicitly, as exception
- # objects do not have nice looking string formats on Python 2.4.
- self.description, self.error[0].__name__, self.error[1].args)
-
-
- def run(self, result):
- """
- Run the test, reporting the error.
-
- @param result: The C{TestResult} to store the results in.
- @type result: L{twisted.trial.itrial.ITestResult}.
- """
- result.startTest(self)
- result.addError(self, self.error)
- result.stopTest(self)
-
-
- def visit(self, visitor):
- """
- See L{unittest.TestCase.visit}.
- """
- visitor(self)
-
-
-
-class TestLoader(object):
- """
- I find tests inside function, modules, files -- whatever -- then return
- them wrapped inside a Test (either a L{TestSuite} or a L{TestCase}).
-
- @ivar methodPrefix: A string prefix. C{TestLoader} will assume that all the
- methods in a class that begin with C{methodPrefix} are test cases.
-
- @ivar modulePrefix: A string prefix. Every module in a package that begins
- with C{modulePrefix} is considered a module full of tests.
-
- @ivar forceGarbageCollection: A flag applied to each C{TestCase} loaded.
- See L{unittest.TestCase} for more information.
-
- @ivar sorter: A key function used to sort C{TestCase}s, test classes,
- modules and packages.
-
- @ivar suiteFactory: A callable which is passed a list of tests (which
- themselves may be suites of tests). Must return a test suite.
- """
-
- methodPrefix = 'test'
- modulePrefix = 'test_'
-
- def __init__(self):
- self.suiteFactory = TestSuite
- self.sorter = name
- self._importErrors = []
-
- def sort(self, xs):
- """
- Sort the given things using L{sorter}.
-
- @param xs: A list of test cases, class or modules.
- """
- return sorted(xs, key=self.sorter)
-
- def findTestClasses(self, module):
- """Given a module, return all Trial test classes"""
- classes = []
- for name, val in inspect.getmembers(module):
- if isTestCase(val):
- classes.append(val)
- return self.sort(classes)
-
- def findByName(self, name):
- """
- Return a Python object given a string describing it.
-
- @param name: a string which may be either a filename or a
- fully-qualified Python name.
-
- @return: If C{name} is a filename, return the module. If C{name} is a
- fully-qualified Python name, return the object it refers to.
- """
- if os.path.exists(name):
- return filenameToModule(name)
- return reflect.namedAny(name)
-
- def loadModule(self, module):
- """
- Return a test suite with all the tests from a module.
-
- Included are TestCase subclasses and doctests listed in the module's
- __doctests__ module. If that's not good for you, put a function named
- either C{testSuite} or C{test_suite} in your module that returns a
- TestSuite, and I'll use the results of that instead.
-
- If C{testSuite} and C{test_suite} are both present, then I'll use
- C{testSuite}.
- """
- ## XXX - should I add an optional parameter to disable the check for
- ## a custom suite.
- ## OR, should I add another method
- if not isinstance(module, types.ModuleType):
- raise TypeError("%r is not a module" % (module,))
- if hasattr(module, 'testSuite'):
- return module.testSuite()
- elif hasattr(module, 'test_suite'):
- return module.test_suite()
- suite = self.suiteFactory()
- for testClass in self.findTestClasses(module):
- suite.addTest(self.loadClass(testClass))
- if not hasattr(module, '__doctests__'):
- return suite
- docSuite = self.suiteFactory()
- for doctest in module.__doctests__:
- docSuite.addTest(self.loadDoctests(doctest))
- return self.suiteFactory([suite, docSuite])
- loadTestsFromModule = loadModule
-
- def loadClass(self, klass):
- """
- Given a class which contains test cases, return a sorted list of
- C{TestCase} instances.
- """
- if not (isinstance(klass, type) or isinstance(klass, types.ClassType)):
- raise TypeError("%r is not a class" % (klass,))
- if not isTestCase(klass):
- raise ValueError("%r is not a test case" % (klass,))
- names = self.getTestCaseNames(klass)
- tests = self.sort([self._makeCase(klass, self.methodPrefix+name)
- for name in names])
- return self.suiteFactory(tests)
- loadTestsFromTestCase = loadClass
-
- def getTestCaseNames(self, klass):
- """
- Given a class that contains C{TestCase}s, return a list of names of
- methods that probably contain tests.
- """
- return reflect.prefixedMethodNames(klass, self.methodPrefix)
-
- def loadMethod(self, method):
- """
- Given a method of a C{TestCase} that represents a test, return a
- C{TestCase} instance for that test.
- """
- if not isinstance(method, types.MethodType):
- raise TypeError("%r not a method" % (method,))
- return self._makeCase(method.im_class, _getMethodNameInClass(method))
-
- def _makeCase(self, klass, methodName):
- return klass(methodName)
-
- def loadPackage(self, package, recurse=False):
- """
- Load tests from a module object representing a package, and return a
- TestSuite containing those tests.
-
- Tests are only loaded from modules whose name begins with 'test_'
- (or whatever C{modulePrefix} is set to).
-
- @param package: a types.ModuleType object (or reasonable facsimilie
- obtained by importing) which may contain tests.
-
- @param recurse: A boolean. If True, inspect modules within packages
- within the given package (and so on), otherwise, only inspect modules
- in the package itself.
-
- @raise: TypeError if 'package' is not a package.
-
- @return: a TestSuite created with my suiteFactory, containing all the
- tests.
- """
- if not isPackage(package):
- raise TypeError("%r is not a package" % (package,))
- pkgobj = modules.getModule(package.__name__)
- if recurse:
- discovery = pkgobj.walkModules()
- else:
- discovery = pkgobj.iterModules()
- discovered = []
- for disco in discovery:
- if disco.name.split(".")[-1].startswith(self.modulePrefix):
- discovered.append(disco)
- suite = self.suiteFactory()
- for modinfo in self.sort(discovered):
- try:
- module = modinfo.load()
- except:
- thingToAdd = ErrorHolder(modinfo.name, failure.Failure())
- else:
- thingToAdd = self.loadModule(module)
- suite.addTest(thingToAdd)
- return suite
-
- def loadDoctests(self, module):
- """
- Return a suite of tests for all the doctests defined in C{module}.
-
- @param module: A module object or a module name.
- """
- if isinstance(module, str):
- try:
- module = reflect.namedAny(module)
- except:
- return ErrorHolder(module, failure.Failure())
- if not inspect.ismodule(module):
- warnings.warn("trial only supports doctesting modules")
- return
- extraArgs = {}
- if sys.version_info > (2, 4):
- # Work around Python issue2604: DocTestCase.tearDown clobbers globs
- def saveGlobals(test):
- """
- Save C{test.globs} and replace it with a copy so that if
- necessary, the original will be available for the next test
- run.
- """
- test._savedGlobals = getattr(test, '_savedGlobals', test.globs)
- test.globs = test._savedGlobals.copy()
- extraArgs['setUp'] = saveGlobals
- return doctest.DocTestSuite(module, **extraArgs)
-
- def loadAnything(self, thing, recurse=False):
- """
- Given a Python object, return whatever tests that are in it. Whatever
- 'in' might mean.
-
- @param thing: A Python object. A module, method, class or package.
- @param recurse: Whether or not to look in subpackages of packages.
- Defaults to False.
-
- @return: A C{TestCase} or C{TestSuite}.
- """
- if isinstance(thing, types.ModuleType):
- if isPackage(thing):
- return self.loadPackage(thing, recurse)
- return self.loadModule(thing)
- elif isinstance(thing, types.ClassType):
- return self.loadClass(thing)
- elif isinstance(thing, type):
- return self.loadClass(thing)
- elif isinstance(thing, types.MethodType):
- return self.loadMethod(thing)
- raise TypeError("No loader for %r. Unrecognized type" % (thing,))
-
- def loadByName(self, name, recurse=False):
- """
- Given a string representing a Python object, return whatever tests
- are in that object.
-
- If C{name} is somehow inaccessible (e.g. the module can't be imported,
- there is no Python object with that name etc) then return an
- L{ErrorHolder}.
-
- @param name: The fully-qualified name of a Python object.
- """
- try:
- thing = self.findByName(name)
- except:
- return ErrorHolder(name, failure.Failure())
- return self.loadAnything(thing, recurse)
- loadTestsFromName = loadByName
-
- def loadByNames(self, names, recurse=False):
- """
- Construct a TestSuite containing all the tests found in 'names', where
- names is a list of fully qualified python names and/or filenames. The
- suite returned will have no duplicate tests, even if the same object
- is named twice.
- """
- things = []
- errors = []
- for name in names:
- try:
- things.append(self.findByName(name))
- except:
- errors.append(ErrorHolder(name, failure.Failure()))
- suites = [self.loadAnything(thing, recurse)
- for thing in self._uniqueTests(things)]
- suites.extend(errors)
- return self.suiteFactory(suites)
-
-
- def _uniqueTests(self, things):
- """
- Gather unique suite objects from loaded things. This will guarantee
- uniqueness of inherited methods on TestCases which would otherwise hash
- to same value and collapse to one test unexpectedly if using simpler
- means: e.g. set().
- """
- entries = []
- for thing in things:
- if isinstance(thing, types.MethodType):
- entries.append((thing, thing.im_class))
- else:
- entries.append((thing,))
- return [entry[0] for entry in set(entries)]
-
-
-
-class DryRunVisitor(object):
- """
- A visitor that makes a reporter think that every test visited has run
- successfully.
- """
-
- def __init__(self, reporter):
- """
- @param reporter: A C{TestResult} object.
- """
- self.reporter = reporter
-
-
- def markSuccessful(self, testCase):
- """
- Convince the reporter that this test has been run successfully.
- """
- self.reporter.startTest(testCase)
- self.reporter.addSuccess(testCase)
- self.reporter.stopTest(testCase)
-
-
-
-class TrialRunner(object):
- """
- A specialised runner that the trial front end uses.
- """
-
- DEBUG = 'debug'
- DRY_RUN = 'dry-run'
-
- def _getDebugger(self):
- dbg = pdb.Pdb()
- try:
- import readline
- except ImportError:
- print "readline module not available"
- sys.exc_clear()
- for path in ('.pdbrc', 'pdbrc'):
- if os.path.exists(path):
- try:
- rcFile = file(path, 'r')
- except IOError:
- sys.exc_clear()
- else:
- dbg.rcLines.extend(rcFile.readlines())
- return dbg
-
-
- def _setUpTestdir(self):
- self._tearDownLogFile()
- currentDir = os.getcwd()
- base = filepath.FilePath(self.workingDirectory)
- testdir, self._testDirLock = util._unusedTestDirectory(base)
- os.chdir(testdir.path)
- return currentDir
-
-
- def _tearDownTestdir(self, oldDir):
- os.chdir(oldDir)
- self._testDirLock.unlock()
-
-
- _log = log
- def _makeResult(self):
- reporter = self.reporterFactory(self.stream, self.tbformat,
- self.rterrors, self._log)
- if self.uncleanWarnings:
- reporter = UncleanWarningsReporterWrapper(reporter)
- return reporter
-
- def __init__(self, reporterFactory,
- mode=None,
- logfile='test.log',
- stream=sys.stdout,
- profile=False,
- tracebackFormat='default',
- realTimeErrors=False,
- uncleanWarnings=False,
- workingDirectory=None,
- forceGarbageCollection=False):
- self.reporterFactory = reporterFactory
- self.logfile = logfile
- self.mode = mode
- self.stream = stream
- self.tbformat = tracebackFormat
- self.rterrors = realTimeErrors
- self.uncleanWarnings = uncleanWarnings
- self._result = None
- self.workingDirectory = workingDirectory or '_trial_temp'
- self._logFileObserver = None
- self._logFileObject = None
- self._forceGarbageCollection = forceGarbageCollection
- if profile:
- self.run = util.profiled(self.run, 'profile.data')
-
- def _tearDownLogFile(self):
- if self._logFileObserver is not None:
- log.removeObserver(self._logFileObserver.emit)
- self._logFileObserver = None
- if self._logFileObject is not None:
- self._logFileObject.close()
- self._logFileObject = None
-
- def _setUpLogFile(self):
- self._tearDownLogFile()
- if self.logfile == '-':
- logFile = sys.stdout
- else:
- logFile = file(self.logfile, 'a')
- self._logFileObject = logFile
- self._logFileObserver = log.FileLogObserver(logFile)
- log.startLoggingWithObserver(self._logFileObserver.emit, 0)
-
-
- def run(self, test):
- """
- Run the test or suite and return a result object.
- """
- test = unittest.decorate(test, ITestCase)
- if self._forceGarbageCollection:
- test = unittest.decorate(
- test, unittest._ForceGarbageCollectionDecorator)
- return self._runWithoutDecoration(test)
-
-
- def _runWithoutDecoration(self, test):
- """
- Private helper that runs the given test but doesn't decorate it.
- """
- result = self._makeResult()
- # decorate the suite with reactor cleanup and log starting
- # This should move out of the runner and be presumed to be
- # present
- suite = TrialSuite([test])
- startTime = time.time()
- if self.mode == self.DRY_RUN:
- for single in unittest._iterateTests(suite):
- result.startTest(single)
- result.addSuccess(single)
- result.stopTest(single)
- else:
- if self.mode == self.DEBUG:
- # open question - should this be self.debug() instead.
- debugger = self._getDebugger()
- run = lambda: debugger.runcall(suite.run, result)
- else:
- run = lambda: suite.run(result)
-
- oldDir = self._setUpTestdir()
- try:
- self._setUpLogFile()
- run()
- finally:
- self._tearDownLogFile()
- self._tearDownTestdir(oldDir)
-
- endTime = time.time()
- done = getattr(result, 'done', None)
- if done is None:
- warnings.warn(
- "%s should implement done() but doesn't. Falling back to "
- "printErrors() and friends." % reflect.qual(result.__class__),
- category=DeprecationWarning, stacklevel=3)
- result.printErrors()
- result.writeln(result.separator)
- result.writeln('Ran %d tests in %.3fs', result.testsRun,
- endTime - startTime)
- result.write('\n')
- result.printSummary()
- else:
- result.done()
- return result
-
-
- def runUntilFailure(self, test):
- """
- Repeatedly run C{test} until it fails.
- """
- count = 0
- while True:
- count += 1
- self.stream.write("Test Pass %d\n" % (count,))
- if count == 1:
- result = self.run(test)
- else:
- result = self._runWithoutDecoration(test)
- if result.testsRun == 0:
- break
- if not result.wasSuccessful():
- break
- return result
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)
diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/unittest.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/unittest.py
deleted file mode 100755
index 6e8427c6..00000000
--- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/unittest.py
+++ /dev/null
@@ -1,1778 +0,0 @@
-# -*- test-case-name: twisted.trial.test -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-
-"""
-Things likely to be used by writers of unit tests.
-
-Maintainer: Jonathan Lange
-"""
-
-
-import doctest, inspect
-import os, warnings, sys, tempfile, gc, types
-from pprint import pformat
-from dis import findlinestarts as _findlinestarts
-
-from twisted.internet import defer, utils
-from twisted.python import components, failure, log, monkey
-from twisted.python.deprecate import (
- getDeprecationWarningString, warnAboutFunction)
-
-from twisted.trial import itrial, reporter, util
-
-pyunit = __import__('unittest')
-
-from zope.interface import implements
-
-
-
-class SkipTest(Exception):
- """
- Raise this (with a reason) to skip the current test. You may also set
- method.skip to a reason string to skip it, or set class.skip to skip the
- entire TestCase.
- """
-
-
-class FailTest(AssertionError):
- """Raised to indicate the current test has failed to pass."""
-
-
-class Todo(object):
- """
- Internal object used to mark a L{TestCase} as 'todo'. Tests marked 'todo'
- are reported differently in Trial L{TestResult}s. If todo'd tests fail,
- they do not fail the suite and the errors are reported in a separate
- category. If todo'd tests succeed, Trial L{TestResult}s will report an
- unexpected success.
- """
-
- def __init__(self, reason, errors=None):
- """
- @param reason: A string explaining why the test is marked 'todo'
-
- @param errors: An iterable of exception types that the test is
- expected to raise. If one of these errors is raised by the test, it
- will be trapped. Raising any other kind of error will fail the test.
- If C{None} is passed, then all errors will be trapped.
- """
- self.reason = reason
- self.errors = errors
-
- def __repr__(self):
- return "<Todo reason=%r errors=%r>" % (self.reason, self.errors)
-
- def expected(self, failure):
- """
- @param failure: A L{twisted.python.failure.Failure}.
-
- @return: C{True} if C{failure} is expected, C{False} otherwise.
- """
- if self.errors is None:
- return True
- for error in self.errors:
- if failure.check(error):
- return True
- return False
-
-
-def makeTodo(value):
- """
- Return a L{Todo} object built from C{value}.
-
- If C{value} is a string, return a Todo that expects any exception with
- C{value} as a reason. If C{value} is a tuple, the second element is used
- as the reason and the first element as the excepted error(s).
-
- @param value: A string or a tuple of C{(errors, reason)}, where C{errors}
- is either a single exception class or an iterable of exception classes.
-
- @return: A L{Todo} object.
- """
- if isinstance(value, str):
- return Todo(reason=value)
- if isinstance(value, tuple):
- errors, reason = value
- try:
- errors = list(errors)
- except TypeError:
- errors = [errors]
- return Todo(reason=reason, errors=errors)
-
-
-
-class _Warning(object):
- """
- A L{_Warning} instance represents one warning emitted through the Python
- warning system (L{warnings}). This is used to insulate callers of
- L{_collectWarnings} from changes to the Python warnings system which might
- otherwise require changes to the warning objects that function passes to
- the observer object it accepts.
-
- @ivar message: The string which was passed as the message parameter to
- L{warnings.warn}.
-
- @ivar category: The L{Warning} subclass which was passed as the category
- parameter to L{warnings.warn}.
-
- @ivar filename: The name of the file containing the definition of the code
- object which was C{stacklevel} frames above the call to
- L{warnings.warn}, where C{stacklevel} is the value of the C{stacklevel}
- parameter passed to L{warnings.warn}.
-
- @ivar lineno: The source line associated with the active instruction of the
- code object object which was C{stacklevel} frames above the call to
- L{warnings.warn}, where C{stacklevel} is the value of the C{stacklevel}
- parameter passed to L{warnings.warn}.
- """
- def __init__(self, message, category, filename, lineno):
- self.message = message
- self.category = category
- self.filename = filename
- self.lineno = lineno
-
-
-def _setWarningRegistryToNone(modules):
- """
- Disable the per-module cache for every module found in C{modules}, typically
- C{sys.modules}.
-
- @param modules: Dictionary of modules, typically sys.module dict
- """
- for v in modules.values():
- if v is not None:
- try:
- v.__warningregistry__ = None
- except:
- # Don't specify a particular exception type to handle in case
- # some wacky object raises some wacky exception in response to
- # the setattr attempt.
- pass
-
-
-def _collectWarnings(observeWarning, f, *args, **kwargs):
- """
- Call C{f} with C{args} positional arguments and C{kwargs} keyword arguments
- and collect all warnings which are emitted as a result in a list.
-
- @param observeWarning: A callable which will be invoked with a L{_Warning}
- instance each time a warning is emitted.
-
- @return: The return value of C{f(*args, **kwargs)}.
- """
- def showWarning(message, category, filename, lineno, file=None, line=None):
- assert isinstance(message, Warning)
- observeWarning(_Warning(
- message.args[0], category, filename, lineno))
-
- # Disable the per-module cache for every module otherwise if the warning
- # which the caller is expecting us to collect was already emitted it won't
- # be re-emitted by the call to f which happens below.
- _setWarningRegistryToNone(sys.modules)
-
- origFilters = warnings.filters[:]
- origShow = warnings.showwarning
- warnings.simplefilter('always')
- try:
- warnings.showwarning = showWarning
- result = f(*args, **kwargs)
- finally:
- warnings.filters[:] = origFilters
- warnings.showwarning = origShow
- return result
-
-
-
-class _Assertions(pyunit.TestCase, object):
- """
- Replaces many of the built-in TestCase assertions. In general, these
- assertions provide better error messages and are easier to use in
- callbacks. Also provides new assertions such as L{failUnlessFailure}.
-
- Although the tests are defined as 'failIf*' and 'failUnless*', they can
- also be called as 'assertNot*' and 'assert*'.
- """
-
- def fail(self, msg=None):
- """
- Absolutely fail the test. Do not pass go, do not collect $200.
-
- @param msg: the message that will be displayed as the reason for the
- failure
- """
- raise self.failureException(msg)
-
- def failIf(self, condition, msg=None):
- """
- Fail the test if C{condition} evaluates to True.
-
- @param condition: any object that defines __nonzero__
- """
- if condition:
- raise self.failureException(msg)
- return condition
- assertNot = assertFalse = failUnlessFalse = failIf
-
- def failUnless(self, condition, msg=None):
- """
- Fail the test if C{condition} evaluates to False.
-
- @param condition: any object that defines __nonzero__
- """
- if not condition:
- raise self.failureException(msg)
- return condition
- assert_ = assertTrue = failUnlessTrue = failUnless
-
- def failUnlessRaises(self, exception, f, *args, **kwargs):
- """
- Fail the test unless calling the function C{f} with the given
- C{args} and C{kwargs} raises C{exception}. The failure will report
- the traceback and call stack of the unexpected exception.
-
- @param exception: exception type that is to be expected
- @param f: the function to call
-
- @return: The raised exception instance, if it is of the given type.
- @raise self.failureException: Raised if the function call does
- not raise an exception or if it raises an exception of a
- different type.
- """
- try:
- result = f(*args, **kwargs)
- except exception, inst:
- return inst
- except:
- raise self.failureException('%s raised instead of %s:\n %s'
- % (sys.exc_info()[0],
- exception.__name__,
- failure.Failure().getTraceback()))
- else:
- raise self.failureException('%s not raised (%r returned)'
- % (exception.__name__, result))
- assertRaises = failUnlessRaises
-
-
- def assertEqual(self, first, second, msg=''):
- """
- Fail the test if C{first} and C{second} are not equal.
-
- @param msg: A string describing the failure that's included in the
- exception.
- """
- if not first == second:
- if msg is None:
- msg = ''
- if len(msg) > 0:
- msg += '\n'
- raise self.failureException(
- '%snot equal:\na = %s\nb = %s\n'
- % (msg, pformat(first), pformat(second)))
- return first
- failUnlessEqual = failUnlessEquals = assertEquals = assertEqual
-
-
- def failUnlessIdentical(self, first, second, msg=None):
- """
- Fail the test if C{first} is not C{second}. This is an
- obect-identity-equality test, not an object equality
- (i.e. C{__eq__}) test.
-
- @param msg: if msg is None, then the failure message will be
- '%r is not %r' % (first, second)
- """
- if first is not second:
- raise self.failureException(msg or '%r is not %r' % (first, second))
- return first
- assertIdentical = failUnlessIdentical
-
- def failIfIdentical(self, first, second, msg=None):
- """
- Fail the test if C{first} is C{second}. This is an
- obect-identity-equality test, not an object equality
- (i.e. C{__eq__}) test.
-
- @param msg: if msg is None, then the failure message will be
- '%r is %r' % (first, second)
- """
- if first is second:
- raise self.failureException(msg or '%r is %r' % (first, second))
- return first
- assertNotIdentical = failIfIdentical
-
- def failIfEqual(self, first, second, msg=None):
- """
- Fail the test if C{first} == C{second}.
-
- @param msg: if msg is None, then the failure message will be
- '%r == %r' % (first, second)
- """
- if not first != second:
- raise self.failureException(msg or '%r == %r' % (first, second))
- return first
- assertNotEqual = assertNotEquals = failIfEquals = failIfEqual
-
- def failUnlessIn(self, containee, container, msg=None):
- """
- Fail the test if C{containee} is not found in C{container}.
-
- @param containee: the value that should be in C{container}
- @param container: a sequence type, or in the case of a mapping type,
- will follow semantics of 'if key in dict.keys()'
- @param msg: if msg is None, then the failure message will be
- '%r not in %r' % (first, second)
- """
- if containee not in container:
- raise self.failureException(msg or "%r not in %r"
- % (containee, container))
- return containee
- assertIn = failUnlessIn
-
- def failIfIn(self, containee, container, msg=None):
- """
- Fail the test if C{containee} is found in C{container}.
-
- @param containee: the value that should not be in C{container}
- @param container: a sequence type, or in the case of a mapping type,
- will follow semantics of 'if key in dict.keys()'
- @param msg: if msg is None, then the failure message will be
- '%r in %r' % (first, second)
- """
- if containee in container:
- raise self.failureException(msg or "%r in %r"
- % (containee, container))
- return containee
- assertNotIn = failIfIn
-
- def failIfAlmostEqual(self, first, second, places=7, msg=None):
- """
- Fail if the two objects are equal as determined by their
- difference rounded to the given number of decimal places
- (default 7) and comparing to zero.
-
- @note: decimal places (from zero) is usually not the same
- as significant digits (measured from the most
- signficant digit).
-
- @note: included for compatiblity with PyUnit test cases
- """
- if round(second-first, places) == 0:
- raise self.failureException(msg or '%r == %r within %r places'
- % (first, second, places))
- return first
- assertNotAlmostEqual = assertNotAlmostEquals = failIfAlmostEqual
- failIfAlmostEquals = failIfAlmostEqual
-
- def failUnlessAlmostEqual(self, first, second, places=7, msg=None):
- """
- Fail if the two objects are unequal as determined by their
- difference rounded to the given number of decimal places
- (default 7) and comparing to zero.
-
- @note: decimal places (from zero) is usually not the same
- as significant digits (measured from the most
- signficant digit).
-
- @note: included for compatiblity with PyUnit test cases
- """
- if round(second-first, places) != 0:
- raise self.failureException(msg or '%r != %r within %r places'
- % (first, second, places))
- return first
- assertAlmostEqual = assertAlmostEquals = failUnlessAlmostEqual
- failUnlessAlmostEquals = failUnlessAlmostEqual
-
- def failUnlessApproximates(self, first, second, tolerance, msg=None):
- """
- Fail if C{first} - C{second} > C{tolerance}
-
- @param msg: if msg is None, then the failure message will be
- '%r ~== %r' % (first, second)
- """
- if abs(first - second) > tolerance:
- raise self.failureException(msg or "%s ~== %s" % (first, second))
- return first
- assertApproximates = failUnlessApproximates
-
- def failUnlessFailure(self, deferred, *expectedFailures):
- """
- Fail if C{deferred} does not errback with one of C{expectedFailures}.
- Returns the original Deferred with callbacks added. You will need
- to return this Deferred from your test case.
- """
- def _cb(ignore):
- raise self.failureException(
- "did not catch an error, instead got %r" % (ignore,))
-
- def _eb(failure):
- if failure.check(*expectedFailures):
- return failure.value
- else:
- output = ('\nExpected: %r\nGot:\n%s'
- % (expectedFailures, str(failure)))
- raise self.failureException(output)
- return deferred.addCallbacks(_cb, _eb)
- assertFailure = failUnlessFailure
-
- def failUnlessSubstring(self, substring, astring, msg=None):
- """
- Fail if C{substring} does not exist within C{astring}.
- """
- return self.failUnlessIn(substring, astring, msg)
- assertSubstring = failUnlessSubstring
-
- def failIfSubstring(self, substring, astring, msg=None):
- """
- Fail if C{astring} contains C{substring}.
- """
- return self.failIfIn(substring, astring, msg)
- assertNotSubstring = failIfSubstring
-
- def failUnlessWarns(self, category, message, filename, f,
- *args, **kwargs):
- """
- Fail if the given function doesn't generate the specified warning when
- called. It calls the function, checks the warning, and forwards the
- result of the function if everything is fine.
-
- @param category: the category of the warning to check.
- @param message: the output message of the warning to check.
- @param filename: the filename where the warning should come from.
- @param f: the function which is supposed to generate the warning.
- @type f: any callable.
- @param args: the arguments to C{f}.
- @param kwargs: the keywords arguments to C{f}.
-
- @return: the result of the original function C{f}.
- """
- warningsShown = []
- result = _collectWarnings(warningsShown.append, f, *args, **kwargs)
-
- if not warningsShown:
- self.fail("No warnings emitted")
- first = warningsShown[0]
- for other in warningsShown[1:]:
- if ((other.message, other.category)
- != (first.message, first.category)):
- self.fail("Can't handle different warnings")
- self.assertEqual(first.message, message)
- self.assertIdentical(first.category, category)
-
- # Use starts with because of .pyc/.pyo issues.
- self.failUnless(
- filename.startswith(first.filename),
- 'Warning in %r, expected %r' % (first.filename, filename))
-
- # It would be nice to be able to check the line number as well, but
- # different configurations actually end up reporting different line
- # numbers (generally the variation is only 1 line, but that's enough
- # to fail the test erroneously...).
- # self.assertEqual(lineno, xxx)
-
- return result
- assertWarns = failUnlessWarns
-
- def failUnlessIsInstance(self, instance, classOrTuple, message=None):
- """
- Fail if C{instance} is not an instance of the given class or of
- one of the given classes.
-
- @param instance: the object to test the type (first argument of the
- C{isinstance} call).
- @type instance: any.
- @param classOrTuple: the class or classes to test against (second
- argument of the C{isinstance} call).
- @type classOrTuple: class, type, or tuple.
-
- @param message: Custom text to include in the exception text if the
- assertion fails.
- """
- if not isinstance(instance, classOrTuple):
- if message is None:
- suffix = ""
- else:
- suffix = ": " + message
- self.fail("%r is not an instance of %s%s" % (
- instance, classOrTuple, suffix))
- assertIsInstance = failUnlessIsInstance
-
- def failIfIsInstance(self, instance, classOrTuple):
- """
- Fail if C{instance} is not an instance of the given class or of
- one of the given classes.
-
- @param instance: the object to test the type (first argument of the
- C{isinstance} call).
- @type instance: any.
- @param classOrTuple: the class or classes to test against (second
- argument of the C{isinstance} call).
- @type classOrTuple: class, type, or tuple.
- """
- if isinstance(instance, classOrTuple):
- self.fail("%r is an instance of %s" % (instance, classOrTuple))
- assertNotIsInstance = failIfIsInstance
-
-
-class _LogObserver(object):
- """
- Observes the Twisted logs and catches any errors.
-
- @ivar _errors: A C{list} of L{Failure} instances which were received as
- error events from the Twisted logging system.
-
- @ivar _added: A C{int} giving the number of times C{_add} has been called
- less the number of times C{_remove} has been called; used to only add
- this observer to the Twisted logging since once, regardless of the
- number of calls to the add method.
-
- @ivar _ignored: A C{list} of exception types which will not be recorded.
- """
-
- def __init__(self):
- self._errors = []
- self._added = 0
- self._ignored = []
-
-
- def _add(self):
- if self._added == 0:
- log.addObserver(self.gotEvent)
- self._added += 1
-
-
- def _remove(self):
- self._added -= 1
- if self._added == 0:
- log.removeObserver(self.gotEvent)
-
-
- def _ignoreErrors(self, *errorTypes):
- """
- Do not store any errors with any of the given types.
- """
- self._ignored.extend(errorTypes)
-
-
- def _clearIgnores(self):
- """
- Stop ignoring any errors we might currently be ignoring.
- """
- self._ignored = []
-
-
- def flushErrors(self, *errorTypes):
- """
- Flush errors from the list of caught errors. If no arguments are
- specified, remove all errors. If arguments are specified, only remove
- errors of those types from the stored list.
- """
- if errorTypes:
- flushed = []
- remainder = []
- for f in self._errors:
- if f.check(*errorTypes):
- flushed.append(f)
- else:
- remainder.append(f)
- self._errors = remainder
- else:
- flushed = self._errors
- self._errors = []
- return flushed
-
-
- def getErrors(self):
- """
- Return a list of errors caught by this observer.
- """
- return self._errors
-
-
- def gotEvent(self, event):
- """
- The actual observer method. Called whenever a message is logged.
-
- @param event: A dictionary containing the log message. Actual
- structure undocumented (see source for L{twisted.python.log}).
- """
- if event.get('isError', False) and 'failure' in event:
- f = event['failure']
- if len(self._ignored) == 0 or not f.check(*self._ignored):
- self._errors.append(f)
-
-
-
-_logObserver = _LogObserver()
-
-_wait_is_running = []
-
-
-class SynchronousTestCase(_Assertions):
- """
- A unit test. The atom of the unit testing universe.
-
- This class extends C{unittest.TestCase} from the standard library. A number
- of convenient testing helpers are added, including logging and warning
- integration, monkey-patching support, and more.
-
- To write a unit test, subclass C{SynchronousTestCase} and define a method
- (say, 'test_foo') on the subclass. To run the test, instantiate your
- subclass with the name of the method, and call L{run} on the instance,
- passing a L{TestResult} object.
-
- The C{trial} script will automatically find any C{SynchronousTestCase}
- subclasses defined in modules beginning with 'test_' and construct test
- cases for all methods beginning with 'test'.
-
- If an error is logged during the test run, the test will fail with an
- error. See L{log.err}.
-
- @ivar failureException: An exception class, defaulting to C{FailTest}. If
- the test method raises this exception, it will be reported as a failure,
- rather than an exception. All of the assertion methods raise this if the
- assertion fails.
-
- @ivar skip: C{None} or a string explaining why this test is to be
- skipped. If defined, the test will not be run. Instead, it will be
- reported to the result object as 'skipped' (if the C{TestResult} supports
- skipping).
-
- @ivar todo: C{None}, a string or a tuple of C{(errors, reason)} where
- C{errors} is either an exception class or an iterable of exception
- classes, and C{reason} is a string. See L{Todo} or L{makeTodo} for more
- information.
-
- @ivar suppress: C{None} or a list of tuples of C{(args, kwargs)} to be
- passed to C{warnings.filterwarnings}. Use these to suppress warnings
- raised in a test. Useful for testing deprecated code. See also
- L{util.suppress}.
- """
- failureException = FailTest
-
- def __init__(self, methodName='runTest'):
- super(SynchronousTestCase, self).__init__(methodName)
- self._passed = False
- self._cleanups = []
- self._testMethodName = methodName
- testMethod = getattr(self, methodName)
- self._parents = [testMethod, self]
- self._parents.extend(util.getPythonContainers(testMethod))
-
-
- if sys.version_info >= (2, 6):
- # Override the comparison defined by the base TestCase which considers
- # instances of the same class with the same _testMethodName to be
- # equal. Since trial puts TestCase instances into a set, that
- # definition of comparison makes it impossible to run the same test
- # method twice. Most likely, trial should stop using a set to hold
- # tests, but until it does, this is necessary on Python 2.6. Only
- # __eq__ and __ne__ are required here, not __hash__, since the
- # inherited __hash__ is compatible with these equality semantics. A
- # different __hash__ might be slightly more efficient (by reducing
- # collisions), but who cares? -exarkun
- def __eq__(self, other):
- return self is other
-
- def __ne__(self, other):
- return self is not other
-
-
- def shortDescription(self):
- desc = super(SynchronousTestCase, self).shortDescription()
- if desc is None:
- return self._testMethodName
- return desc
-
-
- def getSkip(self):
- """
- Return the skip reason set on this test, if any is set. Checks on the
- instance first, then the class, then the module, then packages. As
- soon as it finds something with a C{skip} attribute, returns that.
- Returns C{None} if it cannot find anything. See L{TestCase} docstring
- for more details.
- """
- return util.acquireAttribute(self._parents, 'skip', None)
-
-
- def getTodo(self):
- """
- Return a L{Todo} object if the test is marked todo. Checks on the
- instance first, then the class, then the module, then packages. As
- soon as it finds something with a C{todo} attribute, returns that.
- Returns C{None} if it cannot find anything. See L{TestCase} docstring
- for more details.
- """
- todo = util.acquireAttribute(self._parents, 'todo', None)
- if todo is None:
- return None
- return makeTodo(todo)
-
-
- def runTest(self):
- """
- If no C{methodName} argument is passed to the constructor, L{run} will
- treat this method as the thing with the actual test inside.
- """
-
-
- def run(self, result):
- """
- Run the test case, storing the results in C{result}.
-
- First runs C{setUp} on self, then runs the test method (defined in the
- constructor), then runs C{tearDown}. As with the standard library
- L{unittest.TestCase}, the return value of these methods is disregarded.
- In particular, returning a L{Deferred} has no special additional
- consequences.
-
- @param result: A L{TestResult} object.
- """
- log.msg("--> %s <--" % (self.id()))
- new_result = itrial.IReporter(result, None)
- if new_result is None:
- result = PyUnitResultAdapter(result)
- else:
- result = new_result
- result.startTest(self)
- if self.getSkip(): # don't run test methods that are marked as .skip
- result.addSkip(self, self.getSkip())
- result.stopTest(self)
- return
-
- self._passed = False
- self._warnings = []
-
- self._installObserver()
- # All the code inside _runFixturesAndTest will be run such that warnings
- # emitted by it will be collected and retrievable by flushWarnings.
- _collectWarnings(self._warnings.append, self._runFixturesAndTest, result)
-
- # Any collected warnings which the test method didn't flush get
- # re-emitted so they'll be logged or show up on stdout or whatever.
- for w in self.flushWarnings():
- try:
- warnings.warn_explicit(**w)
- except:
- result.addError(self, failure.Failure())
-
- result.stopTest(self)
-
-
- def addCleanup(self, f, *args, **kwargs):
- """
- Add the given function to a list of functions to be called after the
- test has run, but before C{tearDown}.
-
- Functions will be run in reverse order of being added. This helps
- ensure that tear down complements set up.
-
- As with all aspects of L{SynchronousTestCase}, Deferreds are not
- supported in cleanup functions.
- """
- self._cleanups.append((f, args, kwargs))
-
-
- def patch(self, obj, attribute, value):
- """
- Monkey patch an object for the duration of the test.
-
- The monkey patch will be reverted at the end of the test using the
- L{addCleanup} mechanism.
-
- The L{MonkeyPatcher} is returned so that users can restore and
- re-apply the monkey patch within their tests.
-
- @param obj: The object to monkey patch.
- @param attribute: The name of the attribute to change.
- @param value: The value to set the attribute to.
- @return: A L{monkey.MonkeyPatcher} object.
- """
- monkeyPatch = monkey.MonkeyPatcher((obj, attribute, value))
- monkeyPatch.patch()
- self.addCleanup(monkeyPatch.restore)
- return monkeyPatch
-
-
- def flushLoggedErrors(self, *errorTypes):
- """
- Remove stored errors received from the log.
-
- C{TestCase} stores each error logged during the run of the test and
- reports them as errors during the cleanup phase (after C{tearDown}).
-
- @param *errorTypes: If unspecifed, flush all errors. Otherwise, only
- flush errors that match the given types.
-
- @return: A list of failures that have been removed.
- """
- return self._observer.flushErrors(*errorTypes)
-
-
- def flushWarnings(self, offendingFunctions=None):
- """
- Remove stored warnings from the list of captured warnings and return
- them.
-
- @param offendingFunctions: If C{None}, all warnings issued during the
- currently running test will be flushed. Otherwise, only warnings
- which I{point} to a function included in this list will be flushed.
- All warnings include a filename and source line number; if these
- parts of a warning point to a source line which is part of a
- function, then the warning I{points} to that function.
- @type offendingFunctions: C{NoneType} or L{list} of functions or methods.
-
- @raise ValueError: If C{offendingFunctions} is not C{None} and includes
- an object which is not a L{types.FunctionType} or
- L{types.MethodType} instance.
-
- @return: A C{list}, each element of which is a C{dict} giving
- information about one warning which was flushed by this call. The
- keys of each C{dict} are:
-
- - C{'message'}: The string which was passed as the I{message}
- parameter to L{warnings.warn}.
-
- - C{'category'}: The warning subclass which was passed as the
- I{category} parameter to L{warnings.warn}.
-
- - C{'filename'}: The name of the file containing the definition
- of the code object which was C{stacklevel} frames above the
- call to L{warnings.warn}, where C{stacklevel} is the value of
- the C{stacklevel} parameter passed to L{warnings.warn}.
-
- - C{'lineno'}: The source line associated with the active
- instruction of the code object object which was C{stacklevel}
- frames above the call to L{warnings.warn}, where
- C{stacklevel} is the value of the C{stacklevel} parameter
- passed to L{warnings.warn}.
- """
- if offendingFunctions is None:
- toFlush = self._warnings[:]
- self._warnings[:] = []
- else:
- toFlush = []
- for aWarning in self._warnings:
- for aFunction in offendingFunctions:
- if not isinstance(aFunction, (
- types.FunctionType, types.MethodType)):
- raise ValueError("%r is not a function or method" % (
- aFunction,))
-
- # inspect.getabsfile(aFunction) sometimes returns a
- # filename which disagrees with the filename the warning
- # system generates. This seems to be because a
- # function's code object doesn't deal with source files
- # being renamed. inspect.getabsfile(module) seems
- # better (or at least agrees with the warning system
- # more often), and does some normalization for us which
- # is desirable. inspect.getmodule() is attractive, but
- # somewhat broken in Python < 2.6. See Python bug 4845.
- aModule = sys.modules[aFunction.__module__]
- filename = inspect.getabsfile(aModule)
-
- if filename != os.path.normcase(aWarning.filename):
- continue
- lineStarts = list(_findlinestarts(aFunction.func_code))
- first = lineStarts[0][1]
- last = lineStarts[-1][1]
- if not (first <= aWarning.lineno <= last):
- continue
- # The warning points to this function, flush it and move on
- # to the next warning.
- toFlush.append(aWarning)
- break
- # Remove everything which is being flushed.
- map(self._warnings.remove, toFlush)
-
- return [
- {'message': w.message, 'category': w.category,
- 'filename': w.filename, 'lineno': w.lineno}
- for w in toFlush]
-
-
- def callDeprecated(self, version, f, *args, **kwargs):
- """
- Call a function that should have been deprecated at a specific version
- and in favor of a specific alternative, and assert that it was thusly
- deprecated.
-
- @param version: A 2-sequence of (since, replacement), where C{since} is
- a the first L{version<twisted.python.versions.Version>} that C{f}
- should have been deprecated since, and C{replacement} is a suggested
- replacement for the deprecated functionality, as described by
- L{twisted.python.deprecate.deprecated}. If there is no suggested
- replacement, this parameter may also be simply a
- L{version<twisted.python.versions.Version>} by itself.
-
- @param f: The deprecated function to call.
-
- @param args: The arguments to pass to C{f}.
-
- @param kwargs: The keyword arguments to pass to C{f}.
-
- @return: Whatever C{f} returns.
-
- @raise: Whatever C{f} raises. If any exception is
- raised by C{f}, though, no assertions will be made about emitted
- deprecations.
-
- @raise FailTest: if no warnings were emitted by C{f}, or if the
- L{DeprecationWarning} emitted did not produce the canonical
- please-use-something-else message that is standard for Twisted
- deprecations according to the given version and replacement.
- """
- result = f(*args, **kwargs)
- warningsShown = self.flushWarnings([self.callDeprecated])
- try:
- info = list(version)
- except TypeError:
- since = version
- replacement = None
- else:
- [since, replacement] = info
-
- if len(warningsShown) == 0:
- self.fail('%r is not deprecated.' % (f,))
-
- observedWarning = warningsShown[0]['message']
- expectedWarning = getDeprecationWarningString(
- f, since, replacement=replacement)
- self.assertEqual(expectedWarning, observedWarning)
-
- return result
-
-
- def mktemp(self):
- """
- Returns a unique name that may be used as either a temporary directory
- or filename.
-
- @note: you must call os.mkdir on the value returned from this method if
- you wish to use it as a directory!
- """
- MAX_FILENAME = 32 # some platforms limit lengths of filenames
- base = os.path.join(self.__class__.__module__[:MAX_FILENAME],
- self.__class__.__name__[:MAX_FILENAME],
- self._testMethodName[:MAX_FILENAME])
- if not os.path.exists(base):
- os.makedirs(base)
- dirname = tempfile.mkdtemp('', '', base)
- return os.path.join(dirname, 'temp')
-
-
- def _getSuppress(self):
- """
- Returns any warning suppressions set for this test. Checks on the
- instance first, then the class, then the module, then packages. As
- soon as it finds something with a C{suppress} attribute, returns that.
- Returns any empty list (i.e. suppress no warnings) if it cannot find
- anything. See L{TestCase} docstring for more details.
- """
- return util.acquireAttribute(self._parents, 'suppress', [])
-
-
- def _getSkipReason(self, method, skip):
- """
- Return the reason to use for skipping a test method.
-
- @param method: The method which produced the skip.
- @param skip: A L{SkipTest} instance raised by C{method}.
- """
- if len(skip.args) > 0:
- return skip.args[0]
-
- warnAboutFunction(
- method,
- "Do not raise unittest.SkipTest with no arguments! Give a reason "
- "for skipping tests!")
- return skip
-
-
- def _run(self, suppress, todo, method, result):
- """
- Run a single method, either a test method or fixture.
-
- @param suppress: Any warnings to suppress, as defined by the C{suppress}
- attribute on this method, test case, or the module it is defined in.
-
- @param todo: Any expected failure or failures, as defined by the C{todo}
- attribute on this method, test case, or the module it is defined in.
-
- @param method: The method to run.
-
- @param result: The TestResult instance to which to report results.
-
- @return: C{True} if the method fails and no further method/fixture calls
- should be made, C{False} otherwise.
- """
- try:
- # XXX runWithWarningsSuppressed is from twisted.internet, involves
- # Deferreds, we need a synchronous-only version probably.
- utils.runWithWarningsSuppressed(suppress, method)
- except SkipTest as e:
- result.addSkip(self, self._getSkipReason(method, e))
- except:
- reason = failure.Failure()
- if todo is None or not todo.expected(reason):
- if reason.check(self.failureException):
- addResult = result.addFailure
- else:
- addResult = result.addError
- addResult(self, reason)
- else:
- result.addExpectedFailure(self, reason, todo)
- else:
- return False
- return True
-
-
- def _runFixturesAndTest(self, result):
- """
- Run C{setUp}, a test method, test cleanups, and C{tearDown}.
-
- @param result: The TestResult instance to which to report results.
- """
- suppress = self._getSuppress()
- try:
- if self._run(suppress, None, self.setUp, result):
- return
-
- todo = self.getTodo()
- method = getattr(self, self._testMethodName)
- if self._run(suppress, todo, method, result):
- return
- finally:
- self._runCleanups(result)
-
- if todo:
- result.addUnexpectedSuccess(self, todo)
-
- if self._run(suppress, None, self.tearDown, result):
- return
-
- passed = True
- for error in self._observer.getErrors():
- result.addError(self, error)
- passed = False
- self._observer.flushErrors()
- self._removeObserver()
-
- if passed and not todo:
- result.addSuccess(self)
-
-
- def _runCleanups(self, result):
- """
- Synchronously run any cleanups which have been added.
- """
- while len(self._cleanups) > 0:
- f, args, kwargs = self._cleanups.pop()
- try:
- f(*args, **kwargs)
- except:
- f = failure.Failure()
- result.addError(self, f)
-
-
- def _installObserver(self):
- self._observer = _logObserver
- self._observer._add()
-
-
- def _removeObserver(self):
- self._observer._remove()
-
-
-
-class TestCase(SynchronousTestCase):
- """
- A unit test. The atom of the unit testing universe.
-
- This class extends L{SynchronousTestCase} which extends C{unittest.TestCase}
- from the standard library. The main feature is the ability to return
- C{Deferred}s from tests and fixture methods and to have the suite wait for
- those C{Deferred}s to fire.
-
- @ivar timeout: A real number of seconds. If set, the test will
- raise an error if it takes longer than C{timeout} seconds.
- If not set, util.DEFAULT_TIMEOUT_DURATION is used.
- """
- implements(itrial.ITestCase)
-
- def __init__(self, methodName='runTest'):
- """
- Construct an asynchronous test case for C{methodName}.
-
- @param methodName: The name of a method on C{self}. This method should
- be a unit test. That is, it should be a short method that calls some of
- the assert* methods. If C{methodName} is unspecified, L{runTest} will
- be used as the test method. This is mostly useful for testing Trial.
- """
- super(TestCase, self).__init__(methodName)
-
-
- def _run(self, methodName, result):
- from twisted.internet import reactor
- timeout = self.getTimeout()
- def onTimeout(d):
- e = defer.TimeoutError("%r (%s) still running at %s secs"
- % (self, methodName, timeout))
- f = failure.Failure(e)
- # try to errback the deferred that the test returns (for no gorram
- # reason) (see issue1005 and test_errorPropagation in
- # test_deferred)
- try:
- d.errback(f)
- except defer.AlreadyCalledError:
- # if the deferred has been called already but the *back chain
- # is still unfinished, crash the reactor and report timeout
- # error ourself.
- reactor.crash()
- self._timedOut = True # see self._wait
- todo = self.getTodo()
- if todo is not None and todo.expected(f):
- result.addExpectedFailure(self, f, todo)
- else:
- result.addError(self, f)
- onTimeout = utils.suppressWarnings(
- onTimeout, util.suppress(category=DeprecationWarning))
- method = getattr(self, methodName)
- d = defer.maybeDeferred(
- utils.runWithWarningsSuppressed, self._getSuppress(), method)
- call = reactor.callLater(timeout, onTimeout, d)
- d.addBoth(lambda x : call.active() and call.cancel() or x)
- return d
-
-
- def __call__(self, *args, **kwargs):
- return self.run(*args, **kwargs)
-
-
- def deferSetUp(self, ignored, result):
- d = self._run('setUp', result)
- d.addCallbacks(self.deferTestMethod, self._ebDeferSetUp,
- callbackArgs=(result,),
- errbackArgs=(result,))
- return d
-
-
- def _ebDeferSetUp(self, failure, result):
- if failure.check(SkipTest):
- result.addSkip(self, self._getSkipReason(self.setUp, failure.value))
- else:
- result.addError(self, failure)
- if failure.check(KeyboardInterrupt):
- result.stop()
- return self.deferRunCleanups(None, result)
-
-
- def deferTestMethod(self, ignored, result):
- d = self._run(self._testMethodName, result)
- d.addCallbacks(self._cbDeferTestMethod, self._ebDeferTestMethod,
- callbackArgs=(result,),
- errbackArgs=(result,))
- d.addBoth(self.deferRunCleanups, result)
- d.addBoth(self.deferTearDown, result)
- return d
-
-
- def _cbDeferTestMethod(self, ignored, result):
- if self.getTodo() is not None:
- result.addUnexpectedSuccess(self, self.getTodo())
- else:
- self._passed = True
- return ignored
-
-
- def _ebDeferTestMethod(self, f, result):
- todo = self.getTodo()
- if todo is not None and todo.expected(f):
- result.addExpectedFailure(self, f, todo)
- elif f.check(self.failureException, FailTest):
- result.addFailure(self, f)
- elif f.check(KeyboardInterrupt):
- result.addError(self, f)
- result.stop()
- elif f.check(SkipTest):
- result.addSkip(
- self,
- self._getSkipReason(getattr(self, self._testMethodName), f.value))
- else:
- result.addError(self, f)
-
-
- def deferTearDown(self, ignored, result):
- d = self._run('tearDown', result)
- d.addErrback(self._ebDeferTearDown, result)
- return d
-
-
- def _ebDeferTearDown(self, failure, result):
- result.addError(self, failure)
- if failure.check(KeyboardInterrupt):
- result.stop()
- self._passed = False
-
-
- def deferRunCleanups(self, ignored, result):
- """
- Run any scheduled cleanups and report errors (if any to the result
- object.
- """
- d = self._runCleanups()
- d.addCallback(self._cbDeferRunCleanups, result)
- return d
-
-
- def _cbDeferRunCleanups(self, cleanupResults, result):
- for flag, failure in cleanupResults:
- if flag == defer.FAILURE:
- result.addError(self, failure)
- if failure.check(KeyboardInterrupt):
- result.stop()
- self._passed = False
-
-
- def _cleanUp(self, result):
- try:
- clean = util._Janitor(self, result).postCaseCleanup()
- if not clean:
- self._passed = False
- except:
- result.addError(self, failure.Failure())
- self._passed = False
- for error in self._observer.getErrors():
- result.addError(self, error)
- self._passed = False
- self.flushLoggedErrors()
- self._removeObserver()
- if self._passed:
- result.addSuccess(self)
-
-
- def _classCleanUp(self, result):
- try:
- util._Janitor(self, result).postClassCleanup()
- except:
- result.addError(self, failure.Failure())
-
-
- def _makeReactorMethod(self, name):
- """
- Create a method which wraps the reactor method C{name}. The new
- method issues a deprecation warning and calls the original.
- """
- def _(*a, **kw):
- warnings.warn("reactor.%s cannot be used inside unit tests. "
- "In the future, using %s will fail the test and may "
- "crash or hang the test run."
- % (name, name),
- stacklevel=2, category=DeprecationWarning)
- return self._reactorMethods[name](*a, **kw)
- return _
-
-
- def _deprecateReactor(self, reactor):
- """
- Deprecate C{iterate}, C{crash} and C{stop} on C{reactor}. That is,
- each method is wrapped in a function that issues a deprecation
- warning, then calls the original.
-
- @param reactor: The Twisted reactor.
- """
- self._reactorMethods = {}
- for name in ['crash', 'iterate', 'stop']:
- self._reactorMethods[name] = getattr(reactor, name)
- setattr(reactor, name, self._makeReactorMethod(name))
-
-
- def _undeprecateReactor(self, reactor):
- """
- Restore the deprecated reactor methods. Undoes what
- L{_deprecateReactor} did.
-
- @param reactor: The Twisted reactor.
- """
- for name, method in self._reactorMethods.iteritems():
- setattr(reactor, name, method)
- self._reactorMethods = {}
-
-
- def _runCleanups(self):
- """
- Run the cleanups added with L{addCleanup} in order.
-
- @return: A C{Deferred} that fires when all cleanups are run.
- """
- def _makeFunction(f, args, kwargs):
- return lambda: f(*args, **kwargs)
- callables = []
- while len(self._cleanups) > 0:
- f, args, kwargs = self._cleanups.pop()
- callables.append(_makeFunction(f, args, kwargs))
- return util._runSequentially(callables)
-
-
- def _runFixturesAndTest(self, result):
- """
- Really run C{setUp}, the test method, and C{tearDown}. Any of these may
- return L{Deferred}s. After they complete, do some reactor cleanup.
-
- @param result: A L{TestResult} object.
- """
- from twisted.internet import reactor
- self._deprecateReactor(reactor)
- self._timedOut = False
- try:
- d = self.deferSetUp(None, result)
- try:
- self._wait(d)
- finally:
- self._cleanUp(result)
- self._classCleanUp(result)
- finally:
- self._undeprecateReactor(reactor)
-
-
- def addCleanup(self, f, *args, **kwargs):
- """
- Extend the base cleanup feature with support for cleanup functions which
- return Deferreds.
-
- If the function C{f} returns a Deferred, C{TestCase} will wait until the
- Deferred has fired before proceeding to the next function.
- """
- return super(TestCase, self).addCleanup(f, *args, **kwargs)
-
-
- def getSuppress(self):
- return self._getSuppress()
-
-
- def getTimeout(self):
- """
- Returns the timeout value set on this test. Checks on the instance
- first, then the class, then the module, then packages. As soon as it
- finds something with a C{timeout} attribute, returns that. Returns
- L{util.DEFAULT_TIMEOUT_DURATION} if it cannot find anything. See
- L{TestCase} docstring for more details.
- """
- timeout = util.acquireAttribute(self._parents, 'timeout',
- util.DEFAULT_TIMEOUT_DURATION)
- try:
- return float(timeout)
- except (ValueError, TypeError):
- # XXX -- this is here because sometimes people will have methods
- # called 'timeout', or set timeout to 'orange', or something
- # Particularly, test_news.NewsTestCase and ReactorCoreTestCase
- # both do this.
- warnings.warn("'timeout' attribute needs to be a number.",
- category=DeprecationWarning)
- return util.DEFAULT_TIMEOUT_DURATION
-
-
- def visit(self, visitor):
- """
- Visit this test case. Call C{visitor} with C{self} as a parameter.
-
- Deprecated in Twisted 8.0.
-
- @param visitor: A callable which expects a single parameter: a test
- case.
-
- @return: None
- """
- warnings.warn("Test visitors deprecated in Twisted 8.0",
- category=DeprecationWarning)
- visitor(self)
-
-
- def _wait(self, d, running=_wait_is_running):
- """Take a Deferred that only ever callbacks. Block until it happens.
- """
- from twisted.internet import reactor
- if running:
- raise RuntimeError("_wait is not reentrant")
-
- results = []
- def append(any):
- if results is not None:
- results.append(any)
- def crash(ign):
- if results is not None:
- reactor.crash()
- crash = utils.suppressWarnings(
- crash, util.suppress(message=r'reactor\.crash cannot be used.*',
- category=DeprecationWarning))
- def stop():
- reactor.crash()
- stop = utils.suppressWarnings(
- stop, util.suppress(message=r'reactor\.crash cannot be used.*',
- category=DeprecationWarning))
-
- running.append(None)
- try:
- d.addBoth(append)
- if results:
- # d might have already been fired, in which case append is
- # called synchronously. Avoid any reactor stuff.
- return
- d.addBoth(crash)
- reactor.stop = stop
- try:
- reactor.run()
- finally:
- del reactor.stop
-
- # If the reactor was crashed elsewhere due to a timeout, hopefully
- # that crasher also reported an error. Just return.
- # _timedOut is most likely to be set when d has fired but hasn't
- # completed its callback chain (see self._run)
- if results or self._timedOut: #defined in run() and _run()
- return
-
- # If the timeout didn't happen, and we didn't get a result or
- # a failure, then the user probably aborted the test, so let's
- # just raise KeyboardInterrupt.
-
- # FIXME: imagine this:
- # web/test/test_webclient.py:
- # exc = self.assertRaises(error.Error, wait, method(url))
- #
- # wait() will raise KeyboardInterrupt, and assertRaises will
- # swallow it. Therefore, wait() raising KeyboardInterrupt is
- # insufficient to stop trial. A suggested solution is to have
- # this code set a "stop trial" flag, or otherwise notify trial
- # that it should really try to stop as soon as possible.
- raise KeyboardInterrupt()
- finally:
- results = None
- running.pop()
-
-
-
-class UnsupportedTrialFeature(Exception):
- """A feature of twisted.trial was used that pyunit cannot support."""
-
-
-
-class PyUnitResultAdapter(object):
- """
- Wrap a C{TestResult} from the standard library's C{unittest} so that it
- supports the extended result types from Trial, and also supports
- L{twisted.python.failure.Failure}s being passed to L{addError} and
- L{addFailure}.
- """
-
- def __init__(self, original):
- """
- @param original: A C{TestResult} instance from C{unittest}.
- """
- self.original = original
-
- def _exc_info(self, err):
- return util.excInfoOrFailureToExcInfo(err)
-
- def startTest(self, method):
- self.original.startTest(method)
-
- def stopTest(self, method):
- self.original.stopTest(method)
-
- def addFailure(self, test, fail):
- self.original.addFailure(test, self._exc_info(fail))
-
- def addError(self, test, error):
- self.original.addError(test, self._exc_info(error))
-
- def _unsupported(self, test, feature, info):
- self.original.addFailure(
- test,
- (UnsupportedTrialFeature,
- UnsupportedTrialFeature(feature, info),
- None))
-
- def addSkip(self, test, reason):
- """
- Report the skip as a failure.
- """
- self._unsupported(test, 'skip', reason)
-
- def addUnexpectedSuccess(self, test, todo):
- """
- Report the unexpected success as a failure.
- """
- self._unsupported(test, 'unexpected success', todo)
-
- def addExpectedFailure(self, test, error):
- """
- Report the expected failure (i.e. todo) as a failure.
- """
- self._unsupported(test, 'expected failure', error)
-
- def addSuccess(self, test):
- self.original.addSuccess(test)
-
- def upDownError(self, method, error, warn, printStatus):
- pass
-
-
-
-def suiteVisit(suite, visitor):
- """
- Visit each test in C{suite} with C{visitor}.
-
- Deprecated in Twisted 8.0.
-
- @param visitor: A callable which takes a single argument, the L{TestCase}
- instance to visit.
- @return: None
- """
- warnings.warn("Test visitors deprecated in Twisted 8.0",
- category=DeprecationWarning)
- for case in suite._tests:
- visit = getattr(case, 'visit', None)
- if visit is not None:
- visit(visitor)
- elif isinstance(case, pyunit.TestCase):
- case = itrial.ITestCase(case)
- case.visit(visitor)
- elif isinstance(case, pyunit.TestSuite):
- suiteVisit(case, visitor)
- else:
- case.visit(visitor)
-
-
-
-class TestSuite(pyunit.TestSuite):
- """
- Extend the standard library's C{TestSuite} with support for the visitor
- pattern and a consistently overrideable C{run} method.
- """
-
- visit = suiteVisit
-
- def __call__(self, result):
- return self.run(result)
-
-
- def run(self, result):
- """
- Call C{run} on every member of the suite.
- """
- # we implement this because Python 2.3 unittest defines this code
- # in __call__, whereas 2.4 defines the code in run.
- for test in self._tests:
- if result.shouldStop:
- break
- test(result)
- return result
-
-
-
-class TestDecorator(components.proxyForInterface(itrial.ITestCase,
- "_originalTest")):
- """
- Decorator for test cases.
-
- @param _originalTest: The wrapped instance of test.
- @type _originalTest: A provider of L{itrial.ITestCase}
- """
-
- implements(itrial.ITestCase)
-
-
- def __call__(self, result):
- """
- Run the unit test.
-
- @param result: A TestResult object.
- """
- return self.run(result)
-
-
- def run(self, result):
- """
- Run the unit test.
-
- @param result: A TestResult object.
- """
- return self._originalTest.run(
- reporter._AdaptedReporter(result, self.__class__))
-
-
-
-def _clearSuite(suite):
- """
- Clear all tests from C{suite}.
-
- This messes with the internals of C{suite}. In particular, it assumes that
- the suite keeps all of its tests in a list in an instance variable called
- C{_tests}.
- """
- suite._tests = []
-
-
-def decorate(test, decorator):
- """
- Decorate all test cases in C{test} with C{decorator}.
-
- C{test} can be a test case or a test suite. If it is a test suite, then the
- structure of the suite is preserved.
-
- L{decorate} tries to preserve the class of the test suites it finds, but
- assumes the presence of the C{_tests} attribute on the suite.
-
- @param test: The C{TestCase} or C{TestSuite} to decorate.
-
- @param decorator: A unary callable used to decorate C{TestCase}s.
-
- @return: A decorated C{TestCase} or a C{TestSuite} containing decorated
- C{TestCase}s.
- """
-
- try:
- tests = iter(test)
- except TypeError:
- return decorator(test)
-
- # At this point, we know that 'test' is a test suite.
- _clearSuite(test)
-
- for case in tests:
- test.addTest(decorate(case, decorator))
- return test
-
-
-
-class _PyUnitTestCaseAdapter(TestDecorator):
- """
- Adapt from pyunit.TestCase to ITestCase.
- """
-
-
- def visit(self, visitor):
- """
- Deprecated in Twisted 8.0.
- """
- warnings.warn("Test visitors deprecated in Twisted 8.0",
- category=DeprecationWarning)
- visitor(self)
-
-
-
-class _BrokenIDTestCaseAdapter(_PyUnitTestCaseAdapter):
- """
- Adapter for pyunit-style C{TestCase} subclasses that have undesirable id()
- methods. That is L{pyunit.FunctionTestCase} and L{pyunit.DocTestCase}.
- """
-
- def id(self):
- """
- Return the fully-qualified Python name of the doctest.
- """
- testID = self._originalTest.shortDescription()
- if testID is not None:
- return testID
- return self._originalTest.id()
-
-
-
-class _ForceGarbageCollectionDecorator(TestDecorator):
- """
- Forces garbage collection to be run before and after the test. Any errors
- logged during the post-test collection are added to the test result as
- errors.
- """
-
- def run(self, result):
- gc.collect()
- TestDecorator.run(self, result)
- _logObserver._add()
- gc.collect()
- for error in _logObserver.getErrors():
- result.addError(self, error)
- _logObserver.flushErrors()
- _logObserver._remove()
-
-
-components.registerAdapter(
- _PyUnitTestCaseAdapter, pyunit.TestCase, itrial.ITestCase)
-
-
-components.registerAdapter(
- _BrokenIDTestCaseAdapter, pyunit.FunctionTestCase, itrial.ITestCase)
-
-
-_docTestCase = getattr(doctest, 'DocTestCase', None)
-if _docTestCase:
- components.registerAdapter(
- _BrokenIDTestCaseAdapter, _docTestCase, itrial.ITestCase)
-
-
-def _iterateTests(testSuiteOrCase):
- """
- Iterate through all of the test cases in C{testSuiteOrCase}.
- """
- try:
- suite = iter(testSuiteOrCase)
- except TypeError:
- yield testSuiteOrCase
- else:
- for test in suite:
- for subtest in _iterateTests(test):
- yield subtest
-
-
-
-# Support for Python 2.3
-try:
- iter(pyunit.TestSuite())
-except TypeError:
- # Python 2.3's TestSuite doesn't support iteration. Let's monkey patch it!
- def __iter__(self):
- return iter(self._tests)
- pyunit.TestSuite.__iter__ = __iter__
-
-
-
-class _SubTestCase(TestCase):
- def __init__(self):
- TestCase.__init__(self, 'run')
-
-_inst = _SubTestCase()
-
-def _deprecate(name):
- """
- Internal method used to deprecate top-level assertions. Do not use this.
- """
- def _(*args, **kwargs):
- warnings.warn("unittest.%s is deprecated. Instead use the %r "
- "method on unittest.TestCase" % (name, name),
- stacklevel=2, category=DeprecationWarning)
- return getattr(_inst, name)(*args, **kwargs)
- return _
-
-
-_assertions = ['fail', 'failUnlessEqual', 'failIfEqual', 'failIfEquals',
- 'failUnless', 'failUnlessIdentical', 'failUnlessIn',
- 'failIfIdentical', 'failIfIn', 'failIf',
- 'failUnlessAlmostEqual', 'failIfAlmostEqual',
- 'failUnlessRaises', 'assertApproximates',
- 'assertFailure', 'failUnlessSubstring', 'failIfSubstring',
- 'assertAlmostEqual', 'assertAlmostEquals',
- 'assertNotAlmostEqual', 'assertNotAlmostEquals', 'assertEqual',
- 'assertEquals', 'assertNotEqual', 'assertNotEquals',
- 'assertRaises', 'assert_', 'assertIdentical',
- 'assertNotIdentical', 'assertIn', 'assertNotIn',
- 'failUnlessFailure', 'assertSubstring', 'assertNotSubstring']
-
-
-for methodName in _assertions:
- globals()[methodName] = _deprecate(methodName)
-del methodName
-
-
-__all__ = ['SynchronousTestCase', 'TestCase', 'FailTest', 'SkipTest']
diff --git a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/util.py b/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/util.py
deleted file mode 100755
index 90d4437f..00000000
--- a/lib/python2.7/site-packages/Twisted-12.2.0-py2.7-linux-x86_64.egg/twisted/trial/util.py
+++ /dev/null
@@ -1,430 +0,0 @@
-# -*- test-case-name: twisted.trial.test.test_util -*-
-# Copyright (c) Twisted Matrix Laboratories.
-# See LICENSE for details.
-#
-
-"""
-A collection of utility functions and classes, used internally by Trial.
-
-This code is for Trial's internal use. Do NOT use this code if you are writing
-tests. It is subject to change at the Trial maintainer's whim. There is
-nothing here in this module for you to use unless you are maintaining Trial.
-
-Any non-Trial Twisted code that uses this module will be shot.
-
-Maintainer: Jonathan Lange
-"""
-
-import traceback, sys
-from random import randrange
-
-from twisted.internet import defer, utils, interfaces
-from twisted.python.failure import Failure
-from twisted.python import deprecate, versions
-from twisted.python.lockfile import FilesystemLock
-from twisted.python.filepath import FilePath
-
-DEFAULT_TIMEOUT = object()
-DEFAULT_TIMEOUT_DURATION = 120.0
-
-
-
-class DirtyReactorAggregateError(Exception):
- """
- Passed to L{twisted.trial.itrial.IReporter.addError} when the reactor is
- left in an unclean state after a test.
-
- @ivar delayedCalls: The L{DelayedCall} objects which weren't cleaned up.
- @ivar selectables: The selectables which weren't cleaned up.
- """
-
- def __init__(self, delayedCalls, selectables=None):
- self.delayedCalls = delayedCalls
- self.selectables = selectables
-
- def __str__(self):
- """
- Return a multi-line message describing all of the unclean state.
- """
- msg = "Reactor was unclean."
- if self.delayedCalls:
- msg += ("\nDelayedCalls: (set "
- "twisted.internet.base.DelayedCall.debug = True to "
- "debug)\n")
- msg += "\n".join(map(str, self.delayedCalls))
- if self.selectables:
- msg += "\nSelectables:\n"
- msg += "\n".join(map(str, self.selectables))
- return msg
-
-
-
-class _Janitor(object):
- """
- The guy that cleans up after you.
-
- @ivar test: The L{TestCase} to report errors about.
- @ivar result: The L{IReporter} to report errors to.
- @ivar reactor: The reactor to use. If None, the global reactor
- will be used.
- """
- def __init__(self, test, result, reactor=None):
- """
- @param test: See L{_Janitor.test}.
- @param result: See L{_Janitor.result}.
- @param reactor: See L{_Janitor.reactor}.
- """
- self.test = test
- self.result = result
- self.reactor = reactor
-
-
- def postCaseCleanup(self):
- """
- Called by L{unittest.TestCase} after a test to catch any logged errors
- or pending L{DelayedCall}s.
- """
- calls = self._cleanPending()
- if calls:
- aggregate = DirtyReactorAggregateError(calls)
- self.result.addError(self.test, Failure(aggregate))
- return False
- return True
-
-
- def postClassCleanup(self):
- """
- Called by L{unittest.TestCase} after the last test in a C{TestCase}
- subclass. Ensures the reactor is clean by murdering the threadpool,
- catching any pending L{DelayedCall}s, open sockets etc.
- """
- selectables = self._cleanReactor()
- calls = self._cleanPending()
- if selectables or calls:
- aggregate = DirtyReactorAggregateError(calls, selectables)
- self.result.addError(self.test, Failure(aggregate))
- self._cleanThreads()
-
-
- def _getReactor(self):
- """
- Get either the passed-in reactor or the global reactor.
- """
- if self.reactor is not None:
- reactor = self.reactor
- else:
- from twisted.internet import reactor
- return reactor
-
-
- def _cleanPending(self):
- """
- Cancel all pending calls and return their string representations.
- """
- reactor = self._getReactor()
-
- # flush short-range timers
- reactor.iterate(0)
- reactor.iterate(0)
-
- delayedCallStrings = []
- for p in reactor.getDelayedCalls():
- if p.active():
- delayedString = str(p)
- p.cancel()
- else:
- print "WEIRDNESS! pending timed call not active!"
- delayedCallStrings.append(delayedString)
- return delayedCallStrings
- _cleanPending = utils.suppressWarnings(
- _cleanPending, (('ignore',), {'category': DeprecationWarning,
- 'message':
- r'reactor\.iterate cannot be used.*'}))
-
- def _cleanThreads(self):
- reactor = self._getReactor()
- if interfaces.IReactorThreads.providedBy(reactor):
- if reactor.threadpool is not None:
- # Stop the threadpool now so that a new one is created.
- # This improves test isolation somewhat (although this is a
- # post class cleanup hook, so it's only isolating classes
- # from each other, not methods from each other).
- reactor._stopThreadPool()
-
- def _cleanReactor(self):
- """
- Remove all selectables from the reactor, kill any of them that were
- processes, and return their string representation.
- """
- reactor = self._getReactor()
- selectableStrings = []
- for sel in reactor.removeAll():
- if interfaces.IProcessTransport.providedBy(sel):
- sel.signalProcess('KILL')
- selectableStrings.append(repr(sel))
- return selectableStrings
-
-
-def excInfoOrFailureToExcInfo(err):
- """
- Coerce a Failure to an _exc_info, if err is a Failure.
-
- @param err: Either a tuple such as returned by L{sys.exc_info} or a
- L{Failure} object.
- @return: A tuple like the one returned by L{sys.exc_info}. e.g.
- C{exception_type, exception_object, traceback_object}.
- """
- if isinstance(err, Failure):
- # Unwrap the Failure into a exc_info tuple.
- err = (err.type, err.value, err.getTracebackObject())
- return err
-
-
-def suppress(action='ignore', **kwarg):
- """
- Sets up the .suppress tuple properly, pass options to this method as you
- would the stdlib warnings.filterwarnings()
-
- So, to use this with a .suppress magic attribute you would do the
- following:
-
- >>> from twisted.trial import unittest, util
- >>> import warnings
- >>>
- >>> class TestFoo(unittest.TestCase):
- ... def testFooBar(self):
- ... warnings.warn("i am deprecated", DeprecationWarning)
- ... testFooBar.suppress = [util.suppress(message='i am deprecated')]
- ...
- >>>
-
- Note that as with the todo and timeout attributes: the module level
- attribute acts as a default for the class attribute which acts as a default
- for the method attribute. The suppress attribute can be overridden at any
- level by specifying C{.suppress = []}
- """
- return ((action,), kwarg)
-
-
-def profiled(f, outputFile):
- def _(*args, **kwargs):
- if sys.version_info[0:2] != (2, 4):
- import profile
- prof = profile.Profile()
- try:
- result = prof.runcall(f, *args, **kwargs)
- prof.dump_stats(outputFile)
- except SystemExit:
- pass
- prof.print_stats()
- return result
- else: # use hotshot, profile is broken in 2.4
- import hotshot.stats
- prof = hotshot.Profile(outputFile)
- try:
- return prof.runcall(f, *args, **kwargs)
- finally:
- stats = hotshot.stats.load(outputFile)
- stats.strip_dirs()
- stats.sort_stats('cum') # 'time'
- stats.print_stats(100)
- return _
-
-
-def getPythonContainers(meth):
- """Walk up the Python tree from method 'meth', finding its class, its module
- and all containing packages."""
- containers = []
- containers.append(meth.im_class)
- moduleName = meth.im_class.__module__
- while moduleName is not None:
- module = sys.modules.get(moduleName, None)
- if module is None:
- module = __import__(moduleName)
- containers.append(module)
- moduleName = getattr(module, '__module__', None)
- return containers
-
-
-_DEFAULT = object()
-def acquireAttribute(objects, attr, default=_DEFAULT):
- """Go through the list 'objects' sequentially until we find one which has
- attribute 'attr', then return the value of that attribute. If not found,
- return 'default' if set, otherwise, raise AttributeError. """
- for obj in objects:
- if hasattr(obj, attr):
- return getattr(obj, attr)
- if default is not _DEFAULT:
- return default
- raise AttributeError('attribute %r not found in %r' % (attr, objects))
-
-
-
-deprecate.deprecatedModuleAttribute(
- versions.Version("Twisted", 10, 1, 0),
- "Please use twisted.python.reflect.namedAny instead.",
- __name__, "findObject")
-
-
-
-def findObject(name):
- """Get a fully-named package, module, module-global object or attribute.
- Forked from twisted.python.reflect.namedAny.
-
- Returns a tuple of (bool, obj). If bool is True, the named object exists
- and is returned as obj. If bool is False, the named object does not exist
- and the value of obj is unspecified.
- """
- names = name.split('.')
- topLevelPackage = None
- moduleNames = names[:]
- while not topLevelPackage:
- trialname = '.'.join(moduleNames)
- if len(trialname) == 0:
- return (False, None)
- try:
- topLevelPackage = __import__(trialname)
- except ImportError:
- # if the ImportError happened in the module being imported,
- # this is a failure that should be handed to our caller.
- # count stack frames to tell the difference.
- exc_info = sys.exc_info()
- if len(traceback.extract_tb(exc_info[2])) > 1:
- try:
- # Clean up garbage left in sys.modules.
- del sys.modules[trialname]
- except KeyError:
- # Python 2.4 has fixed this. Yay!
- pass
- raise exc_info[0], exc_info[1], exc_info[2]
- moduleNames.pop()
- obj = topLevelPackage
- for n in names[1:]:
- try:
- obj = getattr(obj, n)
- except AttributeError:
- return (False, obj)
- return (True, obj)
-
-
-
-def _runSequentially(callables, stopOnFirstError=False):
- """
- Run the given callables one after the other. If a callable returns a
- Deferred, wait until it has finished before running the next callable.
-
- @param callables: An iterable of callables that take no parameters.
-
- @param stopOnFirstError: If True, then stop running callables as soon as
- one raises an exception or fires an errback. False by default.
-
- @return: A L{Deferred} that fires a list of C{(flag, value)} tuples. Each
- tuple will be either C{(SUCCESS, <return value>)} or C{(FAILURE,
- <Failure>)}.
- """
- results = []
- for f in callables:
- d = defer.maybeDeferred(f)
- thing = defer.waitForDeferred(d)
- yield thing
- try:
- results.append((defer.SUCCESS, thing.getResult()))
- except:
- results.append((defer.FAILURE, Failure()))
- if stopOnFirstError:
- break
- yield results
-_runSequentially = defer.deferredGenerator(_runSequentially)
-
-
-
-class _NoTrialMarker(Exception):
- """
- No trial marker file could be found.
-
- Raised when trial attempts to remove a trial temporary working directory
- that does not contain a marker file.
- """
-
-
-
-def _removeSafely(path):
- """
- Safely remove a path, recursively.
-
- If C{path} does not contain a node named C{_trial_marker}, a
- L{_NoTrialmarker} exception is raised and the path is not removed.
- """
- if not path.child('_trial_marker').exists():
- raise _NoTrialMarker(
- '%r is not a trial temporary path, refusing to remove it'
- % (path,))
- try:
- path.remove()
- except OSError, e:
- print ("could not remove %r, caught OSError [Errno %s]: %s"
- % (path, e.errno, e.strerror))
- try:
- newPath = FilePath('_trial_temp_old%s' % (randrange(1000000),))
- path.moveTo(newPath)
- except OSError, e:
- print ("could not rename path, caught OSError [Errno %s]: %s"
- % (e.errno,e.strerror))
- raise
-
-
-
-class _WorkingDirectoryBusy(Exception):
- """
- A working directory was specified to the runner, but another test run is
- currently using that directory.
- """
-
-
-
-def _unusedTestDirectory(base):
- """
- Find an unused directory named similarly to C{base}.
-
- Once a directory is found, it will be locked and a marker dropped into it to
- identify it as a trial temporary directory.
-
- @param base: A template path for the discovery process. If this path
- exactly cannot be used, a path which varies only in a suffix of the
- basename will be used instead.
- @type base: L{FilePath}
-
- @return: A two-tuple. The first element is a L{FilePath} representing the
- directory which was found and created. The second element is a locked
- L{FilesystemLock}. Another call to C{_unusedTestDirectory} will not be
- able to reused the the same name until the lock is released, either
- explicitly or by this process exiting.
- """
- counter = 0
- while True:
- if counter:
- testdir = base.sibling('%s-%d' % (base.basename(), counter))
- else:
- testdir = base
-
- testDirLock = FilesystemLock(testdir.path + '.lock')
- if testDirLock.lock():
- # It is not in use
- if testdir.exists():
- # It exists though - delete it
- _removeSafely(testdir)
-
- # Create it anew and mark it as ours so the next _removeSafely on it
- # succeeds.
- testdir.makedirs()
- testdir.child('_trial_marker').setContent('')
- return testdir, testDirLock
- else:
- # It is in use
- if base.basename() == '_trial_temp':
- counter += 1
- else:
- raise _WorkingDirectoryBusy()
-
-
-__all__ = ['excInfoOrFailureToExcInfo', 'suppress']