Python asyncio.run() Examples

The following are 30 code examples of asyncio.run(). 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 asyncio , or try the search function .
Example #1
Source File: test_duck_pond.py    From bot with MIT License 6 votes vote down vote up
def test_fetch_webhook_logs_when_unable_to_fetch_webhook(self):
        """The `fetch_webhook` method should log an exception when it fails to fetch the webhook."""
        self.bot.fetch_webhook.side_effect = discord.HTTPException(response=MagicMock(), message="Not found.")
        self.cog.webhook_id = 1

        log = logging.getLogger('bot.cogs.duck_pond')
        with self.assertLogs(logger=log, level=logging.ERROR) as log_watcher:
            asyncio.run(self.cog.fetch_webhook())

        self.bot.wait_until_guild_available.assert_called_once()
        self.bot.fetch_webhook.assert_called_once_with(1)

        self.assertEqual(len(log_watcher.records), 1)

        record = log_watcher.records[0]
        self.assertEqual(record.levelno, logging.ERROR) 
Example #2
Source File: getTGS.py    From minikerberos with MIT License 6 votes vote down vote up
def main():
	import argparse
	
	parser = argparse.ArgumentParser(description='Polls the kerberos service for a TGS for the sepcified user and specified service', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
	parser.add_argument('kerberos_connection_string', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')
	parser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server "fileserver". IMPORTANT: SERVER\'S HOSTNAME MUST BE USED, NOT IP!!!')
	parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
	parser.add_argument('-u', action='store_true', help='Use UDP instead of TCP (not tested)')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	
	args = parser.parse_args()
	if args.verbose == 0:
		logging.basicConfig(level=logging.INFO)
	elif args.verbose == 1:
		logging.basicConfig(level=logging.DEBUG)
	else:
		logging.basicConfig(level=1)
	
	asyncio.run(amain(args)) 
Example #3
Source File: getS4U2proxy.py    From minikerberos with MIT License 6 votes vote down vote up
def main():
	import argparse
	
	parser = argparse.ArgumentParser(description='Gets an S4U2proxy ticket impersonating given user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
	parser.add_argument('kerberos_connection_url', help='the kerberos target string in the following format <domain>/<username>/<secret_type>:<secret>@<domaincontroller-ip>')
	parser.add_argument('spn', help='the service principal in format <service>/<server-hostname>@<domain> Example: cifs/fileserver.test.corp@TEST.corp for a TGS ticket to be used for file access on server "fileserver". IMPORTANT: SERVER\'S HOSTNAME MUST BE USED, NOT IP!!!')
	parser.add_argument('targetuser', help='')
	parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	
	args = parser.parse_args()
	if args.verbose == 0:
		logger.setLevel(logging.WARNING)
	elif args.verbose == 1:
		logger.setLevel(logging.INFO)
	else:
		logger.setLevel(1)

	asyncio.run(amain(args)) 
Example #4
Source File: getTGT.py    From minikerberos with MIT License 6 votes vote down vote up
def main():
	import argparse
	
	parser = argparse.ArgumentParser(description='Polls the kerberos service for a TGT for the sepcified user', formatter_class=argparse.RawDescriptionHelpFormatter, epilog = kerberos_url_help_epilog)
	parser.add_argument('kerberos_connection_url', help='the kerberos target string. ')
	parser.add_argument('ccache', help='ccache file to store the TGT ticket in')
	parser.add_argument('-v', '--verbose', action='count', default=0)
	
	args = parser.parse_args()
	if args.verbose == 0:
		logging.basicConfig(level=logging.INFO)
	elif args.verbose == 1:
		logging.basicConfig(level=logging.DEBUG)
	else:
		logging.basicConfig(level=1)
	
	asyncio.run(amain(args)) 
Example #5
Source File: test_duck_pond.py    From bot with MIT License 6 votes vote down vote up
def test_on_raw_reaction_add_returns_on_message_with_green_checkmark_placed_by_bot(self, count_ducks, is_staff):
        """The `on_raw_reaction_add` event should return when the message has a green check mark placed by the bot."""
        channel_id = 31415926535
        message_id = 27182818284
        user_id = 16180339887

        channel, message, member, payload = self._raw_reaction_mocks(channel_id, message_id, user_id)

        payload.emoji = helpers.MockPartialEmoji(name=self.unicode_duck_emoji)
        payload.emoji.is_custom_emoji.return_value = False

        message.reactions = [helpers.MockReaction(emoji=self.checkmark_emoji, users=[self.bot.user])]

        is_staff.return_value = True
        count_ducks.side_effect = AssertionError("Expected method to return before calling `self.count_ducks`")

        self.assertIsNone(asyncio.run(self.cog.on_raw_reaction_add(payload)))

        # Assert that we've made it past `self.is_staff`
        is_staff.assert_called_once() 
Example #6
Source File: eva.py    From eva with Apache License 2.0 6 votes vote down vote up
def eva():
    """
        Start the eva system
    """

    # Get the hostname and port information from the configuration file
    config = ConfigurationManager()
    hostname = config.get_value('server', 'hostname')
    port = config.get_value('server', 'port')
    socket_timeout = config.get_value('server', 'socket_timeout')    
    loop = asyncio.new_event_loop()
    stop_server_future = loop.create_future()

    # Launch server
    try:
        asyncio.run(start_server(host=hostname,
                                 port=port,
                                 loop=loop,
                                 socket_timeout=socket_timeout,
                                 stop_server_future=stop_server_future)
                    )

    except Exception as e:
        LoggingManager().log(e, LoggingLevel.CRITICAL) 
Example #7
Source File: server.py    From edgedb with Apache License 2.0 6 votes vote down vote up
def run_cli(self, *args, input: Optional[str]=None):
        conn_args = self.get_connect_args()

        cmd_args = (
            '--host', conn_args['host'],
            '--port', str(conn_args['port']),
            '--user', conn_args['user'],
        ) + args

        if conn_args['password']:
            cmd_args = ('--password-from-stdin',) + cmd_args
            if input is not None:
                input = f"{conn_args['password']}\n{input}"
            else:
                input = f"{conn_args['password']}\n"

        subprocess.run(
            ('edgedb',) + cmd_args,
            input=input.encode() if input else None,
            check=True,
            capture_output=True,
        ) 
Example #8
Source File: etcd.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def get(cli_ctx, key, prefix, scope):
    '''
    Get the value of a key in the configured etcd namespace.
    '''
    async def _impl():
        async with etcd_ctx(cli_ctx) as etcd:
            try:
                if prefix:
                    data = await etcd.get_prefix(key, scope=scope)
                    print(json.dumps(dict(data), indent=4))
                else:
                    val = await etcd.get(key, scope=scope)
                    if val is None:
                        sys.exit(1)
                    print(val)
            except Exception:
                log.exception('An error occurred.')
    with cli_ctx.logger:
        asyncio.run(_impl()) 
Example #9
Source File: cluster.py    From edgedb with Apache License 2.0 6 votes vote down vote up
def _init(self, pg_connector):
        if self._env:
            env = os.environ.copy()
            env.update(self._env)
        else:
            env = None

        init = subprocess.run(
            self._edgedb_cmd + ['--bootstrap'],
            stdout=sys.stdout, stderr=sys.stderr,
            env=env)

        if init.returncode != 0:
            raise ClusterError(
                f'edgedb-server --bootstrap failed with '
                f'exit code {init.returncode}') 
Example #10
Source File: device.py    From Facedancer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def emulate(self, *coroutines: Iterable[asyncio.coroutine]):
        """ Convenience method that runs a full method in a blocking manner.
        Performs connect, run, and then disconnect.

        Parameters:
            *coroutines -- any asyncio coroutines to be executed concurrently
                           with our emulation
        """

        self.connect()

        try:
            self.run_with(*coroutines)
        except KeyboardInterrupt:
            pass
        finally:
            self.disconnect()


    #
    # I/O interface.
    # 
Example #11
Source File: hb_sub_reindexing.py    From avrae with GNU General Public License v3.0 6 votes vote down vote up
def run():
    mdb = None
    if 'test' in sys.argv:
        import credentials

        mdb = motor.motor_asyncio.AsyncIOMotorClient(credentials.test_mongo_url).avrae
    else:
        mclient = motor.motor_asyncio.AsyncIOMotorClient(os.getenv('MONGO_URL', "mongodb://localhost:27017"))
        mdb = mclient[os.getenv('MONGO_DB', "avrae")]

    if 'bestiary' in sys.argv:
        input(f"Reindexing {mdb.name} bestiaries. Press enter to continue.")
        await migrate_bestiaries(mdb)

    if 'tome' in sys.argv:
        input(f"Reindexing {mdb.name} tomes. Press enter to continue.")
        await migrate_tomes(mdb)

    if 'pack' in sys.argv:
        input(f"Reindexing {mdb.name} packs. Press enter to continue.")
        await migrate_packs(mdb) 
Example #12
Source File: test_http.py    From filesystem_spec with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_async_this_thread(server):
    async def _():
        loop = asyncio.get_event_loop()
        fs = fsspec.filesystem("http", asynchronous=True, loop=loop)

        with pytest.raises(RuntimeError):
            # fails because client creation has not yet been awaited
            await fs._cat(server + "/index/realfile")

        await fs.set_session()  # creates client

        out = await fs._cat(server + "/index/realfile")
        del fs
        assert out == data

    asyncio.run(_()) 
Example #13
Source File: test_information.py    From bot with MIT License 6 votes vote down vote up
def test_user_command_helper_method_get_requests(self):
        """The helper methods should form the correct get requests."""
        test_values = (
            {
                "helper_method": self.cog.basic_user_infraction_counts,
                "expected_args": ("bot/infractions", {'hidden': 'False', 'user__id': str(self.member.id)}),
            },
            {
                "helper_method": self.cog.expanded_user_infraction_counts,
                "expected_args": ("bot/infractions", {'user__id': str(self.member.id)}),
            },
            {
                "helper_method": self.cog.user_nomination_counts,
                "expected_args": ("bot/nominations", {'user__id': str(self.member.id)}),
            },
        )

        for test_value in test_values:
            helper_method = test_value["helper_method"]
            endpoint, params = test_value["expected_args"]

            with self.subTest(method=helper_method, endpoint=endpoint, params=params):
                asyncio.run(helper_method(self.member))
                self.bot.api_client.get.assert_called_once_with(endpoint, params=params)
                self.bot.api_client.get.reset_mock() 
Example #14
Source File: nest_asyncio.py    From nest_asyncio with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _patch_asyncio():
    """
    Patch asyncio module to use pure Python tasks and futures,
    use module level _current_tasks, all_tasks and patch run method.
    """
    def run(future, *, debug=False):
        loop = asyncio.get_event_loop()
        loop.set_debug(debug)
        return loop.run_until_complete(future)

    if sys.version_info >= (3, 6, 0):
        asyncio.Task = asyncio.tasks._CTask = asyncio.tasks.Task = \
            asyncio.tasks._PyTask
        asyncio.Future = asyncio.futures._CFuture = asyncio.futures.Future = \
            asyncio.futures._PyFuture
    if sys.version_info < (3, 7, 0):
        asyncio.tasks._current_tasks = asyncio.tasks.Task._current_tasks  # noqa
        asyncio.all_tasks = asyncio.tasks.Task.all_tasks  # noqa
    if not hasattr(asyncio, '_run_orig'):
        asyncio._run_orig = getattr(asyncio, 'run', None)
        asyncio.run = run 
Example #15
Source File: test_information.py    From bot with MIT License 6 votes vote down vote up
def test_roles_command_command(self):
        """Test if the `role_info` command correctly returns the `moderator_role`."""
        self.ctx.guild.roles.append(self.moderator_role)

        self.cog.roles_info.can_run = unittest.mock.AsyncMock()
        self.cog.roles_info.can_run.return_value = True

        coroutine = self.cog.roles_info.callback(self.cog, self.ctx)

        self.assertIsNone(asyncio.run(coroutine))
        self.ctx.send.assert_called_once()

        _, kwargs = self.ctx.send.call_args
        embed = kwargs.pop('embed')

        self.assertEqual(embed.title, "Role information (Total 1 role)")
        self.assertEqual(embed.colour, discord.Colour.blurple())
        self.assertEqual(embed.description, f"\n`{self.moderator_role.id}` - {self.moderator_role.mention}\n") 
Example #16
Source File: test_duck_pond.py    From bot with MIT License 6 votes vote down vote up
def test_send_webhook_correctly_passes_on_arguments(self):
        """The `send_webhook` method should pass the arguments to the webhook correctly."""
        self.cog.webhook = helpers.MockAsyncWebhook()

        content = "fake content"
        username = "fake username"
        avatar_url = "fake avatar_url"
        embed = "fake embed"

        asyncio.run(self.cog.send_webhook(content, username, avatar_url, embed))

        self.cog.webhook.send.assert_called_once_with(
            content=content,
            username=username,
            avatar_url=avatar_url,
            embed=embed
        ) 
Example #17
Source File: security.py    From minikerberos with MIT License 6 votes vote down vote up
def run(self):
		req = self.construct_tgt_req()

		rep = await self.ksoc.sendrecv(req.dump(), throw = False)

		if rep.name != 'KRB_ERROR':	
			# user doesnt need preauth, but it exists
			return True
			
		elif rep.native['error-code'] != KerberosErrorCode.KDC_ERR_PREAUTH_REQUIRED.value:
			# any other error means user doesnt exist
			return False
			
		else:
			# preauth needed, only if user exists
			return True 
Example #18
Source File: security.py    From minikerberos with MIT License 5 votes vote down vote up
def run(self, cred: KerberosCredential, override_etype = [23]):
		"""
		override_etype: list : list of supported encryption types
		"""
		try:
			kcomm = AIOKerberosClient(cred, self.target)
			await kcomm.get_TGT(override_etype = override_etype, decrypt_tgt = False)
			return TGTTicket2hashcat(kcomm.kerberos_TGT)
		except Exception as e:
			logger.debug('Error while roasting client %s/%s Reason: %s' % (cred.domain, cred.username, str(e))) 
Example #19
Source File: bench.py    From grpclib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_grpclib_uvloop():
    import uvloop
    uvloop.install()

    asyncio.run(_grpclib_server()) 
Example #20
Source File: test_item_target.py    From ruia with Apache License 2.0 5 votes vote down vote up
def test_main():
    if sys.version_info[:2] == (3, 7):
        # Recommended for Python 3.7
        asyncio.run(main())
    else:
        loop = asyncio.new_event_loop()
        loop.run_until_complete(main()) 
Example #21
Source File: bench.py    From grpclib with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve_grpclib():
    asyncio.run(_grpclib_server()) 
Example #22
Source File: main.py    From pantalaimon with Apache License 2.0 5 votes vote down vote up
def main(context, log_level, debug_encryption, config, data_path):
    try:
        asyncio.run(daemon(context, log_level, debug_encryption, config, data_path))
    except (KeyboardInterrupt, asyncio.CancelledError):
        pass

    return 
Example #23
Source File: server.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def setup_test_cases(cases, conn, num_jobs, verbose=False):
    setup = get_test_cases_setup(cases)

    async def _run():
        if num_jobs == 1:
            # Special case for --jobs=1
            for _case, dbname, setup_script in setup:
                await _setup_database(dbname, setup_script, conn)
                if verbose:
                    print(f' -> {dbname}: OK', flush=True)
        else:
            async with taskgroup.TaskGroup(name='setup test cases') as g:
                # Use a semaphore to limit the concurrency of bootstrap
                # tasks to the number of jobs (bootstrap is heavy, having
                # more tasks than `--jobs` won't necessarily make
                # things faster.)
                sem = asyncio.BoundedSemaphore(num_jobs)

                async def controller(coro, dbname, *args):
                    async with sem:
                        await coro(dbname, *args)
                        if verbose:
                            print(f' -> {dbname}: OK', flush=True)

                for _case, dbname, setup_script in setup:
                    g.create_task(controller(
                        _setup_database, dbname, setup_script, conn))

    return asyncio.run(_run()) 
Example #24
Source File: nodes_manager.py    From PySyft with Apache License 2.0 5 votes vote down vote up
def _send_msg(self, message: bin, location):
        """ Forward a local syft request to the proper destination. """
        return asyncio.run(self._connection[location.id].send(message)) 
Example #25
Source File: testcase_unittest.py    From TestSlide with MIT License 5 votes vote down vote up
def test_has_mock_async_callable(self):
        self.mock_async_callable(SomeClass, "async_do_something").to_return_value(
            42
        ).and_assert_called_once()
        if sys.version_info >= (3, 7):
            self.assertEqual(asyncio.run(SomeClass.async_do_something()), 42)
        else:
            loop = asyncio.get_event_loop()
            result = loop.run_until_complete(SomeClass.async_do_something())
            loop.close()
            self.assertEqual(result, 42) 
Example #26
Source File: __init__.py    From TestSlide with MIT License 5 votes vote down vote up
def add_test_case(self, test_case, attr_name):
        """
        Add around hooks to context from given unittest.TestCase class. Only
        hooks such as setUp or tearDown will be called, no tests will be
        included.
        """

        def wrap_test_case(self, example):
            def test_test_slide(_):
                example()

            def exec_body(ns):
                ns.update({"test_test_slide": test_test_slide})

            # Build a child class of given TestCase, with a defined test that
            # will run TestSlide example.
            test_slide_test_case = types.new_class(
                "TestSlideTestCase", bases=(test_case,), exec_body=exec_body
            )

            # This suite will only contain TestSlide's example test.
            test_suite = unittest.TestLoader().loadTestsFromName(
                "test_test_slide", test_slide_test_case
            )
            setattr(self, attr_name, list(test_suite)[0])
            result = _TestSlideTestResult()
            test_suite(result=result)
            if not result.wasSuccessful():
                result.aggregated_exceptions.raise_correct_exception()

        self.around_functions.append(wrap_test_case) 
Example #27
Source File: __init__.py    From TestSlide with MIT License 5 votes vote down vote up
def run(self):
        try:
            if self.example.skip:
                raise Skip()
            context_data = _ContextData(self.example, self.formatter)
            if self.example.is_async:
                self._async_run_all_hooks_and_example(context_data)
            else:
                self._sync_run_all_hooks_and_example(context_data)
        finally:
            sys.stdout.flush()
            sys.stderr.flush()
            testslide.mock_callable.unpatch_all_callable_mocks()
            testslide.mock_constructor.unpatch_all_constructor_mocks()
            testslide.patch_attribute.unpatch_all_mocked_attributes() 
Example #28
Source File: __init__.py    From TestSlide with MIT License 5 votes vote down vote up
def _async_run_all_hooks_and_example(self, context_data):
        coro = self._real_async_run_all_hooks_and_example(context_data)
        with self._raise_if_asyncio_warnings(context_data):
            if sys.version_info < (3, 7):
                loop = asyncio.events.new_event_loop()
                try:
                    loop.set_debug(True)
                    loop.run_until_complete(coro)
                finally:
                    try:
                        loop.run_until_complete(loop.shutdown_asyncgens())
                    finally:
                        loop.close()
            else:
                asyncio.run(coro, debug=True) 
Example #29
Source File: contact_self.py    From python-wechaty with Apache License 2.0 5 votes vote down vote up
def name(self, name: Optional[str]) -> str:
        puppet_id: str
        try:
            puppet_id = self.puppet.self_id()
        except Exception as e:
            raise Exception('Can not get qr_code, user might be either not logged in or already logged out')

        if self.contact_id != puppet_id:
            raise Exception('only can get qr_code for the login user self')

        return asyncio.run(self.puppet.contact_self_name(name)) 
Example #30
Source File: specter.py    From specter-diy with MIT License 5 votes vote down vote up
def start(self):
        # start the GUI
        self.gui.start()
        # register coroutines for all hosts
        for host in self.hosts:
            host.start(self)
        asyncio.run(self.setup())