def _handle_ledger_closed(self, msg_json): self.fee.set_fee_scale(msg_json) p = Promise() p.fulfill(self.fee.calculate_fee()) self.fee_promise = p return True
def test_3_2_6_3_if_rejected(): """ Testing return of pending promises to make sure they are properly chained. This covers the case where the root promise is rejected before the chaining is defined. """ p1 = Promise() p1.reject("Error") pending = Promise() pending.fulfill(10) pr = p1.then(None, lambda r: pending) assert pending.isFulfilled() assert_equals(10, pending.value) assert pr.isFulfilled() assert_equals(10, pr.value) p2 = Promise() p2.reject("Error") bad = Promise() bad.reject("Assertion") pr = p2.then(None, lambda r: bad) assert bad.isRejected() assert_equals("Assertion", bad.reason) assert pr.isRejected() assert_equals("Assertion", pr.reason)
def _handle_server_status(self, msg_json): self.fee.set_load_scale(msg_json) p = Promise() p.fulfill(self.fee.calculate_fee()) self.fee_promise = p return True
def test_3_2_6_3_when_rejected(): """ Testing return of pending promises to make sure they are properly chained. This covers the case where the root promise is rejected after the chaining is defined. """ p1 = Promise() pending = Promise() pr = p1.then(None, lambda r: pending) assert pending.isPending assert pr.isPending p1.reject(Exception("Error")) pending.fulfill(10) assert pending.isFulfilled assert_equals(10, pending.value) assert pr.isFulfilled assert_equals(10, pr.value) p2 = Promise() bad = Promise() pr = p2.then(None, lambda r: bad) assert bad.isPending assert pr.isPending p2.reject(Exception("Error")) bad.reject(Exception("Assertion")) assert bad.isRejected assert_exception(bad.reason, Exception, "Assertion") assert pr.isRejected assert_exception(pr.reason, Exception, "Assertion")
def handle_request(self, request): request_indication = map_request_to_request_indication(request) #TODO: "check authorization of requestingEntity based on default access rights" p = Promise() if request_indication.method != "retrieve": return p.reject(SCLMethodNotAllowed(request_indication.method)) path = urlparse(request_indication.path).path channel_id = path[len(PREFIX) + 1:] try: notification, content_type = self.queues[channel_id].popleft() except KeyError: self.logger.info("Polling on unknown channel: %s", channel_id) return p.reject(SCLNotFound(path)) except IndexError: #TODO: handle timeouts self.waiting[channel_id].append(p) else: response_confirmation = RetrieveResponseConfirmation( notification, content_type) response = map_response_confirmation_to_response( request, response_confirmation) p.fulfill(response) self.logger.debug("Returning channel promise: %s", p.isPending()) return p
def test_then_all(): p = Promise() handlers = [ ((lambda x: x * x), (lambda r: 1)), {'success': (lambda x: x + x), 'failure': (lambda r: 2)}, ] results = p.then_all() + p.then_all(((lambda x: x * x), (lambda r: 1))) + p.then_all(handlers) p.fulfill(4) assert_equals(results[0].value, 16) assert_equals(results[1].value, 16) assert_equals(results[2].value, 8) p = Promise() handlers = [ ((lambda x: x * x), (lambda r: 1)), {'success': (lambda x: x + x), 'failure': (lambda r: 2)}, ] results = p.then_all() + p.then_all(((lambda x: x * x), (lambda r: 1))) + p.then_all(handlers) p.reject(Exception()) assert_equals(results[0].value, 1) assert_equals(results[1].value, 1) assert_equals(results[2].value, 2)
def test_3_2_6_3_if_rejected(): """ Testing return of pending promises to make sure they are properly chained. This covers the case where the root promise is rejected before the chaining is defined. """ p1 = Promise() p1.reject(Exception("Error")) pending = Promise() pending.fulfill(10) pr = p1.then(None, lambda r: pending) assert pending.isFulfilled assert_equals(10, pending.value) assert pr.isFulfilled assert_equals(10, pr.value) p2 = Promise() p2.reject(Exception("Error")) bad = Promise() bad.reject(Exception("Assertion")) pr = p2.then(None, lambda r: bad) assert bad.isRejected assert_exception(bad.reason, Exception, "Assertion") assert pr.isRejected assert_exception(pr.reason, Exception, "Assertion")
def testNonFunction(nonFunction): def foo(k, r): results[k] = r p1 = Promise() p2 = p1.then(lambda r: foo(str(nonFunction), r), nonFunction) p1.fulfill("Error: " + str(nonFunction))
def test_done_all(): counter = [0] def inc(_): counter[0] += 1 def dec(_): counter[0] -= 1 p = Promise() p.done_all() p.done_all((inc, dec)) p.done_all([ (inc, dec), (inc, dec), {'success': inc, 'failure': dec}, ]) p.fulfill(4) assert_equals(counter[0], 4) p = Promise() p.done_all() p.done_all((inc, dec)) p.done_all([ (inc, dec), {'success': inc, 'failure': dec}, ]) p.reject(Exception()) assert_equals(counter[0], 1)
def test_dict_promise_when(): p1 = Promise() p2 = Promise() d = {"a": p1, "b": p2} pd1 = dictPromise(d) pd2 = dictPromise({"a": p1}) pd3 = dictPromise({}) assert p1.isPending assert p2.isPending assert pd1.isPending assert pd2.isPending assert pd3.isFulfilled p1.fulfill(5) assert p1.isFulfilled assert p2.isPending assert pd1.isPending assert pd2.isFulfilled p2.fulfill(10) assert p1.isFulfilled assert p2.isFulfilled assert pd1.isFulfilled assert pd2.isFulfilled assert_equals(5, p1.value) assert_equals(10, p2.value) assert_equals(5, pd1.value["a"]) assert_equals(5, pd2.value["a"]) assert_equals(10, pd1.value["b"]) assert_equals({}, pd3.value)
def test_list_promise_if(): p1 = Promise() p2 = Promise() pd1 = listPromise([p1, p2]) pd2 = listPromise([p1]) pd3 = listPromise([]) assert p1.isPending assert p2.isPending assert pd1.isPending assert pd2.isPending assert pd3.isFulfilled p1.fulfill(5) assert p1.isFulfilled assert p2.isPending assert pd1.isPending assert pd2.isFulfilled p2.fulfill(10) assert p1.isFulfilled assert p2.isFulfilled assert pd1.isFulfilled assert pd2.isFulfilled assert_equals(5, p1.value) assert_equals(10, p2.value) assert_equals(5, pd1.value[0]) assert_equals(5, pd2.value[0]) assert_equals(10, pd1.value[1]) assert_equals([], pd3.value)
def async_all(promises, fulfill_with_none=False): p = Promise() num = len(promises) if num == 0: if fulfill_with_none: p.fulfill(None) else: p.fulfill([]) else: results = [] def _done(result): if not p.isRejected(): results.append(result) if len(results) == num: if fulfill_with_none: #logger.debug("Fulfilling with None") p.fulfill(None) else: #logger.debug("Fulfilling with %s", results) p.fulfill(results) def _error(error): if p.isPending(): p.reject(error) for promise in promises: promise.then(_done, _error) return p
def _wait_for_same_resource(self, path): p = Promise() try: self._pending_operations[path].append(p) except KeyError: self._pending_operations[path] = [p] p.fulfill(path) return p
def process_connectivity_request(self, req_category, requested_ssid=None): self.logger.info( "processing connectivity request with request category " + str(req_category)) p = Promise() if requested_ssid: ssid = requested_ssid else: #get the AN info for which the req_category can be served ssid = self.wifi_manager.get_ssid_for_req_category(req_category) self.logger.info("found suitable network with ssid %s", ssid) if ssid is not None: self.logger.info( "found suitable network with ssid %s, current ssid %s", ssid, self.wifi_manager.current_ssid) def conn_callback(dict_reply): if dict_reply is None: self.logger.info("invalid conn_callback dict_reply") #p.reject() self.logger.info( "connectivity callback for trying to connect on " + ssid + " has status " + dict_reply["status"]) if dict_reply["ssid"].startswith('"'): # Unquote dict_reply["ssid"] = dict_reply["ssid"][1:-1] if dict_reply["status"] != "CONNECTED" or dict_reply[ "ssid"] != ssid: self.logger.info( "status is not CONNECTED or current ssid not %s rejecting... (%s instead)" % (ssid, dict_reply["ssid"])) #p.reject() else: channel_tuple = (ssid, req_category) self.logger.debug( "Handover is done, fulfilling with ssid %s" % ssid) p.fulfill(channel_tuple) self.wifi_manager.removeConnectionAlert(conn_callback) if ssid == self.wifi_manager.current_ssid: self.logger.info( "no need to handover, the current ssid is good enough") channel_tuple = (ssid, req_category) p.fulfill(channel_tuple) else: self.wifi_manager.addConnectionAlert(conn_callback) self.wifi_manager.connectToNetwork(ssid, conn_callback) self.logger.info("trying to connect on network with ssid %s", ssid) else: p.reject("no WiFi for request category " + req_category + " available") return p
def test_3_2_1(): """ Test that the arguments to 'then' are optional. """ p1 = Promise() p2 = p1.then() p3 = Promise() p4 = p3.then() p1.fulfill(5) p3.reject("How dare you!")
def test_3_2_1(): """ Test that the arguments to 'then' are optional. """ p1 = Promise() p2 = p1.then() p3 = Promise() p4 = p3.then() p1.fulfill(5) p3.reject(Exception("How dare you!"))
def test_3_2_6_4_fulfilled(): """ Handles the case where the arguments to then are values, not functions or promises. """ p1 = Promise() p1.fulfill(10) p2 = p1.then(5) assert_equals(10, p1.value) assert p2.isFulfilled() assert_equals(10, p2.value)
def test_exceptions(): def throws(v): assert False p1 = Promise() p1.addCallback(throws) p1.fulfill(5) p2 = Promise() p2.addErrback(throws) p2.reject("Error")
def test_3_2_6_4_fulfilled(): """ Handles the case where the arguments to then are values, not functions or promises. """ p1 = Promise() p1.fulfill(10) p2 = p1.then(5) assert_equals(10, p1.value) assert p2.isFulfilled assert_equals(10, p2.value)
def test_3_2_6_1_literally(): """ If _either_ onFulfilled or onRejected returns a value that is not a promise, promise2 must be fulfilled with that value """ def _raise(e): raise e p1 = Promise() pf = p1.then(lambda v : _raise(Exception("Error")), lambda x : "catched") p1.fulfill(5) assert_equals(pf.value, "catched")
def test_3_2_3_3(): """ Make sure rejected callback never called if promise is fulfilled """ cf = Counter() cr = Counter() p1 = Promise() p2 = p1.then(lambda v: cf.tick(), lambda r: cr.tick()) p1.fulfill(5) assert_equals(0, cr.value()) assert_equals(1, cf.value())
def test_exceptions(): def throws(v): assert False p1 = Promise() p1.addCallback(throws) p1.fulfill(5) p2 = Promise() p2.addErrback(throws) p2.reject(Exception()) assert_raises(Exception, p2.get)
def test_list_promise_if(): p1 = Promise() p1.fulfill(5) p2 = Promise() p2.fulfill(10) pl = listPromise(p1, p2) assert p1.isFulfilled() assert p2.isFulfilled() assert pl.isFulfilled() assert_equals(5, p1.value) assert_equals(10, p2.value) assert_equals(5, pl.value[0]) assert_equals(10, pl.value[1])
def test_3_2_2_1(): """ The first argument to 'then' must be called when a promise is fulfilled. """ c = Counter() def check(v, c): assert_equals(v, 5) c.tick() p1 = Promise() p2 = p1.then(lambda v: check(v, c)) p1.fulfill(5) assert_equals(1, c.value())
def test_3_2_6_1(): """ Promises returned by then must be fulfilled when the promise they are chained from is fulfilled IF the fulfillment value is not a promise. """ p1 = Promise() pf = p1.then(lambda v: v * v) p1.fulfill(5) assert_equals(pf.value, 25) p2 = Promise() pr = p2.then(None, lambda r: 5) p2.reject(Exception("Error")) assert_equals(5, pr.value)
def test_3_2_6_1(): """ Promises returned by then must be fulfilled when the promise they are chained from is fulfilled IF the fulfillment value is not a promise. """ p1 = Promise() pf = p1.then(lambda v: v*v) p1.fulfill(5) assert_equals(pf.value, 25) p2 = Promise() pr = p2.then(None, lambda r: 5) p2.reject("Error") assert_equals(5, pr.value)
def test_3_2_5_1_if(): """ Then can be called multiple times on the same promise and callbacks must be called in the order of the then calls. """ def add(l, v): l.append(v) p1 = Promise() p1.fulfill(2) order = [] p2 = p1.then(lambda v: add(order, "p2")) p3 = p1.then(lambda v: add(order, "p3")) assert_equals(2, len(order)) assert_equals("p2", order[0]) assert_equals("p3", order[1])
def test_3_2_2_2(): """ Make sure callbacks are never called more than once. """ c = Counter() p1 = Promise() p2 = p1.then(lambda v: c.tick()) p1.fulfill(5) try: # I throw an exception p1.fulfill(5) assert False # Should not get here! except AssertionError: # This is expected pass assert_equals(1, c.value())
def handle_items(items): if not items: p = Promise() return p.fulfill(None) promises = [] for path, pocs in items: promises.append(self._do_handle_pocs(path, pocs, shelve)) return async_all(promises, fulfill_with_none=True)
def test_3_2_6_2_if(): """ Promises returned by then must be rejected when any of their callbacks throw an exception. """ def fail(v): raise AssertionError("Exception Message") p1 = Promise() p1.fulfill(5) pf = p1.then(fail) assert pf.isRejected() assert_equals("Exception Message", pf.reason) p2 = Promise() p2.reject("Error") pr = p2.then(None, fail) assert pr.isRejected() assert_equals("Exception Message", pr.reason)
def test_list_promise_when(): p1 = Promise() p2 = Promise() pl = listPromise(p1, p2) assert p1.isPending assert p2.isPending assert pl.isPending p1.fulfill(5) assert p1.isFulfilled assert p2.isPending assert pl.isPending p2.fulfill(10) assert p1.isFulfilled assert p2.isFulfilled assert pl.isFulfilled assert_equals(5, p1.value) assert_equals(10, p2.value) assert_equals(5, pl.value[0]) assert_equals(10, pl.value[1])
def test_dict_promise_if(): p1 = Promise() p2 = Promise() d = {"a": p1, "b": p2} pd = dictPromise(d) assert p1.isPending assert p2.isPending assert pd.isPending p1.fulfill(5) assert p1.isFulfilled assert p2.isPending assert pd.isPending p2.fulfill(10) assert p1.isFulfilled assert p2.isFulfilled assert pd.isFulfilled assert_equals(5, p1.value) assert_equals(10, p2.value) assert_equals(5, pd.value["a"]) assert_equals(10, pd.value["b"])
def test_dict_promise_if(): p1 = Promise() p2 = Promise() d = {"a": p1, "b": p2} pd = dictPromise(d) assert p1.isPending() assert p2.isPending() assert pd.isPending() p1.fulfill(5) assert p1.isFulfilled() assert p2.isPending() assert pd.isPending() p2.fulfill(10) assert p1.isFulfilled() assert p2.isFulfilled() assert pd.isFulfilled() assert_equals(5, p1.value) assert_equals(10, p2.value) assert_equals(5, pd.value["a"]) assert_equals(10, pd.value["b"])
def _do_handle_pocs(self, scl_path, scl_info, shelve): """ :param scl_path: str :param scl_info: dict of [str, str] :param shelve: Shelve :return: Promise """ self.logger.debug("_do_handle_pocs: %s", scl_path) p = Promise() return p.fulfill(True)
def test_3_2_6_2_if(): """ Promises returned by then must be rejected when any of their callbacks throw an exception. """ def fail(v): raise AssertionError("Exception Message") p1 = Promise() p1.fulfill(5) pf = p1.then(fail) assert pf.isRejected assert_exception(pf.reason, AssertionError, "Exception Message") p2 = Promise() p2.reject(Exception("Error")) pr = p2.then(None, fail) assert pr.isRejected assert_exception(pr.reason, AssertionError, "Exception Message")
def test_done(): counter = [0] def inc(_): counter[0] += 1 def dec(_): counter[0] -= 1 p = Promise() p.done(inc, dec) p.fulfill(4) assert_equals(counter[0], 1) p = Promise() p.done(inc, dec) p.done(inc, dec) p.reject(Exception()) assert_equals(counter[0], -1)
def _send_delete(self, request_indication): try: promise = Promise() p = self.client.send_delete(self.path) p.then(promise.fulfill(DeleteResponseConfirmation())) return promise except: with Promise() as p: p.fulfill( ErrorResponseConfirmation( 500, "delete", "Error while sending request").__dict__) return p
def test_3_2_6_3_when_fulfilled(): """ Testing return of pending promises to make sure they are properly chained. This covers the case where the root promise is fulfilled after the chaining is defined. """ p1 = Promise() pending = Promise() pf = p1.then(lambda r: pending) assert pending.isPending assert pf.isPending p1.fulfill(10) pending.fulfill(5) assert pending.isFulfilled assert_equals(5, pending.value) assert pf.isFulfilled assert_equals(5, pf.value) p2 = Promise() bad = Promise() pr = p2.then(lambda r: bad) assert bad.isPending assert pr.isPending p2.fulfill(10) bad.reject(Exception("Error")) assert bad.isRejected assert_exception(bad.reason, Exception, "Error") assert pr.isRejected assert_exception(pr.reason, Exception, "Error")
def test_3_2_6_3_when_fulfilled(): """ Testing return of pending promises to make sure they are properly chained. This covers the case where the root promise is fulfilled after the chaining is defined. """ p1 = Promise() pending = Promise() pf = p1.then(lambda r: pending) assert pending.isPending() assert pf.isPending() p1.fulfill(10) pending.fulfill(5) assert pending.isFulfilled() assert_equals(5, pending.value) assert pf.isFulfilled() assert_equals(5, pf.value) p2 = Promise() bad = Promise() pr = p2.then(lambda r: bad) assert bad.isPending() assert pr.isPending() p2.fulfill(10) bad.reject("Error") assert bad.isRejected() assert_equals("Error", bad.reason) assert pr.isRejected() assert_equals("Error", pr.reason)
def transaction_fields_completed_promise(tx_json): p = Promise() if 'Flags' in tx_json: tx_json['Flags'] |= tfFullyCanonicalSig else: tx_json['Flags'] = 0 tx_json['Fee'] = stellar.get_fee() if 'Sequence' in tx_json: p.fulfill(tx_json) else: def inner(res): tx_json['Sequence'] = res['Sequence'] p.fulfill(tx_json) p = stellar.get_account_info_promise(tx_json['Account']) p.then(inner) return p
def _do_update_scl(self, scl_path, scl, shelve): """ :param scl_path: str :param scl :param shelve: GEventSQLShelve :return: Promise """ p = Promise() if shelve is not None: shelve.setitem(scl_path, scl) return p.fulfill(shelve) return p.reject(None)
def _update_online_status(self, status): """ Checks if any known poc is listed as onlineStatus """ self.logger.debug("_update_online_status: status: %s %s ", status, type(status)) promise = Promise() if status.statusCode == STATUS_OK: return promise.fulfill(status) else: return promise.reject(status)
def test_fake_promise(): p = Promise() p.fulfill(FakePromise()) assert p.isRejected assert_exception(p.reason, Exception, "FakePromise raises in 'then'")
def test_wait_if(): p1 = Promise() p1.fulfill(5) p1.wait() assert p1.isFulfilled()
def test_get_if(): p1 = Promise() p1.fulfill(5) v = p1.get() assert p1.isFulfilled() assert_equals(5, v)