Esempio n. 1
0
    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
Esempio n. 2
0
    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])
Esempio n. 3
0
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)
Esempio n. 4
0
class AsyncObject(object):
    def __init__(self):
        self.d = Deferred()

    def start(self):
        return self.d

    def close(self, value):
        self.d.resolve(value)
Esempio n. 5
0
class AsyncObject(object):
    def __init__(self):
        self.d = Deferred()

    def start(self):
        return self.d

    def close(self, value):
        self.d.resolve(value)
Esempio n. 6
0
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)
Esempio n. 7
0
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
Esempio n. 8
0
 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)
Esempio n. 9
0
 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)
Esempio n. 10
0
    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)
Esempio n. 11
0
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))]
Esempio n. 12
0
 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()
Esempio n. 13
0
    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
Esempio n. 14
0
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
Esempio n. 15
0
def getOwie():
    from twisted.internet import reactor
    d = Deferred()

    def CRAP():
        d.errback(ZeroDivisionError('OMG'))

    reactor.callLater(0, CRAP)
    return d
Esempio n. 16
0
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)
Esempio n. 17
0
    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])
Esempio n. 18
0
 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
Esempio n. 19
0
    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])
Esempio n. 20
0
def getThing():
    from twisted.internet import reactor
    d = Deferred()
    reactor.callLater(0, d.callback, "hi")
    return d
Esempio n. 21
0
 def __init__(self):
     self.d = Deferred()
Esempio n. 22
0
    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])
Esempio n. 23
0
 def __init__(self):
     self.d = Deferred()