Python promise.Promise() Examples

The following are 23 code examples of promise.Promise(). 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 , or try the search function .
Example #1
Source File: kernel.py    From geonotebook with Apache License 2.0 6 votes vote down vote up
def resolve(self, msg):
        """Resolve an open JSONRPC request.

        Takes a JSONRPC result message and passes it to either the
        on_fulfilled handler or the on_rejected handler of the Promise.

        :param msg: JSONRPC result message
        :returns: Nothing
        :rtype: None

        """
        if msg['id'] in self._promises:
            try:
                if msg['error'] is not None:
                    self._promises[msg['id']].reject(Exception(msg['error']))
                else:
                    self._promises[msg['id']].fulfill(msg['result'])

            except Exception as e:
                raise e
        else:
            self.log.warn("Could not find promise with id %s" % msg['id']) 
Example #2
Source File: test_dataloader_fetch.py    From gigantum-client with MIT License 6 votes vote down vote up
def test_load_many_dataset(self, fixture_working_dir):
        im = InventoryManager(fixture_working_dir[0])
        im.create_dataset("default", "default", "dataset1", storage_type="gigantum_object_v1",
                          description="a dataset")
        im.create_dataset("default", "default", "dataset2", storage_type="gigantum_object_v1",
                          description="another dataset")
        im.create_dataset("default", "tester_user", "dataset3", storage_type="gigantum_object_v1",
                          description="yet another dataset")

        loader = FetchLoader()

        keys = ["dataset&default&default&dataset1", "dataset&default&default&dataset2",
                "dataset&default&tester_user&dataset3"]
        promise1 = loader.load_many(keys)
        assert isinstance(promise1, Promise)
        promise1.get() 
Example #3
Source File: test_dataloader_dataset.py    From gigantum-client with MIT License 6 votes vote down vote up
def test_load_many(self, fixture_working_dir):
        """Test loading many labbooks"""
        im = InventoryManager(fixture_working_dir[0])
        im.create_dataset("default", "default", "dataset1", storage_type="gigantum_object_v1",
                          description="a dataset")
        im.create_dataset("default", "default", "dataset2", storage_type="gigantum_object_v1",
                          description="another dataset")
        im.create_dataset("default", "tester_user", "dataset3", storage_type="gigantum_object_v1",
                          description="yet another dataset")

        loader = DatasetLoader()

        keys = ["default&default&dataset1", "default&default&dataset2", "default&tester_user&dataset3"]
        promise1 = loader.load_many(keys)
        assert isinstance(promise1, Promise)

        ds_list = promise1.get()
        assert ds_list[0].name == "dataset1"
        assert ds_list[0].description == "a dataset"
        assert ds_list[1].name == "dataset2"
        assert ds_list[1].description == "another dataset"
        assert ds_list[2].name == "dataset3"
        assert ds_list[2].description == "yet another dataset" 
Example #4
Source File: test_dataloader_labbook.py    From gigantum-client with MIT License 6 votes vote down vote up
def test_load_many(self, fixture_working_dir):
        """Test loading many labbooks"""
        im = InventoryManager(fixture_working_dir[0])
        im.create_labbook("default", "default", "labbook1", description="my first labbook1")
        im.create_labbook("default", "default", "labbook2", description="my first labbook2")
        im.create_labbook("default", "test3", "labbook2", description="my first labbook3")

        loader = LabBookLoader()

        keys = ["default&default&labbook1", "default&default&labbook2", "default&test3&labbook2"]
        promise1 = loader.load_many(keys)
        assert isinstance(promise1, Promise)

        lb_list = promise1.get()
        assert lb_list[0].name == "labbook1"
        assert lb_list[0].description == "my first labbook1"
        assert lb_list[1].name == "labbook2"
        assert lb_list[1].description == "my first labbook2"
        assert lb_list[2].name == "labbook2"
        assert lb_list[2].description == "my first labbook3" 
Example #5
Source File: test_dataloader_package.py    From gigantum-client with MIT License 6 votes vote down vote up
def test_load_many_apt(self, build_image_for_jupyterlab):
        lb, username = build_image_for_jupyterlab[0], build_image_for_jupyterlab[5]
        keys = ["apt&curl", "apt&vim"]
        loader = PackageDataloader(keys, lb, username)
        promise1 = loader.load_many(keys)
        assert isinstance(promise1, Promise)

        version_list = promise1.get()
        assert len(version_list) == 2
        assert isinstance(version_list[0], PackageMetadata) is True
        assert 'ubuntu' in version_list[0].latest_version
        assert version_list[0].description == 'command line tool for transferring data with URL syntax'
        assert version_list[0].docs_url is None
        assert version_list[0].package == 'curl'
        assert version_list[0].package_manager == 'apt'

        assert 'ubuntu' in version_list[1].latest_version
        assert version_list[1].description == 'Vi IMproved - enhanced vi editor'
        assert version_list[1].docs_url is None
        assert version_list[1].package == 'vim'
        assert version_list[1].package_manager == 'apt' 
Example #6
Source File: test_dataloader_package.py    From gigantum-client with MIT License 6 votes vote down vote up
def test_load_many_conda2(self, build_image_for_jupyterlab):
        """Test loading many conda2 packages"""
        lb, username = build_image_for_jupyterlab[0], build_image_for_jupyterlab[5]
        keys = ["conda2&cdutil", "conda2&python-coveralls", "conda2&nltk"]
        loader = PackageDataloader(keys, lb, username)
        promise1 = loader.load_many(keys)
        assert isinstance(promise1, Promise)

        version_list = promise1.get()
        assert len(version_list) == 3

        assert version_list[0].latest_version == "8.2"
        assert version_list[0].description == 'A set of tools to manipulate climate data'
        assert version_list[0].docs_url == 'http://anaconda.org/conda-forge/cdutil'

        assert version_list[1].latest_version == "2.9.3"
        assert version_list[1].description == 'Python interface to coveralls.io API\\n'
        assert version_list[1].docs_url == 'http://anaconda.org/conda-forge/python-coveralls'

        assert version_list[2].latest_version == "3.4.4"
        assert version_list[2].description == 'Natural Language Toolkit'
        assert version_list[2].docs_url == 'http://www.nltk.org/' 
Example #7
Source File: test_dataloader_package.py    From gigantum-client with MIT License 5 votes vote down vote up
def test_load_many_conda(self, build_image_for_jupyterlab):
        """Test loading many conda3 packages"""
        lb, username = build_image_for_jupyterlab[0], build_image_for_jupyterlab[5]
        keys = ["conda3&cdutil", "conda3&python-coveralls", "conda3&nltk", "conda3&asdfasdffghdfdasfgh"]
        loader = PackageDataloader(keys, lb, username)
        promise1 = loader.load_many(keys)
        assert isinstance(promise1, Promise)

        version_list = promise1.get()
        assert len(version_list) == 4

        assert version_list[0].latest_version == "8.2"
        assert version_list[0].description == 'A set of tools to manipulate climate data'
        assert version_list[0].docs_url == 'http://anaconda.org/conda-forge/cdutil'

        assert version_list[1].latest_version == "2.9.3"
        assert version_list[1].description == 'Python interface to coveralls.io API\\n'
        assert version_list[1].docs_url == 'http://anaconda.org/conda-forge/python-coveralls'

        assert version_list[2].latest_version == "3.4.4"
        assert version_list[2].description == 'Natural Language Toolkit'
        assert version_list[2].docs_url == 'http://www.nltk.org/'

        assert version_list[3].latest_version is None
        assert version_list[3].description is None
        assert version_list[3].docs_url is None 
Example #8
Source File: process.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def execute(self, fn, *args, **kwargs):
        promise = Promise()

        self.q.put([promise, fn, args, kwargs], False)
        _process = Process(target=queue_process, args=(self.q))
        _process.start()
        self.processes.append(_process)
        return promise 
Example #9
Source File: thread.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def execute_in_pool(self, fn, *args, **kwargs):
        promise = Promise()
        self.pool.map(lambda input: process(*input), [(promise, fn, args, kwargs)])
        return promise 
Example #10
Source File: thread.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def execute_in_thread(self, fn, *args, **kwargs):
        # type: (Callable, *Any, **Any) -> Promise
        promise = Promise()  # type: ignore
        thread = Thread(target=process, args=(promise, fn, args, kwargs))
        thread.start()
        self.threads.append(thread)
        return promise 
Example #11
Source File: graphql.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def execute_graphql(
    schema,  # type: GraphQLSchema
    request_string="",  # type: Union[Document, str]
    root_value=None,  # type: Any
    context_value=None,  # type: Optional[Any]
    variable_values=None,  # type: Optional[Any]
    operation_name=None,  # type: Optional[Any]
    middleware=None,  # type: Optional[Any]
    backend=None,  # type: Optional[Any]
    **execute_options  # type: Any
):
    # type: (...) -> Union[ExecutionResult, Observable, Promise[ExecutionResult]]
    try:
        if backend is None:
            backend = get_default_backend()

        document = backend.document_from_string(schema, request_string)
        return document.execute(
            root_value,
            context_value,
            operation_name=operation_name,
            variable_values=variable_values,
            middleware=middleware,
            **execute_options
        )
    except Exception as e:
        return ExecutionResult(errors=[e], invalid=True) 
Example #12
Source File: graphql.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def graphql(*args, **kwargs):
    # type: (*Any, **Any) -> Union[ExecutionResult, Observable, Promise[ExecutionResult]]
    return_promise = kwargs.get("return_promise", False)
    if return_promise:
        return execute_graphql_as_promise(*args, **kwargs)
    else:
        return execute_graphql(*args, **kwargs) 
Example #13
Source File: test_base.py    From graphql-core-legacy with MIT License 5 votes vote down vote up
def test_reraise_from_promise():
    # type: () -> None
    ast = parse("query Example { a }")

    def fail():
        raise Exception("Failed")

    def resolver(context, *_):
        # type: (Optional[Any], *ResolveInfo) -> None
        return Promise(lambda resolve, reject: resolve(fail()))

    Type = GraphQLObjectType(
        "Type", {"a": GraphQLField(GraphQLString, resolver=resolver)}
    )

    result = execute(GraphQLSchema(Type), ast)
    with pytest.raises(Exception) as exc_info:
        result.errors[0].reraise()

    extracted = traceback.extract_tb(exc_info.tb)
    formatted_tb = [row[2:] for row in extracted]
    formatted_tb = [tb for tb in formatted_tb if tb[0] != "reraise"]

    assert formatted_tb == [
        ("test_reraise_from_promise", "result.errors[0].reraise()"),
        ("_resolve_from_executor", "executor(resolve, reject)"),
        ("<lambda>", "return Promise(lambda resolve, reject: resolve(fail()))"),
        ("fail", 'raise Exception("Failed")'),
    ]

    assert str(exc_info.value) == "Failed" 
Example #14
Source File: test_subscription_transport.py    From graphql-python-subscriptions with MIT License 5 votes vote down vote up
def promisify(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        def executor(resolve, reject):
            return resolve(f(*args, **kwargs))

        return Promise(executor)

    return wrapper 
Example #15
Source File: test_dataloader_package.py    From gigantum-client with MIT License 5 votes vote down vote up
def test_load_many_mixed(self, build_image_for_jupyterlab):
        """Test loading many labbooks"""
        lb, username = build_image_for_jupyterlab[0], build_image_for_jupyterlab[5]
        keys = ["conda3&cdutil", "pip&gtmunit1", "pip&gtmunit2", "conda3&nltk", 'apt&curl']
        loader = PackageDataloader(keys, lb, username)
        promise1 = loader.load_many(keys)
        assert isinstance(promise1, Promise)

        version_list = promise1.get()
        assert len(version_list) == 5
        assert version_list[0].latest_version == "8.2"
        assert version_list[0].description == 'A set of tools to manipulate climate data'
        assert version_list[0].docs_url == 'http://anaconda.org/conda-forge/cdutil'

        assert version_list[1].latest_version == '0.12.4'
        assert version_list[1].description == 'Package 1 for Gigantum Client unit testing.'
        assert version_list[1].docs_url == 'https://github.com/gigantum/gigantum-client'

        assert version_list[2].latest_version == '12.2'
        assert version_list[2].description == 'Package 1 for Gigantum Client unit testing.'
        assert version_list[2].docs_url == 'https://github.com/gigantum/gigantum-client'

        assert version_list[3].latest_version == '3.4.4'
        assert version_list[3].description == 'Natural Language Toolkit'
        assert version_list[3].docs_url == 'http://www.nltk.org/'

        assert version_list[4].latest_version is not None
        assert version_list[4].description == 'command line tool for transferring data with URL syntax'
        assert version_list[4].docs_url is None 
Example #16
Source File: test_decorators.py    From django-graphql-social-auth with MIT License 5 votes vote down vote up
def test_social_auth_thenable(self, *args):

        @decorators.social_auth
        def wrapped(cls, root, info, provider, *args):
            return Promise()

        result = wrapped(TestCase, None, self.info(), 'google-oauth2', 'token')

        self.assertTrue(is_thenable(result)) 
Example #17
Source File: test_dataloader_package.py    From gigantum-client with MIT License 5 votes vote down vote up
def test_load_one_pip(self, build_image_for_jupyterlab):
        """Test loading 1 package"""

        key = "pip&gtmunit1"
        lb, username = build_image_for_jupyterlab[0], build_image_for_jupyterlab[5]

        loader = PackageDataloader([key], lb, username)
        promise1 = loader.load(key)
        assert isinstance(promise1, Promise)

        pkg = promise1.get()
        assert isinstance(pkg, PackageMetadata) is True
        assert pkg.description == 'Package 1 for Gigantum Client unit testing.'
        assert pkg.docs_url == 'https://github.com/gigantum/gigantum-client'
        assert pkg.latest_version == '0.12.4' 
Example #18
Source File: test_dataloader_labbook.py    From gigantum-client with MIT License 5 votes vote down vote up
def test_load_one(self, fixture_working_dir):
        """Test loading 1 labbook"""
        im = InventoryManager(fixture_working_dir[0])
        im.create_labbook("default", "default", "labbook1", description="my first labbook1")
        im.create_labbook("default", "default", "labbook2", description="my first labbook2")
        loader = LabBookLoader()

        key = f"default&default&labbook1"
        promise1 = loader.load(key)
        assert isinstance(promise1, Promise)

        lb = promise1.get()
        assert lb.name == "labbook1"
        assert lb.description == "my first labbook1" 
Example #19
Source File: test_dataloader_fetch.py    From gigantum-client with MIT License 5 votes vote down vote up
def test_load_many_labbook(self, fixture_working_dir):
        im = InventoryManager(fixture_working_dir[0])
        im.create_labbook("default", "default", "lb1", description="a project")
        im.create_labbook("default", "default", "lb2", description="a project")
        im.create_labbook("default", "default", "lb3", description="a project")

        loader = FetchLoader()

        keys = ["labbook&default&default&lb1", "labbook&default&default&lb2",
                "labbook&default&default&lb3"]
        promise1 = loader.load_many(keys)
        assert isinstance(promise1, Promise)
        promise1.get() 
Example #20
Source File: test_dataloader_fetch.py    From gigantum-client with MIT License 5 votes vote down vote up
def test_load_labbook_multiple(self, fixture_working_dir):
        im = InventoryManager(fixture_working_dir[0])
        im.create_labbook("default", "default", "lb1", description="a project")
        im.create_labbook("default", "default", "lb2", description="a project")
        loader = FetchLoader()

        key = "labbook&default&default&lb1"
        promise1 = loader.load(key)
        promise2 = loader.load(key)
        promise3 = loader.load(key)
        assert isinstance(promise1, Promise)
        assert promise1.get() is None
        assert promise2.get() is None
        assert promise3.get() is None 
Example #21
Source File: test_dataloader_fetch.py    From gigantum-client with MIT License 5 votes vote down vote up
def test_load_one_labbook(self, fixture_working_dir):
        im = InventoryManager(fixture_working_dir[0])
        im.create_labbook("default", "default", "lb1", description="a project")
        im.create_labbook("default", "default", "lb2", description="a project")
        loader = FetchLoader()

        key = "labbook&default&default&lb1"
        promise1 = loader.load(key)
        assert isinstance(promise1, Promise)
        assert promise1.get() is None 
Example #22
Source File: test_dataloader_fetch.py    From gigantum-client with MIT License 5 votes vote down vote up
def test_load_one_dataset(self, fixture_working_dir):
        im = InventoryManager(fixture_working_dir[0])
        im.create_dataset("default", "default", "dataset1", storage_type="gigantum_object_v1",
                          description="a dataset")
        im.create_dataset("default", "default", "dataset2", storage_type="gigantum_object_v1",
                          description="another dataset")
        loader = FetchLoader()

        key = f"dataset&default&default&dataset1"
        promise1 = loader.load(key)
        assert isinstance(promise1, Promise)
        assert promise1.get() is None 
Example #23
Source File: channelhandler.py    From python-sdk with MIT License 4 votes vote down vote up
def make_channel_request(self, data, packet_type,
                             response_type=None):
        seq = ChannelPack.make_seq32()
        request_pack = ChannelPack(packet_type, seq, 0, data)
        self.send_pack(request_pack)
        onresponse_emitter_str = ChannelHandler.getEmitterStr(self.onResponsePrefix,
                                                              seq, response_type)
        # register onResponse emitter
        self.lock.acquire()
        self.callbackEmitter.on(onresponse_emitter_str, self.onResponse)
        self.lock.release()
        self.requests.append(onresponse_emitter_str)

        # register onResponse emitter of RPC
        rpc_onresponse_emitter_str = None
        rpc_result_emitter_str = None
        if response_type is ChannelPack.TYPE_TX_COMMITTED \
                or response_type is ChannelPack.CLIENT_REGISTER_EVENT_LOG:
            rpc_onresponse_emitter_str = ChannelHandler.getEmitterStr(self.onResponsePrefix,
                                                                      seq, packet_type)
            self.requests.append(rpc_onresponse_emitter_str)
            rpc_result_emitter_str = ChannelHandler.getEmitterStr(self.getResultPrefix,
                                                                  seq, packet_type)
            self.lock.acquire()
            self.callbackEmitter.on(rpc_onresponse_emitter_str, self.onResponse)
            self.lock.release()
        emitter_str = ChannelHandler.getEmitterStr(self.getResultPrefix,
                                                   seq, response_type)

        def resolve_promise(resolve, reject):
            """
            resolve promise
            """
            # register getResult emitter
            self.lock.acquire()
            self.callbackEmitter.on(emitter_str, (lambda result, is_error: resolve(result)))

            # 1. if send transaction failed, return the error message directly
            #    and erase the registered 0x1002 emitter
            # 2. if send transaction success, remove the registered 0x12 emitter
            if rpc_result_emitter_str is not None:
                self.callbackEmitter.on(
                    rpc_result_emitter_str,
                    (lambda result, is_error:
                     resolve(result) and self.requests.remove(onresponse_emitter_str)
                     if is_error is True else self.requests.remove(rpc_onresponse_emitter_str)
                     if self.requests.count(rpc_onresponse_emitter_str) else None))
            self.lock.release()
        p = Promise(resolve_promise)
        # default timeout is 60s
        return p.get(60)