Python twisted.trial.unittest.TestCase() Examples

The following are 30 code examples of twisted.trial.unittest.TestCase(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.trial.unittest , or try the search function .
Example #1
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_unorderable_types(testdir):
    testdir.makepyfile(
        """
        import unittest
        class TestJoinEmpty(unittest.TestCase):
            pass

        def make_test():
            class Test(unittest.TestCase):
                pass
            Test.__name__ = "TestFoo"
            return Test
        TestFoo = make_test()
    """
    )
    result = testdir.runpytest()
    result.stdout.no_fnmatch_line("*TypeError*")
    assert result.ret == ExitCode.NO_TESTS_COLLECTED 
Example #2
Source File: test_disttrial.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_runUnexpectedError(self):
        """
        If for some reasons we can't connect to the worker process, the test
        suite catches and fails.
        """

        class FakeReactorWithFail(FakeReactor):

            def spawnProcess(self, worker, *args, **kwargs):
                worker.makeConnection(FakeTransport())
                self.spawnCount += 1
                worker._ampProtocol.run = self.failingRun

            def failingRun(self, case, result):
                return fail(RuntimeError("oops"))

        scheduler, cooperator = self.getFakeSchedulerAndEternalCooperator()

        fakeReactor = FakeReactorWithFail()
        result = self.runner.run(TestCase(), fakeReactor,
                                 cooperator.cooperate)
        self.assertEqual(fakeReactor.runCount, 1)
        self.assertEqual(fakeReactor.spawnCount, 1)
        scheduler.pump()
        self.assertEqual(1, len(result.original.failures)) 
Example #3
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def assertNotReading(testCase, reactor, transport):
    """
    Use the given test to assert that the given transport is I{not} actively
    reading in the given reactor.

    @note: Maintainers; for more information on why this is a function rather
        than a method on a test case, see U{this document on how we structure
        test tools
        <http://twistedmatrix.com/trac/wiki/Design/KeepTestToolsOutOfFixtures>}

    @param testCase: a test case to perform the assertion upon.
    @type testCase: L{TestCase}

    @param reactor: A reactor, possibly one providing L{IReactorFDSet}, or an
        IOCP reactor.

    @param transport: An L{ITCPTransport}
    """
    if IReactorFDSet.providedBy(reactor):
        testCase.assertNotIn(transport, reactor.getReaders())
    else:
        # IOCP.
        testCase.assertFalse(transport.reading) 
Example #4
Source File: runner.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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 
Example #5
Source File: test_runner.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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) 
Example #6
Source File: test_runner.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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'))

        f()
        warnings = self.flushWarnings([self.test_reporterDeprecations])

        self.assertEqual(warnings[0]['category'], DeprecationWarning)
        self.assertEqual(warnings[0]['message'],
            "%s should implement done() but doesn't. Falling back to "
            "printErrors() and friends." % reflect.qual(result.__class__))
        self.assertTrue(__file__.startswith(warnings[0]['filename']))
        self.assertEqual(len(warnings), 1) 
Example #7
Source File: test_tests.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
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)
        unittest.decorate(suite, unittest.TestDecorator)
        count2 = getrefcount(test)
        self.assertEqual(count1, count2) 
Example #8
Source File: test_assertions.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _testUnequalPair(self, first, second):
        """
        Assert that when called with unequal arguments, C{assertEqual} raises a
        failure exception with the same message as the standard library
        C{assertEqual} would have raised.
        """
        raised = False
        try:
            self.assertEqual(first, second)
        except self.failureException as ourFailure:
            case = pyunit.TestCase("setUp")
            try:
                case.assertEqual(first, second)
            except case.failureException as theirFailure:
                raised = True
                got = str(ourFailure)
                expected = str(theirFailure)
                if expected != got:
                    self.fail("Expected: %r; Got: %r" % (expected, got))

        if not raised:
            self.fail(
                "Call to assertEqual(%r, %r) didn't fail" % (first, second)
            ) 
Example #9
Source File: test_mail.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def testHandle(self):
        result = {}
        lines = [
            'user:  another@host\n',
            'nextuser:  |/bin/program\n',
            'user:  me@again\n',
            'moreusers: :/etc/include/filename\n',
            'multiuser: first@host, second@host,last@anotherhost',
        ]

        for l in lines:
            mail.alias.handle(result, l, 'TestCase', None)

        self.assertEqual(result['user'], ['another@host', 'me@again'])
        self.assertEqual(result['nextuser'], ['|/bin/program'])
        self.assertEqual(result['moreusers'], [':/etc/include/filename'])
        self.assertEqual(result['multiuser'], ['first@host', 'second@host', 'last@anotherhost']) 
Example #10
Source File: test_checkers.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def assertLoggedIn(self, d, username):
        """
        Assert that the L{Deferred} passed in is called back with the value
        'username'.  This represents a valid login for this TestCase.

        NOTE: To work, this method's return value must be returned from the
        test method, or otherwise hooked up to the test machinery.

        @param d: a L{Deferred} from an L{IChecker.requestAvatarId} method.
        @type d: L{Deferred}
        @rtype: L{Deferred}
        """
        result = []
        d.addBoth(result.append)
        self.assertEqual(len(result), 1, "login incomplete")
        if isinstance(result[0], Failure):
            result[0].raiseException()
        self.assertEqual(result[0], username) 
Example #11
Source File: test_json.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def savedJSONInvariants(testCase, savedJSON):
    """
    Assert a few things about the result of L{eventAsJSON}, then return it.

    @param testCase: The L{TestCase} with which to perform the assertions.
    @type testCase: L{TestCase}

    @param savedJSON: The result of L{eventAsJSON}.
    @type savedJSON: L{unicode} (we hope)

    @return: C{savedJSON}
    @rtype: L{unicode}

    @raise AssertionError: If any of the preconditions fail.
    """
    testCase.assertIsInstance(savedJSON, unicode)
    testCase.assertEqual(savedJSON.count("\n"), 0)
    return savedJSON 
Example #12
Source File: test_sslverify.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def pathContainingDumpOf(testCase, *dumpables):
    """
    Create a temporary file to store some serializable-as-PEM objects in, and
    return its name.

    @param testCase: a test case to use for generating a temporary directory.
    @type testCase: L{twisted.trial.unittest.TestCase}

    @param dumpables: arguments are objects from pyOpenSSL with a C{dump}
        method, taking a pyOpenSSL file-type constant, such as
        L{OpenSSL.crypto.FILETYPE_PEM} or L{OpenSSL.crypto.FILETYPE_ASN1}.
    @type dumpables: L{tuple} of L{object} with C{dump} method taking L{int}
        returning L{bytes}

    @return: the path to a file where all of the dumpables were dumped in PEM
        format.
    @rtype: L{str}
    """
    fname = testCase.mktemp()
    with open(fname, "wb") as f:
        for dumpable in dumpables:
            f.write(dumpable.dump(FILETYPE_PEM))
    return fname 
Example #13
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_runTest_method(testdir):
    testdir.makepyfile(
        """
        import unittest
        class MyTestCaseWithRunTest(unittest.TestCase):
            def runTest(self):
                self.assertEqual('foo', 'foo')
        class MyTestCaseWithoutRunTest(unittest.TestCase):
            def runTest(self):
                self.assertEqual('foo', 'foo')
            def test_something(self):
                pass
        """
    )
    result = testdir.runpytest("-v")
    result.stdout.fnmatch_lines(
        """
        *MyTestCaseWithRunTest::runTest*
        *MyTestCaseWithoutRunTest::test_something*
        *2 passed*
    """
    ) 
Example #14
Source File: test_tcp.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def assertReading(testCase, reactor, transport):
    """
    Use the given test to assert that the given transport is actively reading
    in the given reactor.

    @note: Maintainers; for more information on why this is a function rather
        than a method on a test case, see U{this document on how we structure
        test tools
        <http://twistedmatrix.com/trac/wiki/Design/KeepTestToolsOutOfFixtures>}

    @param testCase: a test case to perform the assertion upon.
    @type testCase: L{TestCase}

    @param reactor: A reactor, possibly one providing L{IReactorFDSet}, or an
        IOCP reactor.

    @param transport: An L{ITCPTransport}
    """
    if IReactorFDSet.providedBy(reactor):
        testCase.assertIn(transport, reactor.getReaders())
    else:
        # IOCP.
        testCase.assertIn(transport, reactor.handles)
        testCase.assertTrue(transport.reading) 
Example #15
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_trial_testcase_runtest_not_collected(self, testdir):
        testdir.makepyfile(
            """
            from twisted.trial.unittest import TestCase

            class TC(TestCase):
                def test_hello(self):
                    pass
        """
        )
        reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)
        reprec.assertoutcome(passed=1)
        testdir.makepyfile(
            """
            from twisted.trial.unittest import TestCase

            class TC(TestCase):
                def runTest(self):
                    pass
        """
        )
        reprec = testdir.inline_run(*self.ignore_unclosed_socket_warning)
        reprec.assertoutcome(passed=1) 
Example #16
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_testcase_adderrorandfailure_defers(testdir, type):
    testdir.makepyfile(
        """
        from unittest import TestCase
        import pytest
        class MyTestCase(TestCase):
            def run(self, result):
                excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)
                try:
                    result.add%s(self, excinfo._excinfo)
                except KeyboardInterrupt:
                    raise
                except:
                    pytest.fail("add%s should not raise")
            def test_hello(self):
                pass
    """
        % (type, type)
    )
    result = testdir.runpytest()
    result.stdout.no_fnmatch_line("*should not raise*") 
Example #17
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_setup_setUpClass(testdir):
    testpath = testdir.makepyfile(
        """
        import unittest
        import pytest
        class MyTestCase(unittest.TestCase):
            x = 0
            @classmethod
            def setUpClass(cls):
                cls.x += 1
            def test_func1(self):
                assert self.x == 1
            def test_func2(self):
                assert self.x == 1
            @classmethod
            def tearDownClass(cls):
                cls.x -= 1
        def test_teareddown():
            assert MyTestCase.x == 0
    """
    )
    reprec = testdir.inline_run(testpath)
    reprec.assertoutcome(passed=3) 
Example #18
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_setup_failure_is_shown(testdir):
    testdir.makepyfile(
        """
        import unittest
        import pytest
        class TC(unittest.TestCase):
            def setUp(self):
                assert 0, "down1"
            def test_method(self):
                print("never42")
                xyz
    """
    )
    result = testdir.runpytest("-s")
    assert result.ret == 1
    result.stdout.fnmatch_lines(["*setUp*", "*assert 0*down1*", "*1 failed*"])
    result.stdout.no_fnmatch_line("*never42*") 
Example #19
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_method_and_teardown_failing_reporting(testdir):
    testdir.makepyfile(
        """
        import unittest
        class TC(unittest.TestCase):
            def tearDown(self):
                assert 0, "down1"
            def test_method(self):
                assert False, "down2"
    """
    )
    result = testdir.runpytest("-s")
    assert result.ret == 1
    result.stdout.fnmatch_lines(
        [
            "*tearDown*",
            "*assert 0*",
            "*test_method*",
            "*assert False*",
            "*1 failed*1 error*",
        ]
    ) 
Example #20
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_unittest_skip_issue148(testdir):
    testpath = testdir.makepyfile(
        """
        import unittest

        @unittest.skip("hello")
        class MyTestCase(unittest.TestCase):
            @classmethod
            def setUpClass(self):
                xxx
            def test_one(self):
                pass
            @classmethod
            def tearDownClass(self):
                xxx
    """
    )
    reprec = testdir.inline_run(testpath)
    reprec.assertoutcome(skipped=1) 
Example #21
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_teardown_issue1649(testdir):
    """
    Are TestCase objects cleaned up? Often unittest TestCase objects set
    attributes that are large and expensive during setUp.

    The TestCase will not be cleaned up if the test fails, because it
    would then exist in the stackframe.
    """
    testpath = testdir.makepyfile(
        """
        import unittest
        class TestCaseObjectsShouldBeCleanedUp(unittest.TestCase):
            def setUp(self):
                self.an_expensive_object = 1
            def test_demo(self):
                pass

    """
    )
    testdir.inline_run("-s", testpath)
    gc.collect()
    for obj in gc.get_objects():
        assert type(obj).__name__ != "TestCaseObjectsShouldBeCleanedUp" 
Example #22
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_function_item_obj_is_instance(testdir):
    """item.obj should be a bound method on unittest.TestCase function items (#5390)."""
    testdir.makeconftest(
        """
        def pytest_runtest_makereport(item, call):
            if call.when == 'call':
                class_ = item.parent.obj
                assert isinstance(item.obj.__self__, class_)
    """
    )
    testdir.makepyfile(
        """
        import unittest

        class Test(unittest.TestCase):
            def test_foo(self):
                pass
    """
    )
    result = testdir.runpytest_inprocess()
    result.stdout.fnmatch_lines(["* 1 passed in*"]) 
Example #23
Source File: test_unittest.py    From pytest with MIT License 6 votes vote down vote up
def test_setup(testdir):
    testpath = testdir.makepyfile(
        """
        import unittest
        class MyTestCase(unittest.TestCase):
            def setUp(self):
                self.foo = 1
            def setup_method(self, method):
                self.foo2 = 1
            def test_both(self):
                self.assertEqual(1, self.foo)
                assert self.foo2 == 1
            def teardown_method(self, method):
                assert 0, "42"

    """
    )
    reprec = testdir.inline_run("-s", testpath)
    assert reprec.matchreport("test_both", when="call").passed
    rep = reprec.matchreport("test_both", when="teardown")
    assert rep.failed and "42" in str(rep.longrepr) 
Example #24
Source File: test_twistd.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _patchTextFileLogObserver(patch):
    """
    Patch L{logger.textFileLogObserver} to record every call and keep a
    reference to the passed log file for tests.

    @param patch: a callback for patching (usually L{unittest.TestCase.patch}).

    @return: the list that keeps track of the log files.
    @rtype: C{list}
    """
    logFiles = []
    oldFileLogObserver = logger.textFileLogObserver

    def observer(logFile, *args, **kwargs):
        logFiles.append(logFile)
        return oldFileLogObserver(logFile, *args, **kwargs)

    patch(logger, 'textFileLogObserver', observer)
    return logFiles 
Example #25
Source File: test_unittest.py    From pytest with MIT License 5 votes vote down vote up
def test_new_instances(testdir):
    testpath = testdir.makepyfile(
        """
        import unittest
        class MyTestCase(unittest.TestCase):
            def test_func1(self):
                self.x = 2
            def test_func2(self):
                assert not hasattr(self, 'x')
    """
    )
    reprec = testdir.inline_run(testpath)
    reprec.assertoutcome(passed=2) 
Example #26
Source File: runner.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
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) 
Example #27
Source File: test_distreporter.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def setUp(self):
        self.stream = StringIO()
        self.distReporter = DistReporter(TreeReporter(self.stream))
        self.test = TestCase() 
Example #28
Source File: runner.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def loadClass(self, klass):
        """
        Given a class which contains test cases, return a list of L{TestCase}s.

        @param klass: The class to load tests from.
        """
        if not isinstance(klass, type):
            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) 
Example #29
Source File: runner.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
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)) 
Example #30
Source File: runner.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def loadAnything(self, thing, recurse=False, parent=None, qualName=None):
        """
        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.

        @param parent: For compatibility with the Python 3 loader, does
            nothing.
        @param qualname: For compatibility with the Python 3 loader, does
            nothing.

        @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,))