Python promise.Promise.resolve() Examples
The following are 30
code examples of promise.Promise.resolve().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
promise.Promise
, or try the search function
.
Example #1
Source File: test_spec.py From promise with MIT License | 8 votes |
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.resolve(2) order = [] p2 = p1.then(lambda v: add(order, "p2")) p3 = p1.then(lambda v: add(order, "p3")) p2._wait() p3._wait() assert 2 == len(order) assert "p2" == order[0] assert "p3" == order[1]
Example #2
Source File: test_spec.py From promise with MIT License | 8 votes |
def test_3_2_1_2(): """ That that the second argument to 'then' is ignored if it is not a function. """ results = {} nonFunctions = [None, False, 5, {}, []] def testNonFunction(nonFunction): def foo(k, r): results[k] = r p1 = Promise.resolve("Error: " + str(nonFunction)) p2 = p1.then(lambda r: foo(str(nonFunction), r), nonFunction) p2._wait() for v in nonFunctions: testNonFunction(v) for v in nonFunctions: assert "Error: " + str(v) == results[str(v)]
Example #3
Source File: connection_field.py From graphene-sqlalchemy-filter with MIT License | 7 votes |
def get_filter_set(cls, info: 'ResolveInfo') -> 'FilterSet': """ Get field filter set. Args: info: Graphene resolve info object. Returns: FilterSet class from field args. """ field_name = info.field_asts[0].name.value schema_field = info.parent_type.fields.get(field_name) filters_type = schema_field.args[cls.filter_arg].type filters: 'FilterSet' = filters_type.graphene_type return filters
Example #4
Source File: test_spec.py From promise with MIT License | 7 votes |
def test_3_2_6_2_when(): """ 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")
Example #5
Source File: connection_field.py From graphene-sqlalchemy-filter with MIT License | 7 votes |
def _get_filter_set(cls, info: 'ResolveInfo') -> 'FilterSet': """ Get field filter set. Args: info: Graphene resolve info object. Returns: FilterSet class from field args. """ field_name = info.field_asts[0].name.value schema_field = info.parent_type.fields.get(field_name) filters_type = schema_field.args[cls.filter_arg].type filters: 'FilterSet' = filters_type.graphene_type return filters
Example #6
Source File: test_spec.py From promise with MIT License | 7 votes |
def test_3_2_5_1_when(): """ 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.resolve(2) order = [] p2 = p1.then(lambda v: add(order, "p2")) p3 = p1.then(lambda v: add(order, "p3")) p2._wait() p3._wait() assert 2 == len(order) assert "p2" == order[0] assert "p3" == order[1]
Example #7
Source File: test_spec.py From promise with MIT License | 7 votes |
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 v == 5 c.tick() p1 = Promise.resolve(5) p2 = p1.then(lambda v: check(v, c)) p2._wait() assert 1 == c.value()
Example #8
Source File: test_benchmark.py From promise with MIT License | 7 votes |
def test_benchmark_promise_creation_with_reject(benchmark): do_resolve = lambda resolve, reject: reject(Exception("Error")) def create_promise(): # unnecessary function call p = Promise(do_resolve) # p._wait() return p with raises(Exception) as exc_info: result = benchmark(create_promise).get() assert str(exc_info.value) == "Error" # def test_benchmark_promisify_promise(benchmark): # instance = Promise() # def create_promise(): # unnecessary function call # return promisify(instance) # result = benchmark(create_promise) # assert isinstance(result, Promise)
Example #9
Source File: test_issues.py From promise with MIT License | 6 votes |
def test_issue_75(): def function_with_local_type(): class A: pass a = A() assert a == Promise.resolve(a).get() return weakref.ref(A) weak_reference = function_with_local_type() # The local type 'A' from the function is still kept alive by reference cycles. gc.collect() # Now the local type should have been garbage collected, # such that the weak reference should be invalid. assert not weak_reference()
Example #10
Source File: test_dataloader.py From promise with MIT License | 6 votes |
def test_wrong_loader_return_type_does_not_block_async_instance(): @Promise.safe def do(): def do_resolve(x): return x a_loader, a_load_calls = id_loader(resolve=do_resolve) with raises(Exception): a_loader.load("A1").get() assert async_instance.have_drained_queues with raises(Exception): a_loader.load("A2").get() assert async_instance.have_drained_queues do().get()
Example #11
Source File: test_dataloader.py From promise with MIT License | 6 votes |
def test_can_represent_failures_and_successes_simultaneously(): @Promise.safe def do(): def resolve(keys): mapped_keys = [ key if key % 2 == 0 else Exception("Odd: {}".format(key)) for key in keys ] return Promise.resolve(mapped_keys) even_loader, load_calls = id_loader(resolve=resolve) promise1 = even_loader.load(1) promise2 = even_loader.load(2) with raises(Exception) as exc_info: promise1.get() assert str(exc_info.value) == "Odd: 1" value2 = promise2.get() assert value2 == 2 assert load_calls == [[1, 2]] do().get()
Example #12
Source File: test_dataloader.py From promise with MIT License | 6 votes |
def test_supports_loading_multiple_keys_in_one_call(): def call_fn(keys): return Promise.resolve(keys) identity_loader = DataLoader(call_fn) promise_all = identity_loader.load_many([1, 2]) assert isinstance(promise_all, Promise) values = promise_all.get() assert values == [1, 2] promise_all = identity_loader.load_many([]) assert isinstance(promise_all, Promise) values = promise_all.get() assert values == []
Example #13
Source File: test_issues.py From promise with MIT License | 6 votes |
def test_issue_11(): # https://github.com/syrusakbary/promise/issues/11 def test(x): def my(resolve, reject): if x > 0: resolve(x) else: reject(Exception(x)) return Promise(my) promise_resolved = test(42).then(lambda x: x) assert promise_resolved.get() == 42 promise_rejected = test(-42).then(lambda x: x, lambda e: str(e)) assert promise_rejected.get() == "-42"
Example #14
Source File: test_dataloader.py From promise with MIT License | 6 votes |
def test_caches_failed_fetches(): @Promise.safe def do(): def resolve(keys): mapped_keys = [Exception("Error: {}".format(key)) for key in keys] return Promise.resolve(mapped_keys) error_loader, load_calls = id_loader(resolve=resolve) with raises(Exception) as exc_info: error_loader.load(1).get() assert str(exc_info.value) == "Error: 1" with raises(Exception) as exc_info: error_loader.load(1).get() assert str(exc_info.value) == "Error: 1" assert load_calls == [[1]] do().get()
Example #15
Source File: connection_field.py From graphene-sqlalchemy-filter with MIT License | 6 votes |
def batch_load_fn(self, keys: 'List[tuple]') -> Promise: """ Load related objects. Args: keys: Primary key values of parent model. Returns: Lists of related orm objects. """ if len(self.parent_model_pk_fields) == 1: left_hand_side = self.parent_model_pk_fields[0] right_hand_side = [k[0] for k in keys] else: left_hand_side = tuple_(*self.parent_model_pk_fields) right_hand_side = keys query: 'Query' = self._get_query().filter( left_hand_side.in_(right_hand_side) ) objects: 'Dict[tuple, Any]' = { self.parent_model_object_to_key(parent_object): getattr( parent_object, self.model_relation_field ) for parent_object in query } return Promise.resolve( [objects.get(object_id, []) for object_id in keys] )
Example #16
Source File: test_issues.py From promise with MIT License | 5 votes |
def test_issue_26(): context = {"success": False} promise1 = Promise( lambda resolve, reject: context.update({"promise1_reject": reject}) ) promise1.then(lambda x: None) promise1.then(lambda x: None) context["promise1_reject"](RuntimeError("Ooops!")) promise2 = Promise( lambda resolve, reject: context.update({"promise2_resolve": resolve}) ) promise3 = promise2.then(lambda x: context.update({"success": True})) context["promise2_resolve"](None) # We wait so it works in asynchronous envs promise3._wait(timeout=.1) assert context["success"] # def promise_in_executor(x, wait): # return Promise.promisify(executor.submit(identity, x, wait)) # @Promise.safe # def test_issue_9_extra(): # no_wait = Promise.all([promise_in_executor(x1, None).then(lambda y: x1*y) for x1 in (0,1,2,3)]).get() # wait_a_bit = Promise.all([promise_in_executor(x2, 0.1).then(lambda y: x2*y) for x2 in (0,1,2,3)]).get() # wait_longer = Promise.all([promise_in_executor(x3, 0.5).then(lambda y: x3*y) for x3 in (0,1,2,3)]).get() # assert no_wait == [0, 3, 6, 9] # assert no_wait == wait_a_bit # assert no_wait == wait_longer
Example #17
Source File: subscription_manager.py From graphql-python-subscriptions with MIT License | 5 votes |
def subscribe(self, trigger_name, on_message_handler, options): self.sub_id_counter += 1 try: if trigger_name not in list(self.subscriptions.values())[0]: self.pubsub.subscribe(trigger_name) except IndexError: self.pubsub.subscribe(trigger_name) self.subscriptions[self.sub_id_counter] = [ trigger_name, on_message_handler ] if not self.greenlet: self.greenlet = gevent.spawn(self.wait_and_get_message) return Promise.resolve(self.sub_id_counter)
Example #18
Source File: schema.py From influence-texas with GNU General Public License v2.0 | 5 votes |
def batch_load_fn(self, keys): bills = {bill.id: bill for bill in Bill.objects.filter(id__in=keys)} return Promise.resolve([bills.get(bill_id) for bill_id in keys])
Example #19
Source File: test_middleware.py From graphql-core-legacy with MIT License | 5 votes |
def test_middleware_class(): # type: () -> None doc = """{ ok not_ok }""" class Data(object): def ok(self): # type: () -> str return "ok" def not_ok(self): # type: () -> str return "not_ok" doc_ast = parse(doc) Type = GraphQLObjectType( "Type", {"ok": GraphQLField(GraphQLString), "not_ok": GraphQLField(GraphQLString)}, ) class MyMiddleware(object): def resolve(self, next, *args, **kwargs): # type: (Callable, *Any, **Any) -> Promise p = next(*args, **kwargs) return p.then(lambda x: x[::-1]) middlewares = MiddlewareManager(MyMiddleware()) result = execute(GraphQLSchema(Type), doc_ast, Data(), middleware=middlewares) assert result.data == {"ok": "ko", "not_ok": "ko_ton"}
Example #20
Source File: test_resolve.py From graphql-core-legacy with MIT License | 5 votes |
def test_handles_resolved_promises(): # type: () -> None def resolver(source, info, **args): # type: (Optional[Any], ResolveInfo, **Any) -> Promise return Promise.resolve("foo") schema = _test_schema(GraphQLField(GraphQLString, resolver=resolver)) result = graphql(schema, "{ test }", None) assert not result.errors assert result.data == {"test": "foo"}
Example #21
Source File: test_resolve.py From graphql-core-legacy with MIT License | 5 votes |
def test_handles_resolved_custom_promises(): # type: () -> None def resolver(source, info, **args): # type: (Optional[Any], ResolveInfo, **Any) -> CustomPromise return CustomPromise.resolve("custom_foo") schema = _test_schema(GraphQLField(GraphQLString, resolver=resolver)) result = graphql(schema, "{ test }", None) assert not result.errors assert result.data == {"test": "custom_foo"}
Example #22
Source File: asyncio.py From graphql-core-legacy with MIT License | 5 votes |
def execute(self, fn, *args, **kwargs): # type: (Callable, *Any, **Any) -> Any result = fn(*args, **kwargs) if isinstance(result, Future) or iscoroutine(result): future = ensure_future(result, loop=self.loop) self.futures.append(future) return Promise.resolve(future) elif isasyncgen(result): return asyncgen_to_observable(result, loop=self.loop) return result
Example #23
Source File: test_subscription_manager.py From graphql-python-subscriptions with MIT License | 5 votes |
def sub_mgr(pubsub, schema): def filter_single(**kwargs): args = kwargs.get('args') return { 'filter_1': { 'filter': lambda root, context: root.get('filterBoolean') == args.get('filterBoolean') }, 'filter_2': { 'filter': lambda root, context: Promise.resolve(root.get('filterBoolean') == args.get('filterBoolean')) }, } def filter_multi(**kwargs): return { 'trigger_1': { 'filter': lambda root, context: True }, 'trigger_2': { 'filter': lambda root, context: True } } def filter_channel_options(**kwargs): return {'trigger_1': {'channel_options': {'foo': 'bar'}}} def filter_context(**kwargs): return {'context_trigger': lambda root, context: context == 'trigger'} return SubscriptionManager( schema, pubsub, setup_funcs={ 'test_filter': filter_single, 'test_filter_multi': filter_multi, 'test_channel_options': filter_channel_options, 'test_context': filter_context })
Example #24
Source File: test_dataloader_awaitable_35.py From promise with MIT License | 5 votes |
def id_loader(**options): load_calls = [] resolve = options.pop("resolve", Promise.resolve) def fn(keys): load_calls.append(keys) return resolve(keys) identity_loader = DataLoader(fn, **options) return identity_loader, load_calls
Example #25
Source File: dataset.py From gigantum-client with MIT License | 5 votes |
def batch_load_fn(self, keys: List[str]): """Method to load dataset objects based on a list of unique keys Args: keys(list(str)): Unique key to identify the dataset Returns: """ return Promise.resolve([self.get_dataset_instance(key) for key in keys])
Example #26
Source File: test_dataloader.py From promise with MIT License | 5 votes |
def test_can_call_a_loader_from_a_loader(): @Promise.safe def do(): deep_loader, deep_load_calls = id_loader() a_loader, a_load_calls = id_loader( resolve=lambda keys: deep_loader.load(tuple(keys)) ) b_loader, b_load_calls = id_loader( resolve=lambda keys: deep_loader.load(tuple(keys)) ) a1, b1, a2, b2 = Promise.all( [ a_loader.load("A1"), b_loader.load("B1"), a_loader.load("A2"), b_loader.load("B2"), ] ).get() assert a1 == "A1" assert b1 == "B1" assert a2 == "A2" assert b2 == "B2" assert a_load_calls == [["A1", "A2"]] assert b_load_calls == [["B1", "B2"]] assert deep_load_calls == [[("A1", "A2"), ("B1", "B2")]] do().get()
Example #27
Source File: test_dataloader.py From promise with MIT License | 5 votes |
def id_loader(**options): load_calls = [] resolve = options.pop("resolve", Promise.resolve) def fn(keys): load_calls.append(keys) return resolve(keys) identity_loader = DataLoader(fn, **options) return identity_loader, load_calls
Example #28
Source File: test_dataloader.py From promise with MIT License | 5 votes |
def test_catches_error_if_loader_resolver_fails(): @Promise.safe def do(): def do_resolve(x): raise Exception("AOH!") a_loader, a_load_calls = id_loader(resolve=do_resolve) with raises(Exception) as exc_info: a_loader.load("A1").get() assert str(exc_info.value) == "AOH!" do().get()
Example #29
Source File: test_dataloader.py From promise with MIT License | 5 votes |
def test_build_a_simple_data_loader(): def call_fn(keys): return Promise.resolve(keys) identity_loader = DataLoader(call_fn) promise1 = identity_loader.load(1) assert isinstance(promise1, Promise) value1 = promise1.get() assert value1 == 1
Example #30
Source File: test_dataloader.py From promise with MIT License | 5 votes |
def test_caches_failed_fetches(): @Promise.safe def do(): identity_loader, load_calls = id_loader() identity_loader.prime(1, Exception("Error: 1")) with raises(Exception) as exc_info: identity_loader.load(1).get() assert load_calls == [] do().get() # It is resilient to job queue ordering # def test_batches_loads_occuring_within_promises(): # @Promise.safe # def do(): # identity_loader, load_calls = id_loader() # values = Promise.all([ # identity_loader.load('A'), # Promise.resolve(None).then(lambda v: Promise.resolve(None)).then( # lambda v: identity_loader.load('B') # ) # ]).get() # assert values == ['A', 'B'] # assert load_calls == [['A', 'B']] # do().get()