Commits

Marcin Kasperski  committed 6ebcec7

testy z wb

  • Participants
  • Parent commits e58bfb6

Comments (0)

Files changed (2)

File tests/test_deferred_sync.py

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+######################################################################
+# (c) 2005, Marcin Kasperski
+######################################################################
+
+#import unittest
+from twisted.trial import unittest
+from twisted.internet import defer
+from twisted.internet import reactor
+
+class someTestCase(unittest.TestCase):
+
+    @defer.deferredGenerator
+    def setUp(self):
+        d = defer.Deferred()
+        reactor.callLater(0.1, d.callback, 0)
+        yield defer.waitForDeferred(d)
+
+    @defer.deferredGenerator
+    def testOne(self):
+        d = defer.Deferred()
+        reactor.callLater(0.2, d.callback, 0)
+        yield defer.waitForDeferred(d)
+
+    @defer.deferredGenerator
+    def testTwo(self):
+        d = defer.Deferred()
+        reactor.callLater(0, d.callback, 0)
+        yield defer.waitForDeferred(d)
+
+    @defer.deferredGenerator
+    def tearDown(self):
+        d = defer.Deferred()
+        reactor.callLater(0.01, d.callback, 0)
+        yield defer.waitForDeferred(d)
+

File tests/test_gather_defs.py

+# -*- coding: utf-8 -*-
+import logging
+import os
+
+from twisted.internet import defer
+from twisted.trial import unittest
+from mekk.watchbot.test_util.delay_defer import delay_succeed, delay_exception
+
+if os.environ.get('DEBUG_REACTOR'):
+    import twisted.internet.base
+    twisted.internet.base.DelayedCall.debug = True
+
+class SomeExc(Exception):
+    pass
+
+class DefDelayTestCase(unittest.TestCase):
+    """
+    Tests whether our test mechanique properly sync
+    """
+    @defer.inlineCallbacks
+    def testDelayOks(self):
+        x = yield delay_succeed("xyz")
+        self.failUnlessEqual(x, "xyz")
+
+    @defer.inlineCallbacks
+    def testMultipleOks(self):
+        x = yield delay_succeed("xyz")
+        self.failUnlessEqual(x, "xyz")
+        y = yield delay_succeed("abc")
+        self.failUnlessEqual(y, "abc")
+
+    @defer.inlineCallbacks
+    def testReorder(self):
+        x = delay_succeed("first", delay=0.2)
+        y = delay_succeed("second", delay=0.05)
+        r = yield defer.gatherResults([x, y])
+        self.failUnlessEqual(r, ["first", "second"])
+
+    @defer.inlineCallbacks
+    def testExcept(self):
+        try:
+            y = yield delay_exception(SomeExc())
+            self.fail("No exception")
+        except SomeExc:
+            pass
+
+    @defer.inlineCallbacks
+    def testOkAndExcept(self):
+        try:
+            x = yield delay_succeed("a")
+            self.failUnlessEqual(x, "a")
+            y = yield delay_exception(SomeExc())
+            self.fail("No exception")
+        except SomeExc:
+            pass
+
+    @defer.inlineCallbacks
+    def testTwoExcept(self):
+        try:
+            x = delay_exception(SomeExc(), delay=0.2)
+            y = delay_exception(SomeExc(), delay=0.05)
+            yield x
+            yield y
+            self.fail("No exception")
+        except SomeExc:
+            pass
+        self.failUnless(x.called)
+        self.failUnless(y.called)
+
+    @defer.inlineCallbacks
+    def testGatherExcept(self):
+        x = delay_succeed("beforee", delay=0.2)
+        y = delay_exception(SomeExc(),delay=0.05)
+        try:
+            r = yield defer.gatherResults([x,y])
+            self.fail("No exception")
+        except SomeExc:
+            pass
+        self.failUnless(x.called)
+
+    @defer.inlineCallbacks
+    def testGatherTwoExcept(self):
+        x = delay_exception(SomeExc(), delay=0.2)
+        y = delay_exception(SomeExc(),delay=0.05)
+        try:
+            r = yield defer.gatherResults([x,y])
+            self.fail("No exception")
+        except SomeExc:
+            pass
+        self.failUnless(x.called)
+        self.failUnless(y.called)
+
+    @defer.inlineCallbacks
+    def testProperlyGatherWithErr(self):
+        x = delay_exception(SomeExc(), delay=0.2)
+        y = delay_exception(SomeExc(),delay=0.05)
+        z = delay_succeed("AAAAA", delay=0.05)
+        try:
+            #r = yield defer.gatherResults([x,y,z], consumeErrors=True)
+            #print r
+            yield gather_safely([x,y,z])
+            self.fail("No exception")
+        except SomeExc:
+            pass
+        self.failUnless(x.called)
+        self.failUnless(y.called)
+        self.failUnless(z.called)
+
+    @defer.inlineCallbacks
+    def testProperlyGatherOK(self):
+        x = delay_succeed("XXX", delay=0.2)
+        y = delay_succeed("YYY",delay=0.05)
+        z = delay_succeed("ZZZ", delay=0.05)
+        rx, ry, rz = yield gather_safely([x,y,z])
+        self.failUnlessEqual(rx, "XXX")
+        self.failUnlessEqual(ry, "YYY")
+        self.failUnlessEqual(rz, "ZZZ")
+
+log = logging.getLogger("test")
+
+class CancellingDeferredList(defer.DeferredList):
+    """
+    Update to normal DeferredList: any failure causes all unfinished items
+    on the list to be cancelled. This way one can properly sync on all results
+    even if some won't be provided due to earlier errors.
+    """
+
+    def __init__(self, deferredList):
+        defer.DeferredList.__init__(
+            self, deferredList,
+            fireOnOneCallback=False, # of course
+            fireOnOneErrback=False,  # all will be finished or cancelled and we wait for all of them
+            consumeErrors=False,     # in case somebody wait's for individual reply, let him know
+            )
+        self._defList = deferredList
+
+    def _cbDeferred(self, result, index, succeeded):
+        result = defer.DeferredList._cbDeferred(self, result, index, succeeded)
+        if not succeeded:
+            for pos, dfr in enumerate(self._defList):
+                if pos != index and not dfr.called:
+                    dfr.cancel()
+        return result
+
+def gather_safely(deferred_list):
+    """
+    gatherResults with "sync all" guarantee.
+
+    Waits for or cancels all deferreds specified, raises first error after
+    cleanup
+    """
+    #df = defer.gatherResults(deferred_list, consumeErrors=True)
+    if not deferred_list:
+        return defer.succeed([])
+
+    d_list = CancellingDeferredList(deferred_list)
+#    def process_correct(result_list):
+#        # lista status,wynik.
+#        # Chyba status zawsze true skoro daliśmy fireOnOneErrback
+#        assert all(status for status, _ in result_list)
+#        #return [result for _, result in result_list]
+#        result_def.callback([result for _, result in result_list])
+#    def process_failed(failure):
+#        error = failure.value
+#        assert isinstance(error, defer.FirstError)
+#        index = error.index
+#        #true_exc = error.subFailure.value
+#        for pos, dfr in enumerate(deferred_list):
+#            if pos != index:
+#                dfr.cancel()
+#        # Tu trzeba poczekać na ten cancel
+#        error.subFailure.raiseException()
+#        #log.warn( "BAD: %s, index: %d, true_failurre: %s",
+#        #          failure, error.index, error.subFailure)
+#
+#    defr_list.addCallback(process_correct)
+#    defr_list.addErrback(process_failed)
+
+    def parse_results(lst):
+        #for success, value in l:
+        #    assert success
+        return [x[1] for x in lst]
+
+    d_list.addCallback(parse_results)
+
+    return d_list