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 _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 testNonFunction(nonFunction): def foo(k, r): results[k] = r p1 = Promise() p2 = p1.then(nonFunction, lambda r: foo(str(nonFunction), r)) p1.reject(Exception("Error: " + str(nonFunction)))
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 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 _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 test_3_2_6_5_rejected(): """ Handles the case where the arguments to then are values, not functions or promises. """ p1 = Promise() p1.reject(Exception("Error")) p2 = p1.then(None, 5) assert_exception(p1.reason, Exception, "Error") assert p2.isRejected assert_exception(p2.reason, Exception, "Error")
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_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 _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_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_5_rejected(): """ Handles the case where the arguments to then are values, not functions or promises. """ p1 = Promise() p1.reject("Error") p2 = p1.then(None, 5) assert_equals("Error", p1.reason) assert p2.isRejected() assert_equals("Error", p2.reason)
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_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_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 _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 _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 _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 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_3_2_3_1(): """ The second argument to 'then' must be called when a promise is rejected. """ c = Counter() def check(r, c): assert_equals(r, "Error") c.tick() p1 = Promise() p2 = p1.then(None, lambda r: check(r, c)) p1.reject("Error") assert_equals(1, c.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 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 stop(self): p = Promise() if not self.started: p.reject(OpenMTCError("Plugin %s was not started")) else: self.__promise = p try: self._stop() except BaseException as e: self.logger.exception("Failed to stop plugin") self._error(e) return p
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 send_request_indication(self, request_indication): self.logger.debug("send_request_indication: %s", request_indication) p = Promise() path = urlparse(request_indication.path).path[1:] self.logger.debug("target sessid (path): %s", path) target = namespace_data.global_namespaces.get(path, None) def callback_handler(result): self.logger.debug("got client response \'%s\' to request \'%s\'", result, request_indication) try: response = util.unmarshal_response(result) p.fulfill(response) except Exception as e: self.logger.warn( "can't unmarshall response \'%s\', error: \'%s\'", result, e) p.fulfill(result) target.emit("request", util.marshal_request_indication(request_indication), callback=callback_handler) return p
def send_request_indication(self, request_indication): # TODO: rewrite HTTP request handling totally with Promise() as p: fullpath = request_indication.path parsed = urlparse(fullpath) request_indication = copy(request_indication) request_indication.path = urlunparse( ParseResult("", "", *parsed[2:])) try: client = XIXClient( parsed.scheme + "://" + parsed.netloc, scl_base=None, etsi_v1_compatibility=self.etsi_compatibility_needed, etsi_v2=self.etsi_version_v2) response = client.send_request_indication(request_indication) except OpenMTCNetworkError as e: response = ErrorResponseConfirmation(STATUS_BAD_GATEWAY, request_indication.method, str(e)) p.reject(response) except SCLError as e: response = ErrorResponseConfirmation(e.statusCode, request_indication.method, str(e)) p.reject(response) else: #response = self._convert_response(fullpath, request_indication, response) if request_indication.method == "retrieve" and hasattr( response.resource, "path"): response.resource.path = fullpath p.fulfill(response) return p
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_3_1(): """ The second argument to 'then' must be called when a promise is rejected. """ c = Counter() def check(r, c): assert_exception(r, Exception, "Error") c.tick() p1 = Promise() p2 = p1.then(None, lambda r: check(r, c)) p1.reject(Exception("Error")) assert_equals(1, c.value())
def send(self, message, remote): """ Send a message to a remote address. :param message: message to be sent :type message: Message :param remote: remote address (host, port) :type remote: tuple :return: promise for request :rtype: Promise """ p = Promise() tx_record = TransmissionRecord(self, message, remote) self.unanswered[tx_record.transaction_id] = p self.timings[p] = time.time() def timeoutfunc(): errormsg = Message(Message.CON, constants.GATEWAY_TIMEOUT, payload="No response") del (self.unanswered[tx_record.transaction_id]) del (self.timings[p]) del (self.timers[p]) p.reject(errormsg) # automatically reject promise after given time timer = Timer(self.timeout, timeoutfunc) timer.start() self.timers[p] = timer start_new_thread(self._send, (tx_record,)) return p
def send_onem2m_request(self, onem2m_request): with Promise() as p: http_request = self.map_onem2m_request_to_http_request( onem2m_request) t = time() client = self._get_client() try: response = client.request(**http_request) except (socket_error, gaierror) as exc: self._handle_network_error(exc, p, http_request, t, ConnectionFailed) except Exception as exc: self.logger.exception("Error in HTTP request") self._handle_network_error(exc, p, http_request, t) else: try: onem2m_response = self.map_http_response_to_onem2m_response( onem2m_request, response) if isinstance(onem2m_response, OneM2MErrorResponse): p.reject(onem2m_response) else: p.fulfill(onem2m_response) finally: response.release() finally: client.close() return p
def _send_request_to_endpoints(self, onem2m_request, poa_list): with Promise() as p: if not poa_list: p.reject(CSETargetNotReachable()) onem2m_request.originator = self.originator for poa in poa_list: use_xml = False # TODO(rst): check how this needs to be handled ssl_certs = { 'ca_certs': self.ca_file, 'cert_file': self.cert_file, 'key_file': self.key_file } # TODO(hve): add scheme test. client = self._get_clients[urlparse(poa).scheme]( poa, use_xml, insecure=self.accept_insecure_certs, **ssl_certs) try: response = client.send_onem2m_request(onem2m_request).get() p.fulfill(response) break except OpenMTCNetworkError: continue except OneM2MErrorResponse as error_response: p.reject(error_response) if p.isPending(): p.reject(CSETargetNotReachable()) return p
def send_request_indication(self, request_indication): path = request_indication.path with Promise() as p: if (request_indication.correlationID is None or request_indication.contactURI is "final_result"): request = map_request_indication_to_request(request_indication) def handle_success(response): return map_response_to_response_confirmation( request_indication.method, path, response) def handle_error(response): raise map_error_response_to_error_response_confirmation( request_indication, request, response ) return self._api.send_request(request).then(handle_success, handle_error) # In that case we have a delayed execution # TODO! request_indication.rcat = int(request_indication.rcat) if type(request_indication.trpdt) is str and \ (request_indication.trpdt.find('-') >= 0 or request_indication.trpdt.find(',') >= 0): # trpdt might be an ISO 8601 request_indication.trpdt = parse_date(request_indication.trpdt) else: request_indication.trpdt = float(request_indication.trpdt) def go(pend_reqs): """Checks if the number of pending requests is not reaching its limit. Answers with a SuccessResponseConfirmation(202). :param pend_reqs: List of pending requests """ cm = self.CommunicationChannelManager rcatParamList = cm.get_rcatParamList(request_indication.rcat) # Todo : Check number of bytes saved too if len(pend_reqs) > rcatParamList.maxPendReq: self.logger.warn( "Error: Pending request buffer overflow %s" % rcatParamList.maxPendReq) p.reject(ErrorResponseConfirmation( 500, request_indication.method, "Pending request buffer is full" )) else: # fulfill with accept self.logger.debug("fulfill with accept") p.fulfill(SuccessResponseConfirmation(202)) self.load_reqs(request_indication.rcat).then(go) return p
def get_epc_subscription_id(self, endpointId): #TODO: add DB search if self.epc_shelve is not None: return self.epc_shelve.getitem(endpointId) else: return Promise().reject( reason= "UnderlyingNetwork_SessionManager: epc id shelve not found")
def _update_scl(self, scl_path, scl): """ :param scl_path: str :param scl: :return: Promise """ p = Promise() def go(shelve): return self._do_update_scl(scl_path, scl, shelve) \ .then(shelve.commit, shelve.rollback) resources = self.shelve.get("resources") if resources is not None: return go(resources) else: return p.fulfill(None)
def test_3_2_5_2_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.reject("Error") order = [] p2 = p1.then(None, lambda v: add(order, "p2")) p3 = p1.then(None, lambda v: add(order, "p3")) assert_equals(2, len(order)) assert_equals("p2", order[0]) assert_equals("p3", order[1])
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_3_2_5_2_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.reject(Exception("Error")) order = [] p2 = p1.then(None, lambda v: add(order, "p2")) p3 = p1.then(None, lambda v: add(order, "p3")) assert_equals(2, len(order)) assert_equals("p2", order[0]) assert_equals("p3", order[1])
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_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_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_command(self, name, args=None, callback=None): promise = Promise() msg = { "name": name, "id": str(self.seq), "args": args or [] } msg_enc = json.dumps(msg, separators=(',', ':')) try: with self.ws_lock: if self.ws is None or self.state == SpotifyAPI.DISCONNECTED: return Promise.rejected(SpotifyDisconnectedError()) pid = self.seq if callback: promise.addCallback(callback) self.cmd_promises[pid] = promise self.seq += 1 self.ws.send(msg_enc) logger.debug("Sent PID({}) with msg: {}".format(pid, msg_enc)) except (SSLError, StreamClosed) as e: logger.error("SSL error ({}), attempting to continue".format(e)) promise.rejected(SpotifyDisconnectedError()) return promise
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 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_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_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 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_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 testNonFunction(nonFunction, results): def foo(results, k, r): results[k] = r p1 = Promise() p2 = p1.then(nonFunction, lambda r: foo(results, str(nonFunction), r)) p1.reject("Error: "+str(nonFunction))
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 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")