示例#1
0
 def testExceptions(self):
     exc = self.assertRaises(ZeroDivisionError, lambda: 1/0)
     assert isinstance(exc, ZeroDivisionError), "ZeroDivisionError instance not returned"
     
     for func in [lambda: 1/0, lambda: None]:
         try:
             self.assertRaises(ValueError, func)
         except unittest.FailTest:
             # Success!
             pass
         except:
             raise unittest.FailTest("FailTest not raised", failure.Failure().getTraceback())
         else:
             raise unittest.FailTest("FailTest not raised")
示例#2
0
文件: test_ssh.py 项目: yuu6/twisted
 def connectionLost(self, reason):
     if self.done:
         return
     if not hasattr(self, 'expectedLoseConnection'):
         raise unittest.FailTest(
             'unexpectedly lost connection %s\n%s' % (self, reason))
     self.done = 1
示例#3
0
 def connectionLost(self, reason):
     if self.done:
         return
     if not hasattr(self, "expectedLoseConnection"):
         raise unittest.FailTest(
             "unexpectedly lost connection {}\n{}".format(self, reason))
     self.done = 1
示例#4
0
    def test_newStyleClassesOnly(self):
        """
        Test that C{self.module} has no old-style classes in it.
        """
        try:
            module = namedAny(self.module)
        except ImportError as e:
            raise unittest.SkipTest("Not importable: {}".format(e))

        oldStyleClasses = []

        for name, val in inspect.getmembers(module):
            if hasattr(val, "__module__") \
               and val.__module__ == self.module:
                if isinstance(val, types.ClassType):
                    oldStyleClasses.append(fullyQualifiedName(val))

        if oldStyleClasses:

            self.todo = "Not all classes are made new-style yet. See #8243."

            for x in forbiddenModules:
                if self.module.startswith(x):
                    delattr(self, "todo")

            raise unittest.FailTest(
                "Old-style classes in {module}: {val}".format(
                    module=self.module, val=", ".join(oldStyleClasses)))
示例#5
0
 def fetch_failed(self, *args, **kwargs):
     if self.check_fetch_failed:
         if self.finished_d:
             self.finished_d.errback(
                 unittest.FailTest(
                     "The node was told by the segment fetcher that the download failed."
                 ))
             self.finished_d = None
示例#6
0
 def test_create(self):
     """
     Test the creation of an epoll object.
     """
     try:
         p = _epoll.epoll(16)
     except OSError, e:
         raise unittest.FailTest(str(e))
 def got_shares(self, shares):
     if self.check_reneging:
         if self._no_more_shares:
             self.finished_d.errback(unittest.FailTest("The node was told by the share finder that it is destined to remain hungry, then was given another share."))
             return
     self.got += len(shares)
     log.msg("yyy 3 %s.got_shares(%s) got: %s" % (self, shares, self.got))
     if self.got == 3:
         self.finished_d.callback(True)
示例#8
0
def runOneDeferred(d):
    L = []
    d.addBoth(L.append)
    reactor.callLater(0, d.addCallback, lambda ign: reactor.crash())
    reactor.run()
    if L:
        if isinstance(L[0], failure.Failure):
            L[0].trap()
        return L[0]
    raise unittest.FailTest("Keyboard Interrupt")
示例#9
0
    def testRaises(self):
        self.failUnless(util.raises(ZeroDivisionError, divmod, 1, 0))
        self.failIf(util.raises(ZeroDivisionError, divmod, 0, 1))

        try:
            util.raises(TypeError, divmod, 1, 0)
        except ZeroDivisionError:
            pass
        else:
            raise unittest.FailTest("util.raises didn't raise when it should have")
 def test_actionAllowed_Defaults(self):
     "by default, nothing is allowed"
     z = Authz()
     failedActions = []
     for a in Authz.knownActions:
         if z.actionAllowed(a, StubRequest('foo', 'bar')):
             failedActions.append(a)
     if failedActions:
         raise unittest.FailTest("action(s) %s do not default to False" %
                                 (failedActions, ))
示例#11
0
 def addChange(**kwargs):
     # check for 8-bit strings
     for k, v in kwargs.items():
         if type(v) == type(""):
             try:
                 v.decode('ascii')
             except UnicodeDecodeError:
                 raise unittest.FailTest(
                     "non-ascii string for key '%s': %r" % (k, v))
     self.changes_added.append(kwargs)
     return defer.succeed(mock.Mock())
示例#12
0
    def verify_state(self, expected_state):
        if self.state_keeper.state != expected_state:
            state_diff = difflib.unified_diff(
                str(expected_state).splitlines(),
                str(self.state_keeper.state).splitlines(),
                fromfile="expected",
                tofile="actual",
                lineterm="",
                n=5)

            raise unittest.FailTest("State is incorrect\n" +
                                    "\n".join(state_diff))
示例#13
0
    def testMega(self):
        # trial should support this use case.
        failures = []
        for n, (start, finish, output, msg) in enumerate(self.testData):
            got = finish.toVT102(start)

            if got != output:
                failures.append((got, output, str(n) + ': ' + msg))

        if failures:
            failures.insert(0, ('received', 'expected', "what's up"))
            raise unittest.FailTest(pprint.pformat(failures))
示例#14
0
class SynchronizationTestCase(unittest.TestCase):
    if hasattr(sys, 'getcheckinterval'):
        def setUpClass(self):
            self.checkInterval = sys.getcheckinterval()
            sys.setcheckinterval(7)

        def tearDownClass(self):
            sys.setcheckinterval(self.checkInterval)


    def setUp(self):
        # XXX This is a trial hack.  We need to make sure the reactor
        # actually *starts* for isInIOThread() to have a meaningful result.
        # Returning a Deferred here should force that to happen, if it has
        # not happened already.  In the future, this should not be
        # necessary.
        d = defer.Deferred()
        reactor.callLater(0, d.callback, None)
        return d


    def testIsInIOThread(self):
        foreignResult = []
        t = threading.Thread(target=lambda: foreignResult.append(threadable.isInIOThread()))
        t.start()
        t.join()
        self.failIf(foreignResult[0], "Non-IO thread reported as IO thread")
        self.failUnless(threadable.isInIOThread(), "IO thread reported as not IO thread")


    def testThreadedSynchronization(self):
        o = TestObject()

        errors = []

        def callMethodLots():
            try:
                for i in xrange(1000):
                    o.aMethod()
            except AssertionError, e:
                errors.append(str(e))

        threads = []
        for x in range(5):
            t = threading.Thread(target=callMethodLots)
            threads.append(t)
            t.start()

        for t in threads:
            t.join()

        if errors:
            raise unittest.FailTest(errors)
示例#15
0
class SynchronizationTestCase(unittest.TestCase):
    def setUp(self):
        """
        Reduce the CPython check interval so that thread switches happen much
        more often, hopefully exercising more possible race conditions.  Also,
        delay actual test startup until the reactor has been started.
        """
        if hasattr(sys, 'getcheckinterval'):
            self.addCleanup(sys.setcheckinterval, sys.getcheckinterval())
            sys.setcheckinterval(7)
        # XXX This is a trial hack.  We need to make sure the reactor
        # actually *starts* for isInIOThread() to have a meaningful result.
        # Returning a Deferred here should force that to happen, if it has
        # not happened already.  In the future, this should not be
        # necessary.
        d = defer.Deferred()
        reactor.callLater(0, d.callback, None)
        return d


    def testIsInIOThread(self):
        foreignResult = []
        t = threading.Thread(target=lambda: foreignResult.append(threadable.isInIOThread()))
        t.start()
        t.join()
        self.failIf(foreignResult[0], "Non-IO thread reported as IO thread")
        self.failUnless(threadable.isInIOThread(), "IO thread reported as not IO thread")


    def testThreadedSynchronization(self):
        o = TestObject()

        errors = []

        def callMethodLots():
            try:
                for i in xrange(1000):
                    o.aMethod()
            except AssertionError, e:
                errors.append(str(e))

        threads = []
        for x in range(5):
            t = threading.Thread(target=callMethodLots)
            threads.append(t)
            t.start()

        for t in threads:
            t.join()

        if errors:
            raise unittest.FailTest(errors)
示例#16
0
 def step5_errback(self, why):
     bad = None
     if why.type != tokens.Violation:
         bad = "%s failure should be a Violation" % why.type
     elif why.value.args[0].find(
             "RemoteReferences can only be sent back to their home Broker"
     ) == -1:
         bad = "wrong error message: '%s'" % why.value.args[0]
     if bad:
         why = unittest.FailTest(bad)
         self.passed = failure.Failure(why)
     else:
         self.passed = True
示例#17
0
    def connectionLost(self, reason):
        if self.disconnect_d:

            if self.disconnect_timeout:
                self.disconnect_timeout.cancel()
                self.disconnect_timeout = None

            d = self.disconnect_d
            self.disconnect_d = None
            d.callback(None)

        elif self.fail_exit_d:
            d = self.fail_exit_d
            self.fail_exit_d = None

            d.errback(unittest.FailTest('Connection unexpectedly dropped'))
示例#18
0
 def testMethod(*args, **kwargs):
     """When this function is generated, a methodname (beginning
     with whatever **methodPrefix** was set to) will also be
     generated, and the (methodname, method) pair will be
     assigned as attributes of the generated
     :api:`~twisted.trial.unittest.TestCase`.
     """
     # Get the number of failures before test.run():
     origFails = len(cls.testResult.original.failures)
     test.run(cls.testResult)
     # Fail the generated testMethod if the underlying failure
     # count has increased:
     if (len(cls.testResult.original.failures) > origFails):
         fail = cls.testResult.original.failures[origFails:][0]
         raise unittest.FailTest(''.join([str(fail[0]),
                                          str(fail[1])]))
     return cls.testResult
示例#19
0
    def assertCommandOutput(self, command, output, observed=()):
        """
        Verify that when C{command} is executed by this
        L{CommandTestCaseMixin.playerWrapper}, C{output} is produced (to the
        actor) and C{observed} is produced (to the observer).

        @param command: The string for L{CommandTestCaseMixin.playerWrapper} to
            execute.
        @type command: L{str}

        @param output: The expected output of C{command} for
            L{CommandTestCaseMixin.player} to observe.
        @type output: iterable of L{str}

        @param observed: The expected output that
            L{CommandTestCaseMixin.observer} will observe.
        @type observed: iterable of L{str}
        """
        if command is not None:
            # Deprecate this or something
            if not isinstance(command, unicode):
                command = unicode(command, 'ascii')
            self.playerWrapper.parse(command)
            output.insert(0, "> " + command)

        results = []
        for perspective, xport, oput in ([
                ('actor' ,self.transport, output),
                ('observer', self.otransport, observed)]):
            results.append([])
            gotLines = xport.value().decode('utf-8').splitlines()
            for i, (got, expected) in enumerate(map(None, gotLines, oput)):
                got = got or ''
                expected = expected or '$^'
                m = compile(expected.rstrip() + '$').match(got.rstrip())
                if m is None:
                    s1 = pprint.pformat(gotLines)
                    s2 = pprint.pformat(oput)
                    raise unittest.FailTest(
                        "\n%s %s\ndid not match expected\n%s\n(Line %d)" % (
                            repr(perspective), s1, s2, i))
                results[-1].append(m)
            xport.clear()
        return results
示例#20
0
    def test_newStyleClassesOnly(self):
        """
        Test that C{self.module} has no old-style classes in it.
        """
        try:
            module = namedAny(self.module)
        except ImportError as e:
            raise unittest.SkipTest("Not importable: {}".format(e))

        oldStyleClasses = []

        for name, val in inspect.getmembers(module):
            if hasattr(val, "__module__") \
               and val.__module__ == self.module:
                if isinstance(val, types.ClassType):
                    oldStyleClasses.append(fullyQualifiedName(val))

        if oldStyleClasses:
            raise unittest.FailTest(
                "Old-style classes in {module}: {val}".format(
                    module=self.module, val=", ".join(oldStyleClasses)))
示例#21
0
 def failUnlessConnection(self,
                          spec,
                          dbapiName,
                          connargs=None,
                          connkw=None):
     errs = []
     if dbapiName is self.SQLITE_NAMES:
         if spec.dbapiName not in self.SQLITE_NAMES:
             errs.append("unexpected dbapiName %s" % spec.dbapiName)
     else:
         if spec.dbapiName != dbapiName:
             errs.append("unexpected dbapiName %s" % spec.dbapiName)
     if connargs is not None:
         if spec.connargs != connargs:
             errs.append("unexpected connargs: %s, expected %s" %
                         (spec.connargs, connargs))
     if connkw is not None:
         if spec.connkw != connkw:
             errs.append("unexpected connkw: %s, expected %s" %
                         (spec.connkw, connkw))
     if errs:
         raise unittest.FailTest("; ".join(errs))
示例#22
0
    def testThreadedSynchronization(self):
        o = TestObject()

        errors = []

        def callMethodLots():
            try:
                for i in range(1000):
                    o.aMethod()
            except AssertionError as e:
                errors.append(str(e))

        threads = []
        for x in range(5):
            t = threading.Thread(target=callMethodLots)
            threads.append(t)
            t.start()

        for t in threads:
            t.join()

        if errors:
            raise unittest.FailTest(errors)
示例#23
0
    def fuzzyMatch(self, first, second):
        "try to ignore bits randomly generated by our code"
        self.assertEqual(first.__class__, second.__class__)
        self.assertEqual(first.version, second.version)
        if isinstance(first, sip.Request):
            self.assertEqual(first.method, second.method)
            self.assertEqual(first.uri, second.uri)
        else:
            self.assertEqual(first.code, second.code)

        for header in first.headers.keys():
            if not second.headers.get(header):
                if not first.headers[header]:
                    #woops, it's empty, never mind
                    continue
                raise unittest.FailTest("%s not present in %s" % (header, second))
            if header in ('from', 'to', 'contact'):
                #strip tags
                if isinstance(first.headers[header][0], sip.URL):
                    firsturl = first.headers[header][0]
                else:
                    firsturl = sip.parseAddress(first.headers[header][0])[1]
                secondurl = sip.parseAddress(second.headers[header][0])[1]
                self.assertEqual(firsturl, secondurl)
            elif header == "via":
                firstvia = [sip.parseViaHeader(h)
                            for h in first.headers['via']]
                secondvia = [sip.parseViaHeader(h)
                            for h in second.headers['via']]
                #convert to strings for easy reading of output
                self.assertEqual([x.toString() for x in firstvia],
                                 [x.toString() for x in firstvia])
            elif header == "content-length":
                continue
            else:
                self.assertEqual([str(x) for x in first.headers[header]],
                                 [str(x) for x in second.headers[header]])
示例#24
0
 def test_connectionLost(self):
     d = self.gp.send(11, "test")
     d.addCallback(lambda x: unittest.FailTest())
     d.addErrback(lambda x: x.trap(ExpectedFailure))
     self.gp.connectionLost(ExpectedFailure())
     return d
示例#25
0
def mustRaise(dummy):
    raise unittest.FailTest("Should have raised an exception.")
示例#26
0
 def _cbRoundRobinBackoff(self, result):
     raise unittest.FailTest("Lookup address succeeded, should have timed out")
示例#27
0
 def ssh_USERAUTH_SUCCESS(self, packet):
     if not self.canSucceedPassword and self.canSucceedPublicKey:
         raise unittest.FailTest(
             "got USERAUTH_SUCCESS before password and publickey")
     userauth.SSHUserAuthClient.ssh_USERAUTH_SUCCESS(self, packet)
示例#28
0
 def receiveUnimplemented(self, seqID):
     raise unittest.FailTest(
         "got unimplemented: seqid {}".format(seqID))
示例#29
0
文件: detests.py 项目: DT021/wau
 def setUp(self):
     return defer.fail(unittest.FailTest('i fail'))
示例#30
0
        """
        for skt in self.connections:
            skt.close()

    def _connectedPair(self):
        """
        Return the two sockets which make up a new TCP connection.
        """
        client = socket.socket()
        client.setblocking(False)
        try:
            client.connect(('127.0.0.1', self.serverSocket.getsockname()[1]))
        except socket.error, e:
            self.assertEquals(e.args[0], errno.EINPROGRESS)
        else:
            raise unittest.FailTest("Connect should have raised EINPROGRESS")
        server, addr = self.serverSocket.accept()

        self.connections.extend((client, server))
        return client, server

    def test_create(self):
        """
        Test the creation of an epoll object.
        """
        try:
            p = _epoll.epoll(16)
        except OSError, e:
            raise unittest.FailTest(str(e))
        else:
            p.close()