def setUp(self): def on_resolve(*args, **kwargs): self.resolve_ran = True self.assertEqual(args, ['resolve']) self.assertEqual(kwargs, {'finish_type': 'resolve'}) return 'ran_resolved' def on_error(*args, **kwargs): self.error_ran = True self.assertEqual(args, ['error']) self.assertEqual(kwargs, {'finish_type': 'error'}) return 'ran_error' def on_always(*args, **kwargs): self.always_ran = True self.assertEqual(len(args), 1) self.assertIn(args[0], ('resolve', 'error')) self.assertEqual(len(kwargs), 1) self.assertIn(kwargs['finish_type'], ('resolve', 'error')) return 'ran_always' def on_after(*args, **kwargs): self.after_ran = True self.assertEqual(len(args), 1) self.assertEqual(len(kwargs), 0) self.assertIn(args[0], ('ran_resolved', 'ran_error')) self.d = Deferred() self.d\ .then(on_resolve, error=on_error, always=on_always)\ .then(on_after) self.resolve_ran = False self.error_ran = False self.always_ran = False self.after_ran = False
def test_when(self): result = [] def on_done(value): result.append(value) def on_all(*args): result.extend(args) return(sum(args)) d1 = Deferred() d2 = Deferred() d3 = When(d1, d2) d1.then(on_done) d2.then(on_done) d3.then(on_all)\ .then(on_done) self.assertEqual(result, []) d2.resolve(2) self.assertEqual(result, [2]) d1.resolve(1) self.assertEqual(result, [2, 1, 2, 3, 1])
class TestDeferred(unittest.TestCase): def setUp(self): def on_resolve(*args, **kwargs): self.resolve_ran = True self.assertEqual(args, ['resolve']) self.assertEqual(kwargs, {'finish_type': 'resolve'}) return 'ran_resolved' def on_error(*args, **kwargs): self.error_ran = True self.assertEqual(args, ['error']) self.assertEqual(kwargs, {'finish_type': 'error'}) return 'ran_error' def on_always(*args, **kwargs): self.always_ran = True self.assertEqual(len(args), 1) self.assertIn(args[0], ('resolve', 'error')) self.assertEqual(len(kwargs), 1) self.assertIn(kwargs['finish_type'], ('resolve', 'error')) return 'ran_always' def on_after(*args, **kwargs): self.after_ran = True self.assertEqual(len(args), 1) self.assertEqual(len(kwargs), 0) self.assertIn(args[0], ('ran_resolved', 'ran_error')) self.d = Deferred() self.d\ .then(on_resolve, error=on_error, always=on_always)\ .then(on_after) self.resolve_ran = False self.error_ran = False self.always_ran = False self.after_ran = False def test_create(self): self.assertIsNotNone(self.d) def test_resolve(self): self.d.resolve('resolve', finish_type='resolve') self.assertTrue(self.d.finished) self.assertTrue(self.d.is_resolved) self.assertTrue(self.resolve_ran) self.assertFalse(self.error_ran) self.assertTrue(self.always_ran) self.assertTrue(self.after_ran) def test_error(self): self.d.reject('error', finish_type='error') self.assertTrue(self.d.finished) self.assertFalse(self.d.is_resolved) self.assertFalse(self.resolve_ran) self.assertTrue(self.error_ran) self.assertTrue(self.always_ran) self.assertTrue(self.after_ran)
class AsyncObject(object): def __init__(self): self.d = Deferred() def start(self): return self.d def close(self, value): self.d.resolve(value)
def enter_sequence(name): d = Deferred() sequence = sequences.get(name, collections.deque()) id = uuid.uuid4().hex sequence.append({'id': id, 'deferred': d}) sequences[name] = sequence if len(sequence) == 1: d.callback(id) return d
def testHandledTerminalAsyncFailure(self): """ Just like testHandledTerminalFailure, only with a Deferred which fires asynchronously with an error. """ d = Deferred() deferredGeneratorResultDeferred = self._genHandledTerminalAsyncFailure(d) d.errback(TerminalException("Handled Terminal Failure")) return deferredGeneratorResultDeferred.addCallback( self.assertEqual, None)
def testHandledTerminalAsyncFailure(self): """ Just like testHandledTerminalFailure, only with a Deferred which fires asynchronously with an error. """ d = Deferred() deferredGeneratorResultDeferred = self._genHandledTerminalAsyncFailure( d) d.errback(TerminalException("Handled Terminal Failure")) return deferredGeneratorResultDeferred.addCallback( self.assertEqual, None)
def __init__(self, req): """ Create a L{Response} from a brython ajax L{Request}. """ self._request = req self.code = getattr(req, "status", 0) self._contentDeferred = Deferred() def callContent(xmlHttpEvent): self._contentDeferred.callback(xmlHttpEvent.text) req.bind("complete", callContent)
def first_of(*a): df = Deferred() df.called = False for i, d in enumerate(a): def cb(result, i=i): if isinstance(result, Exception): raise result if not df.called: df.called = True df.callback((i, result)) d.add_callback(cb) x, r = yield df yield [(True, r) if x == i else None for i in xrange(len(a))]
def __init__(self, suiteID, caseIterator, result): SuiteRun.counter += 1 self.instanceNumber = SuiteRun.counter self.suiteID = suiteID self.caseIterator = caseIterator self.result = result self.finished = Deferred()
def get(url, headers=None): """ Fetch a URL and return a Deferred firing with a L{Response}. @param url: The URL to get. """ result = Deferred() if headers is None: headers = {} req = Request() def fireIfNotFired(event): "Things have either started or completed; fire." if not result.called: result.callback(Response(req)) # the "interactive" handler is where the deliverBody stuff would go req.bind("interactive", fireIfNotFired) def completeHandler(result): fireIfNotFired(result) req.bind("complete", completeHandler) req.open("GET", url, True) req.send() return result
def getOwie(): from twisted.internet import reactor d = Deferred() def CRAP(): d.errback(ZeroDivisionError('OMG')) reactor.callLater(0, CRAP) return d
class Response(object): """ An HTTP response. """ # TODO: version version = ('HTTP', 1, 1) # TODO: content (raw bytes) # TODO: phrase # TODO: headers (and Headers class) # TODO: request attribute (and IClientRequest class) # TODO: previousResponse (is this even possible?) previousResponse = None # TODO: setPreviousResponse # TODO: deliverBody def __init__(self, req): """ Create a L{Response} from a brython ajax L{Request}. """ self._request = req self.code = getattr(req, "status", 0) self._contentDeferred = Deferred() def callContent(xmlHttpEvent): self._contentDeferred.callback(xmlHttpEvent.text) req.bind("complete", callContent) def text(self): """ Get the text associated with this response. """ return self._contentDeferred def json(self): """ Get the JSON object associated with this response. """ return self._contentDeferred.addCallback(loads)
def test_plus(self): result = [] def get_value(): return 42 def got_value(value): self.assertEqual(value, 42) return value * 2 def got_value2(value): self.assertEqual(value, 84) result.append(value) d = Deferred() d.then(get_value)\ .then(got_value)\ .then(got_value2) self.assertEqual(result, []) d.resolve() self.assertEqual(result, [84])
def test_slowly(self): """ This test should wait for 5 seconds for its Deferred to fire, then pass. """ from browser import window d = Deferred() print("one") def later(): d.callback(None) print("two") window.setTimeout(later, 5000) print("three") return d
def getThing(): from twisted.internet import reactor d = Deferred() reactor.callLater(0, d.callback, "hi") return d
def __init__(self): self.d = Deferred()
def test_when(self): result = [] def on_done(value): result.append(value) def on_all(*args): result.extend(args) return (sum(args)) d1 = Deferred() d2 = Deferred() d3 = When(d1, d2) d1.then(on_done) d2.then(on_done) d3.then(on_all)\ .then(on_done) self.assertEqual(result, []) d2.resolve(2) self.assertEqual(result, [2]) d1.resolve(1) self.assertEqual(result, [2, 1, 2, 3, 1])