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]) + p.then_all( [(lambda x: x * x, lambda r: 1)]) + p.then_all(handlers) p.fulfill(4) assert [r.get() for r in results] == [4, 16, 16, 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 [r.get() for r in results] == [1, 1, 2]
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 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 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 counter[0] == 1
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 [r.value for r in results] == [16, 16, 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 [r.value for r in results] == [1, 1, 2]
def test_3_2_6_3_if_fulfilled(): """ Testing return of pending promises to make sure they are properly chained. This covers the case where the root promise is fulfilled before the chaining is defined. """ p1 = Promise() p1.fulfill(10) pending = Promise() pending.fulfill(5) pf = p1.then(lambda r: pending) assert pending.is_fulfilled assert 5 == pending.value assert pf.is_fulfilled assert 5 == pf.value p2 = Promise() p2.fulfill(10) bad = Promise() bad.reject(Exception("Error")) pr = p2.then(lambda r: bad) assert_exception(bad.reason, Exception, "Error") assert pr.is_rejected assert_exception(pr.reason, Exception, "Error")
def test_promise_reject_skip_all_other_values(): e1 = Exception("Error1") e2 = Exception("Error2") p = Promise() all_promises = all([1, Promise.reject(e1), Promise.reject(e2)]) with raises(Exception) as exc_info: all_promises.get() assert str(exc_info.value) == "Error1"
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.is_rejected assert_exception(p2.reason, Exception, "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 test_3_2_2_3(): """ Make sure fulfilled callback never called if promise is rejected """ cf = Counter() cr = Counter() p1 = Promise() p2 = p1.then(lambda v: cf.tick(), lambda r: cr.tick()) p1.reject(Exception("Error")) assert 0 == cf.value() assert 1 == cr.value()
def service_request(request_options): result = requests.get(request_options['url'], request_options['params']) if result.status_code != 200: return Promise.reject('Error on Third-Party service') body = result.text try: body = JSON.parse(body) except: pass if result.status_code != requests.codes.ok: console.error(body) return Promise.reject('Error on Third-Party service') return Promise.resolve(body)
def test_exceptions(): def throws(v): assert False p1 = Promise() p1.add_callback(throws) p1.fulfill(5) p2 = Promise() p2.add_errback(throws) p2.reject(Exception()) with pytest.raises(Exception) as excinfo: p2.get()
def test_exceptions(): def throws(v): assert False p1 = Promise() p1.add_callback(throws) p1.fulfill(5) p2 = Promise() p2.add_errback(throws) p2.reject(Exception()) with raises(Exception) as excinfo: p2.get()
def reject(self, exception): self._release_semaphore() if not self._set_state( Task.REJECTED, lambda state: state in [Task.UNSUBMITTED, Task.SUBMITTED, Task.RUNNING]): return if self._current_try <= self._retries: self._set_state(Task.SUBMITTED) delay_seconds = (2**self._current_try) + (random.randint(0, 1000) / 1000) logger.error( 'Retrying {0} in {1} seconds. exception: {2}, try: {3} of {4}'. format(self, delay_seconds, exception, self._current_try, self._retries + 1)) time.sleep(delay_seconds) self._current_try = self._current_try + 1 self._start(self._resolve, self._reject) return logger.error('Rejected {0} after {1} tries. exception: {2}'.format( self, self._current_try, exception)) self._exception = exception try: return self._reject(exception) if self._reject else Promise.reject( exception) finally: self._enqueue({'type': Task.REJECTED, 'exception': str(exception)}) self._close()
def write_data(script_name, run_time, red, green, blue, x_coordinate, y_coordinate, finished=None): """Given a row data, writes it to the main CSV""" LOGGER.info('Writing data to file') with open(DATA_FILE_NAME, 'a') as log_file: log_writer = writer(log_file, delimiter=',', quotechar='"', quoting=QUOTE_NONNUMERIC) # Attach a final timestamp if not already there if finished is None: finished = unix_time() log_writer.writerow([ script_name, run_time, red, green, blue, x_coordinate, y_coordinate, finished ]) LOGGER.debug('Write successful') return Promise.resolve('written') LOGGER.error('Write failed') return Promise.reject('Unable to write data')
def send_command(self, command, input, schandlerid=None): '''Method for sending ClientQuery commands. Parameters: "command" should be name of the command to send. "input" is a list of dicts. Each key/value in a dict is converted to key=value pair, with proper escaping applied. Each pair is separated from each other with space ( ). Each dict in the list is separated from another with pipe (|). "schandlerid" is server connection ID where to send the command. Any other value than None sends "use" command to switch the connection before the actual command is given. Returns ClientQueryCommand object which will emit "error" or "result" event on command completion. ''' promise = (Promise.resolve(None) .then(lambda res: None if self.is_connected() else Promise.reject(Error("Not connected")))) if schandlerid is not None and schandlerid != self.__schandlerid: # Tell ClientQuery to use different schandlerid if desired schandlerid differs from # previously requested one self.__schandlerid = schandlerid promise = (promise .then(lambda res: self.__queue_command("use", [{"schandlerid": schandlerid}])) .then(lambda res: self.__set_schandlerid(schandlerid))) return (promise .then(lambda res: self.__queue_command(command, input)))
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 1 == c.value()
def testNonFunction(nonFunction): def foo(k, r): results[k] = r p1 = Promise.reject(Exception("Error: " + str(nonFunction))) p2 = p1.then(nonFunction, lambda r: foo(str(nonFunction), r)) p2._wait()
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 pf.value == 25 p2 = Promise() pr = p2.then(None, lambda r: 5) p2.reject(Exception("Error")) assert 5 == pr.value
def promote(self): if self.isGroupMessage(): return self.promoteParticipantsInGroup(self.getFrom(), [self.getAuthor()]) else: return Promise.reject( RuntimeError( "DanksupContext.promote() only valid for group messages"))
def test_promise_rejected(): e = Exception("Error") all_promises = all([1, 2, Promise.reject(e)]) with raises(Exception) as exc_info: all_promises.get() assert str(exc_info.value) == "Error"
def test_3_2_3_2(): """ Make sure callbacks are never called more than once. """ c = Counter() p1 = Promise() p2 = p1.then(None, lambda v: c.tick()) p1.reject(Exception("Error")) try: # I throw an exception p1.reject(Exception("Error")) assert False # Should not get here! except AssertionError: # This is expected pass assert 1 == c.value()
def forecast_result(result): result = ast.literal_eval(result) print result try: result = result['forecast'] except Exception as e: return Promise.reject('Error on parse weather forecast ' + str(e)) return Promise.resolve(result)
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 2 == len(order) assert "p2" == order[0] assert "p3" == order[1]
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.is_rejected assert_exception(pf.reason, AssertionError, "Exception Message") p2 = Promise() p2.reject(Exception("Error")) pr = p2.then(None, fail) assert pr.is_rejected assert_exception(pr.reason, AssertionError, "Exception Message")
def current_result(result): result = ast.literal_eval(result) if 'results' in result['response']: if 'current_observation' not in result: return Promise.reject( 'Invalid address, ' + str(len(result['response']['results'])) + ' match.') elif 'current_observation' not in result: return Promise.reject('Invalid address') result = result['current_observation'] try: del result['image'] del result['icon_url'] del result['forecast_url'] del result['history_url'] del result['ob_url'] del result['estimated'] except Exception as e: return Promise.reject('weather system, ' + str(e)) return Promise.resolve(result)
def parse_out_data(haystack): """Finds the result from stdout""" LOGGER.info('Parsing stdout') possible_result = search(COMPILED_STDOUT_PATTERN, haystack) if possible_result.group('diff'): LOGGER.debug("Diff: %f", float(possible_result.group('diff'))) if possible_result.group('rgb'): raw_rgb = map(int, possible_result.group('rgb').split(',')) LOGGER.debug("RGB: (%d,%d,%d)", *raw_rgb) if possible_result.group('mouse'): mouse_coords = map(int, possible_result.group('mouse').split(',')) LOGGER.debug("Mouse: (%d,%d)", *mouse_coords) return Promise.resolve([float(possible_result.group('diff'))] + raw_rgb + mouse_coords) LOGGER.error('Parsing failed') return Promise.reject('Mouse not found') LOGGER.error('Parsing failed') return Promise.reject('RGB not found') LOGGER.error('Parsing failed') return Promise.reject('Difference not found')
def test_3_2_2_3(): """ Make sure fulfilled callback never called if promise is rejected """ cf = Counter() cr = Counter() p1 = Promise.reject(Exception("Error")) p2 = p1.then(lambda v: cf.tick(), lambda r: cr.tick()) p2._wait() assert 0 == cf.value() assert 1 == cr.value()
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 counter[0] == 1 p = Promise() p.done(inc, dec) p.done(inc, dec) p.reject(Exception()) assert counter[0] == -1
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.is_pending assert pr.is_pending p1.reject(Exception("Error")) pending.fulfill(10) assert pending.is_fulfilled assert 10 == pending.value assert pr.is_fulfilled assert 10 == pr.value p2 = Promise() bad = Promise() pr = p2.then(None, lambda r: bad) assert bad.is_pending assert pr.is_pending p2.reject(Exception("Error")) bad.reject(Exception("Assertion")) assert bad.is_rejected assert_exception(bad.reason, Exception, "Assertion") assert pr.is_rejected assert_exception(pr.reason, Exception, "Assertion")
def reject(self, exception): if not self._set_state( Task.REJECTED, lambda state: state in [Task.UNSUBMITTED, Task.SUBMITTED, Task.RUNNING]): return self._exception = exception logger.exception('Rejected {0}'.format(self)) try: return self._reject(exception) if self._reject else Promise.reject( exception) finally: self._enqueue({'type': Task.REJECTED, 'exception': str(exception)}) self._close()
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 counter[0] == 4 p = Promise() p.done_all() p.done_all([inc]) p.done_all([(inc, dec)]) p.done_all([ (inc, dec), { 'success': inc, 'failure': dec }, ]) p.reject(Exception()) assert counter[0] == 1
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.resolve(5) pf = p1.then(lambda v: v * v) assert pf.get() == 25 p2 = Promise.reject(Exception("Error")) pr = p2.then(None, lambda r: 5) assert 5 == pr.get()
def cancel(self): if not self._set_state( Task.CANCELED, lambda state: state in [Task.UNSUBMITTED, Task.SUBMITTED, Task.RUNNING]): return try: raise Task.Canceled() except Task.Canceled as exception: self.reject(re_raisable()) return self._reject(exception) if self._reject else Promise.reject( exception) finally: self._enqueue({'type': Task.CANCELED}) self._close()
def execute_script(script_name): """Runs the given script""" full_script_path = join(SCRIPTS_PATH, script_name) if isfile(full_script_path): extension = splitext(script_name) runner = ('python' if '.py' == extension[1] else 'bash') LOGGER.debug("%s %s", runner, full_script_path) result = '\n\n' + check_output([runner, full_script_path]) LOGGER.debug(result) return Promise(lambda resolve, reject: resolve(parse_out_data( result))).then(lambda result: Promise.resolve( [result[0] * (1000 if extension[1] == '.py' else 1)] + result[1:])) LOGGER.error("%s failed", script_name) return Promise.reject("%s failed" % (script_name))
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.reject(Exception("Error")) p2 = p1.then(None, lambda r: check(r, c)) p2._wait() assert 1 == c.value()
def test_3_2_3_2(): """ Make sure callbacks are never called more than once. """ c = Counter() p1 = Promise.reject(Exception("Error")) p2 = p1.then(None, lambda v: c.tick()) p2._wait() try: # I throw an exception p1.do_reject(Exception("Error")) assert False # Should not get here! except AssertionError: # This is expected pass assert 1 == c.value()
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.reject(Exception("Error")) order = [] p2 = p1.then(None, lambda v: add(order, "p2")) p3 = p1.then(None, lambda v: add(order, "p3")) p2._wait() p3._wait() assert 2 == len(order) assert "p2" == order[0] assert "p3" == order[1]
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.resolve(5) pf = p1.then(fail) pf._wait() assert pf.is_rejected assert_exception(pf.reason, AssertionError, "Exception Message") p2 = Promise.reject(Exception("Error")) pr = p2.then(None, fail) pr._wait() assert pr.is_rejected assert_exception(pr.reason, AssertionError, "Exception Message")
class PromiseTest(unittest.TestCase): def setUp(self): self.promise = Promise() def testOnFulfilledCallback(self): # 2.2.2.1 self.called_ = False def resolveCallback(val): self.called_ = True self.assertEqual(10, val) self.promise.then(resolveCallback) self.promise.resolve(10) def testResolveCannotBeCalledTwice(self): # 2.2.2.2/2.2.2.3 self.promise.resolve(10) with self.assertRaises(PromiseException): self.promise.resolve(10) def testOnRejectedCallback(self): # 2.2.3.1 self.called_ = False def rejectCallback(error): self.called_ = True self.assertIsInstance(error, Exception) self.promise.then(lambda _: _, rejectCallback) self.promise.reject(Exception('test')) def testRejectCannotBeCalledTwice(self): # 2.2.3.2/2.2.3.3 self.promise.reject(Exception('test')) with self.assertRaises(PromiseException): self.promise.reject(Exception('test')) def testFulfilledCallbacksOrder(self): # 2.2.6.1 self.index = 0 def callback1(): self.index += 1 self.assertEqual(self.index, 1) def callback2(): self.index += 1 self.assertEqual(self.index, 2) self.promise.resolve(10) def testRejectedCallbacksOrder(self): # 2.2.6.2 pass
def history(self, date, query, full, lang): def history_result(result): result = ast.literal_eval(result) result = result['history'] return Promise.resolve(result) params = {'query': query, 'full': full, 'lang': lang} self._setParams(params) try: date = datetime.strptime(date, '%Y-%m-%d') date = str(date.year) + str(format(date.month, '02')) + str( format(date.day, '02')) except Exception as e: return Promise.reject('Invalid date', +e) url = 'http://api.wunderground.com/api/' + self.key + '/lang:' + self._lang + '/history_' + str( date) + '/q/' + urllib.quote(self._query.encode("utf-8")) + '.json' method = 'GET' self.default_options['url'] = url self.default_options['method'] = method self.default_options['params'] = params options = self.default_options return request(options).then(lambda result: history_result(result))
def __execute_whoami(self, schandlerid): return (self.command_whoami(schandlerid=schandlerid) .then(lambda res: self.__set_schandler_data(schandlerid, res["clid"], res["cid"])) .then(lambda res: self.emit("connected-server", schandlerid)) # ignore error if not connected to ts server .catch(lambda err: None if err.id == 1794 else Promise.reject(err)))