Example #1
0
def main():
    print('-' * 80)
    print(str.format(
        '[*] coroutine is coroutine function => {}',
        inspect.iscoroutinefunction(coroutine)
    ))
    print(str.format(
        '[*] subcoroutine is coroutine function => {}',
        inspect.iscoroutinefunction(subcoroutine)
    ))
    sub1 = subcoroutine('Subroutine')
    print(str.format(
        '[*] sub1 is coroutine object => {}', inspect.iscoroutine(sub1)
    ))
    coro1 = coroutine('Coroutine')
    print(str.format(
        '[*] coro1 is coroutine object => {}', inspect.iscoroutine(coro1)
    ))

    print('-' * 80)
    print(str.format(
        '[*] CoroutineClass is sub-class of Awaitable class => {}',
        issubclass(CoroutineClass, Awaitable)
    ))
    c1 = CoroutineClass('Coroutine #1', ['A', 'B', 'C'])
    print(str.format(
        '[*] c1 is awaitable object => {}', inspect.isawaitable(c1)
    ))
    print(str.format(
        '[*] c1 is instance of Awaitable class => {}',
        isinstance(c1, Awaitable)
    ))

    print('-' * 80)
Example #2
0
 async def processor(handler):
     if iscoroutinefunction(h):
         await h()
     else:
         h()
     if iscoroutinefunction(handler):
         return await handler()
     else:
         return handler()
Example #3
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Check to see if the callback is a coroutine function, and if it is
        # we'll wrap it so that it gets called with the global event loop.
        if (inspect.iscoroutinefunction(self.callback) or
                inspect.iscoroutinefunction(
                    getattr(self.callback, "__wrapped__", None))):
            original_callback = self.callback

            @functools.wraps(original_callback)
            def wrapper(*args, **kwargs):
                loop = asyncio.get_event_loop()
                main_t = asyncio.ensure_future(
                    original_callback(*args, **kwargs),
                    loop=loop,
                )

                try:
                    try:
                        loop.run_until_complete(main_t)
                    except KeyboardInterrupt:
                        main_t.cancel()
                        # This won't actually run forever because the call to
                        # loop.run_until_complete added a callback to the
                        # future that will stop the loop once main_t has
                        # finished and return control back to this function.
                        loop.run_forever()

                    # Try to clean up all of the tasks by waiting for any
                    # existing tasks to finish. Ideally the main function
                    # triggered everything to try and finish up and exit on
                    # it's own. However, if it hadn't then we'll cancel
                    # everything after we wait a small amount of time.
                    cleanup_t = asyncio.ensure_future(
                        cleanup(loop, timeout=15),
                        loop=loop,
                    )
                    try:
                        loop.run_until_complete(cleanup_t)
                    except KeyboardInterrupt:
                        # We got another KeyboardInterrupt while waiting on the
                        # pending tasks to finish. We'll cancel that cleanup
                        # job and let everything fall through to the final
                        # cleanup that just cancels everything.
                        cleanup_t.cancel()
                        # Like above, this will not actually run forever
                        # because of callback added to the cleanup_t task.
                        loop.run_forever()
                finally:
                    # Just cancel everything at this point, we don't want
                    # anything to still be executing once this is over.
                    loop.run_until_complete(cleanup(loop, cancel=True))
                    loop.stop()

            self.callback = wrapper
Example #4
0
File: meta.py Project: hiway/curio
    def __init__(cls, name, bases, methods):
        coros = {}
        for base in reversed(cls.__mro__):
            coros.update((name, val) for name, val in vars(base).items()
                         if inspect.iscoroutinefunction(val))

        for name, val in vars(cls).items():
            if name in coros and not inspect.iscoroutinefunction(val):
                raise TypeError('Must use async def %s%s' % (name, inspect.signature(val)))
        super().__init__(name, bases, methods)
Example #5
0
 def register(self, callback):
     wrapped = callback
     if not inspect.iscoroutinefunction(wrapped):
         wrapped = asyncio.coroutine(wrapped)
     self._callbacks.append(wrapped)
     # Always return the decorated function unchanged
     return callback
Example #6
0
 def __setitem__(self, name, value):
     sync_func = None
     async_func = None
     previous_func = self.get(name)
     if previous_func:
         if inspect.iscoroutinefunction(previous_func):
             async_func = previous_func
         else:
             sync_func = previous_func
         if inspect.iscoroutinefunction(value):
             async_func = value
         else:
             sync_func = value
     if sync_func and async_func:
         value = awaitable(sync_func)(async_func)
     super().__setitem__(name, value)
Example #7
0
 def __init__(self, *args, **kwargs):
     unittest.TestCase.__init__(self, *args, **kwargs)
     for s in dir(self):
         attr = getattr(self, s, None)
         # If s is an instance method and starts with 'test_', synchelp wrap it
         if inspect.iscoroutinefunction(attr) and s.startswith('test_') and inspect.ismethod(attr):
             setattr(self, s, s_glob.synchelp(attr))
Example #8
0
def command_operator(func):
    if iscoroutinefunction(func):
        async def async_decorator(self, *args, **kwargs):
            method, params = self.get_params(func.__name__, **kwargs)

            if method == "post":
                response = await self.api_call(data=params)
            elif method == "get":
                response = await self.api_call(params=params)
            else:
                raise PoloniexError("Not available method '{}'".format(method))

            return self.response_handler(response)

        return async_decorator
    else:
        def decorator(self, *args, **kwargs):
            method, params = self.get_params(func.__name__, **kwargs)

            if method == "post":
                response = self.api_call(data=params)
            elif method == "get":
                response = self.api_call(params=params)
            else:
                raise PoloniexError("Not available method '{}'".format(method))

            return self.response_handler(response)

        return decorator
Example #9
0
    def unsubscribe(self, subscription=None):
        """
        Removes the given subscription, so that it no longer gets updated::

            subs = myobj.subscribe()
            myobj.unsubscribe(subs)

        If no argument is given, removes the default subscription created by `get()`.
        If none exists, then does nothing.

        Args:
            subscription (optional):
                Anything that was passed into/returned from :func:`subscribe`.

        """
        if subscription is None:
            if self.__defaultSubscription is not None:
                self.__splog.debug("Removing default subscription")
                self.unsubscribe(self.__defaultSubscription)
                self.__defaultSubscription = None
            else:
                # Otherwise, do nothing
                self.__splog.debug(
                    "Unsubscribe called, but no default subscription is active. Doing nothing."
                )
        else:
            if callable(getattr(subscription, "put_nowait", None)):
                self.__splog.debug("Removing subscription %s", subscription)
                self.__subscriptions.remove(subscription)
            elif inspect.iscoroutinefunction(subscription):
                self.__splog.debug("Removing async callback %s", subscription)
                self.__cocallbacks.remove(subscription)
            else:
                self.__splog.debug("Removing callback %s", subscription)
                self.__callbacks.remove(subscription)
Example #10
0
            async def _bound_coroutine_func(*args, **kwargs):
                coroutine = func(*args, **kwargs)
                frame = coroutine.cr_frame

                if frame in self._frames:
                    errmsg = 'cannot reenter the same frame(%s)' % frame
                    raise PillarError(errmsg)

                assert frame not in self._frames
                self._frames[frame] = {}
                for k, v in bindings:
                    self.push(frame, k, v)

                ret = None
                try:
                    ret = await coroutine
                finally:
                    self.clear_context(frame)

                    if exit_callback:
                        exc_type, exc_val, tb = sys.exc_info()
                        if iscoroutinefunction(exit_callback):
                            await exit_callback(exc_type, exc_val, tb)
                        else:
                            exit_callback(exc_type, exc_val, tb)

                return ret
Example #11
0
    def outer(func: Callable[..., T_Retval],
              executor: Union[Executor, str] = None) -> Callable[..., Awaitable[T_Retval]]:
        def wrapper(*args, **kwargs):
            try:
                loop = get_event_loop()
            except RuntimeError:
                # Event loop not available -- we're in a worker thread
                return func(*args, **kwargs)

            # Resolve the executor resource name to an Executor instance
            if isinstance(executor, str):
                try:
                    ctx = next(obj for obj in args[:2] if isinstance(obj, Context))
                except StopIteration:
                    raise RuntimeError('the callable needs to be called with a Context as the '
                                       'first or second positional argument')

                _executor = ctx.require_resource(Executor, executor)
            else:
                _executor = executor

            callback = partial(func, *args, **kwargs)
            return loop.run_in_executor(_executor, callback)

        assert check_argument_types()
        assert not inspect.iscoroutinefunction(func), \
            'Cannot wrap coroutine functions to be run in an executor'
        return wraps(func)(wrapper)
Example #12
0
    def respond(self, ch, user, msg):
        for fn in self.response_fns:
            groups = self.check_words(fn, msg) or self.check_regex(fn, msg)
            if not groups:
                continue

            if hasattr(fn, 'auth') and not users.UsersDal.is_admin(user):
                self.send(ch, messages.NO_AUTHORIZATION)

                for channel in channels.ChannelsDal.read(admin_only=True):
                    c = helper.get_channel_or_fail(logger, self.slack, channel)
                    self.send(c, messages.UNAUTHORIZED_USAGE(user, msg))

                continue

            if inspect.iscoroutinefunction(fn):
                asyncio.ensure_future(fn(self, ch, user, groups))
            else:
                fn(self, ch, user, groups)

            for channel, msgs in self.buffer.items():
                self.send_now(channel, '\n'.join(msgs))
            self.reset_buffer()

            return True
Example #13
0
        def wrapper(func):
            if not iscoroutinefunction(func):
                print('Handler for command "{}" must be a coroutine'.format(
                    name))
                sys.exit(-1)
            if not func.__doc__:
                print('Missing documentation in command "{}"'.format(
                    name))
                sys.exit(-1)
            func_name = '_cmd_' + func.__name__
            while func_name in cls._commands:
                func_name += '_'

            setattr(cls, func_name, func)
            cls._commands[func_name] = Command(
                func_name, arg_func, aliases,
                section or func.__module__.split(".")[-1],
                utils.cmd_help_format(func.__doc__), context, perm_func)
            # associate the given aliases with the command
            for alias in aliases:
                if alias in cls._aliases:
                    print('The alias "{}"'.format(alias),
                          'is already in use for command',
                          cls._aliases[alias][:5].strip('_'))
                    sys.exit(-1)
                if cls._CMD_NAME_REGEX.match(alias) is None:
                    print('The alias "{}"'.format(alias),
                          ('is invalid. Aliases must only contain lowercase'
                           ' letters or numbers.'))
                    sys.exit(-1)
                cls._aliases[alias] = func_name
Example #14
0
def pytest_collection_modifyitems(items):
    """add asyncio marker to all async tests"""
    for item in items:
        if inspect.iscoroutinefunction(item.obj):
            item.add_marker('asyncio')
        if hasattr(inspect, 'isasyncgenfunction'):
            # double-check that we aren't mixing yield and async def
            assert not inspect.isasyncgenfunction(item.obj)
Example #15
0
 def __new__(cls, name, bases, attrs):
     for key, obj in attrs.items():
         if key.startswith('test_'):
             if inspect.iscoroutinefunction(obj):
                 attrs[key] = run_in_loop(obj)
             else:
                 attrs[key] = obj
     return super().__new__(cls, name, bases, attrs)
    def consume(self, message: t.Dict):
        # todo: validation
        fn = getattr(self.handler, message["method"])

        if inspect.iscoroutinefunction(fn):
            return asyncio.ensure_future(fn(**message["params"]), loop=self.loop)
        else:
            return self.loop.run_in_executor(None, fn, **message["params"])
Example #17
0
File: utils.py Project: Tygs/tygs
def ensure_coroutine(callable_obj):
    if not callable(callable_obj):
        raise TypeError("callable_obj must be an coroutine or a callable. "
                        "Did you try to call a non coroutine "
                        "by mistake?")

    # If a coroutine function is passed instead of a coroutine, call it
    # so everything is a coroutine.
    if inspect.iscoroutinefunction(callable_obj):
        return callable_obj

    if hasattr(callable_obj, '__call__') and \
            inspect.iscoroutinefunction(callable_obj.__call__):
        return callable_obj

    # If it's a normal callable is passed, wrap it as a coroutine.
    return asyncio.coroutine(callable_obj)
def iscoroutinefunction(func):
    """Return True if func is a decorated coroutine function.

    Note: copied and modified from Python 3.5's builtin couroutines.py to avoid import asyncio directly,
    which in turns also initializes the "logging" module as side-effect (see issue #8).
    """
    return (getattr(func, '_is_coroutine', False) or
           (hasattr(inspect, 'iscoroutinefunction') and inspect.iscoroutinefunction(func)))
Example #19
0
async def publish_async(topic, *args, **kwargs):
    from communication.server import loop
    futures = []
    for sub in _subscriptions.get(topic, []):
        future = sub.callback(*args, **kwargs)
        if inspect.iscoroutinefunction(sub.callback):
            futures.append(future)
    return await asyncio.gather(*futures)
Example #20
0
def iscoroutinefunction(func):
    '''
    Modified test for a coroutine function with awareness of functools.partial
    '''
    if isinstance(func, partial):
        return iscoroutinefunction(func.func)
    if hasattr(func, '__func__'):
        return iscoroutinefunction(func.__func__)
    return inspect.iscoroutinefunction(func) or hasattr(func, '_awaitable') or _isasyncgenfunction(func)
Example #21
0
 async def wrapped(self, request):
     has_perm = await permits(request, role)
     if not has_perm:
         message = 'User has no role {}'.format(role)
         raise web.HTTPForbidden(body=message.encode())
     if inspect.iscoroutinefunction(f):
         return await f(self, request)
     else:
         return f(self, request)
Example #22
0
 def invoke_sync(self, *args, **kwargs):
     """Invokes the task synchronously and returns the result."""
     if inspect.iscoroutinefunction(self.invoke):
         loop = asyncio.get_event_loop()
         ret_value = loop.run_until_complete(self.invoke(*args, **kwargs))
         loop.close()
         return ret_value
     else:
         return self.invoke(*args, **kwargs)
Example #23
0
def publish(topic, *args, **kwargs):
    from communication.server import loop
    tasks = []
    for sub in _subscriptions.get(topic, []):
        res = sub.callback(*args, **kwargs)
        if inspect.iscoroutinefunction(sub.callback):
            task = asyncio.ensure_future(res, loop=loop)
            tasks.append(task)
    return tasks
Example #24
0
async def callEvents(eventName, commandObjects, *args, **kwargs):
    calledCount = 0
    for method,commandObject in COCallablesIterator(commandObjects, eventName):
        if not inspect.iscoroutine(method) and not inspect.iscoroutinefunction(method):
            method(*args, **kwargs)
        else:
            await method(*args, **kwargs)
        calledCount += 1
    return calledCount
Example #25
0
def is_coroutine(callable):
    if hasattr(callable, "_is_coroutine"):
        return True

    if hasattr(inspect, "iscoroutinefunction") and\
        inspect.iscoroutinefunction(callable): #@UndefinedVariable
        return True

    return False
Example #26
0
 def __getattr__(self, item):
     orig = getattr(self._wrappedobj, item)
     if inspect.iscoroutinefunction(orig):
         @functools.wraps(orig)
         def wrapped(*args, **kwargs):
             """Gets the waitable and tells the event loop to run it"""
             waitable = orig(*args, **kwargs)
             return self._loop.run_until_complete(waitable)
         return wrapped
     return orig
Example #27
0
 async def handle_class(cls):
     meth = web.ctx.method
     if meth == "HEAD" and not hasattr(cls, meth):
         meth = "GET"
     if not hasattr(cls, meth):
         raise web.nomethod(cls)
     tocall = getattr(cls(), meth)
     if iscoroutinefunction(tocall):
         return await tocall(*args)
     return tocall(*args)
Example #28
0
def wrapsync(func):
    """Turns synchronous function into asynchronous."""

    if iscoroutinefunction(func):
        return func

    async def inner(*args, **kwargs):
        return func(*args, **kwargs)

    return update_wrapper(inner, func)
Example #29
0
def is_docable(attr):
    if isinstance(attr, inspect.Attribute):
        member = attr.object
    else:
        member = attr
    if isinstance(member, commands.Command) or isinstance(member, dutils.EventLoop):
        return True
    return inspect.iscoroutinefunction(member) or inspect.isfunction(member) or inspect.ismethod(member) or \
        inspect.isasyncgenfunction(member) or inspect.isgeneratorfunction(member) or inspect.isclass(member) or \
        isinstance(member, property)
def typed(func):
    signature = inspect.signature(func)
    type_hints = typing.get_type_hints(func)
    types_in = tuple(get_types_in(type_hints, func))
    type_out = get_type_out(type_hints, func)

    def check_in(args, kwargs):
        bound = signature.bind(*args, **kwargs)
        bound.apply_defaults()
        # Check incoming arguments.
        for name, type_in in types_in:
            # An empty *args, for example, will not appear in the bound
            # arguments list, so we much check for that.
            if name in bound.arguments:
                value = bound.arguments[name]
                if not issubclass(type(value), type_in):
                    raise ArgumentTypeError(func, name, value, type_in)

    def check_out(result):
        if not issubclass(type(result), type_out):
            raise ReturnTypeError(func, result, type_out)

    if inspect.iscoroutinefunction(func):
        if type_out is None:
            @wraps(func)
            async def checked(*args, **kwargs):
                check_in(args, kwargs)
                # No annotation on return value.
                return await func(*args, **kwargs)

        else:
            @wraps(func)
            async def checked(*args, **kwargs):
                check_in(args, kwargs)
                result = await func(*args, **kwargs)
                check_out(result)
                return result

    else:
        if type_out is None:
            @wraps(func)
            def checked(*args, **kwargs):
                check_in(args, kwargs)
                # No annotation on return value.
                return func(*args, **kwargs)

        else:
            @wraps(func)
            def checked(*args, **kwargs):
                check_in(args, kwargs)
                result = func(*args, **kwargs)
                check_out(result)
                return result

    return checked
Example #31
0
 def __init__(self, callback):
     self.callback = callback
     self.is_async = inspect.iscoroutinefunction(callback)
Example #32
0
def generate(t: Any) -> None:
    print("")
    class_name = short_name(t)
    base_class = t.__bases__[0].__name__
    if class_name in ["Page", "BrowserContext", "Browser"]:
        base_sync_class = "SyncContextManager"
    elif base_class in ["ChannelOwner", "object"]:
        base_sync_class = "SyncBase"
    else:
        base_sync_class = base_class
    print(f"class {class_name}({base_sync_class}):")
    print("")
    documentation_provider.print_events(class_name)
    for [name, type] in get_type_hints(t, api_globals).items():
        print("")
        print("    @property")
        print(f"    def {name}(self) -> {process_type(type)}:")
        documentation_provider.print_entry(class_name, name, {"return": type},
                                           True)
        [prefix, suffix] = return_value(type)
        prefix = "        return " + prefix + f"self._impl_obj.{name}"
        print(f"{prefix}{suffix}")
    for [name, value] in t.__dict__.items():
        if name.startswith("_"):
            continue
        if str(value).startswith("<property"):
            value = value.fget
            print("")
            print("    @property")
            print(
                f"    def {name}({signature(value, len(name) + 9)}) -> {return_type(value)}:"
            )
            documentation_provider.print_entry(
                class_name, name, get_type_hints(value, api_globals), True)
            [prefix, suffix
             ] = return_value(get_type_hints(value, api_globals)["return"])
            prefix = "        return " + prefix + f"self._impl_obj.{name}"
            print(f"{prefix}{arguments(value, len(prefix))}{suffix}")
    for [name, value] in t.__dict__.items():
        if isinstance(value, FunctionType) and "remove_listener" != name:
            # List of dunder methods to allow without docs
            allow_without_docs_methods = [
                "__getitem__",
            ]
            if name.startswith("_") and name not in allow_without_docs_methods:
                continue
            is_async = inspect.iscoroutinefunction(value)
            return_type_value = return_type(value)
            return_type_value = re.sub(r"\"([^\"]+)Impl\"", r"\1",
                                       return_type_value)
            print("")
            print(
                f"    def {name}({signature(value, len(name) + 9)}) -> {return_type_value}:"
            )
            # Allow dunder methods without docs
            if name not in allow_without_docs_methods:
                documentation_provider.print_entry(
                    class_name, name, get_type_hints(value, api_globals))
            if "expect_" in name:
                print(
                    f"        return EventContextManager(self, self._impl_obj.{name}({arguments(value, 12)}).future)"
                )
            else:
                [prefix, suffix] = return_value(
                    get_type_hints(value, api_globals)["return"])
                if is_async:
                    prefix = (
                        prefix +
                        f'self._sync("{to_snake_case(class_name)}.{name}", self._impl_obj.{name}('
                    )
                    suffix = "))" + suffix
                else:
                    prefix = prefix + f"self._impl_obj.{name}("
                    suffix = ")" + suffix

                print(f"""
        return {prefix}{arguments(value, len(prefix))}{suffix}""")
    print("")
    print(f"mapping.register({class_name}Impl, {class_name})")
Example #33
0
def pytest_collection_modifyitems(items):
    """add asyncio marker to all async tests"""
    for item in items:
        if inspect.iscoroutinefunction(item.obj):
            item.add_marker('asyncio')
Example #34
0
 def __new__(meta, clsname, bases, attributes):
     if '__init__' in attributes and not inspect.iscoroutinefunction(
             attributes['__init__']):
         raise TypeError('__init__ must be a coroutine')
     return super().__new__(meta, clsname, bases, attributes)
Example #35
0
 def __call__(self, func):
     if inspect.isclass(func):
         return self.decorate_class(func)
     elif inspect.iscoroutinefunction(func):
         return self.decorate_coroutine(func)
     return self.decorate_callable(func)
Example #36
0
    async def on_request(self, req):
        """
        on_request(req) is called when a request is received by the service.
        """
        if req.service_identification != self.identification:
            logger.error("Dropping request for wrong identification")
            return

        method = req.method

        try:
            callback = self._actions[method]
        except KeyError:
            logger.error("No such method: %s.%s", self, method)
            await self.reply_error_to(
                req, cellaserv.client.Reply.Error.NoSuchMethod, method)
            return

        try:
            if req.data != b"":
                data = json.loads(req.data.decode())
            else:
                data = None
        except Exception:
            logger.error("Bad arguments formatting: %s",
                         _request_to_string(req),
                         exc_info=True)
            await self.reply_error_to(
                req, cellaserv.client.Reply.Error.BadArguments, req.data)
            return

        try:
            logger.debug(
                "Calling %s/%s.%s(%s)...",
                self.service_name,
                self.identification,
                method,
                data,
            )

            # Guess type of arguments
            if type(data) is list:
                args = data
                kwargs = {}
            elif type(data) is dict:
                args = []
                kwargs = data
            else:
                args = []
                kwargs = {}

            if inspect.iscoroutinefunction(callback):
                reply_data = await callback(*args, **kwargs)
            else:
                reply_data = callback(*args, **kwargs)

            logger.debug(
                "Called %s/%s.%s(%s) = %s",
                self.service_name,
                self.identification,
                method,
                data,
                reply_data,
            )
            # Method may, or may not return something. If it returns some data,
            # it must be encoded in json.
            if reply_data is not None:
                reply_data = json.dumps(reply_data).encode()
        except Exception as e:
            await self.reply_error_to(req, cellaserv.client.Reply.Error.Custom,
                                      str(e))
            logger.error("Exception during %s",
                         _request_to_string(req),
                         exc_info=True)
            return

        await self.reply_to(req, reply_data)
Example #37
0
def pytest_collection_modifyitems(session, config, items):
    for item in items:
        if isinstance(item, pytest.Function) and inspect.iscoroutinefunction(
                item.function):
            item.add_marker(pytest.mark.asyncio)
Example #38
0
    async def __aenter__(self) -> None:
        await binding(url=self.url, **self.bindings)

        if self.initcmd:
            if callable(self.initcmd) and iscoroutinefunction(self.initcmd):
                await self.initcmd()
Example #39
0
 def is_coroutine_fixture(self):
     """
     True if the fixture is defined with 'async def'.
     """
     return inspect.iscoroutinefunction(inspect.unwrap(self.fn))
Example #40
0
def connect_with_tkviewer(f,
                          conn_factory=conn.CozmoConnection,
                          connector=None,
                          force_on_top=False):
    '''Setup a connection to a device and run a user function while displaying Cozmo's camera.

    This display a Tk window on the screen showing a view of Cozmo's camera.
    It will return an error if the current system does not support Tk.

    The function may be either synchronous or asynchronous (defined
    used ``async def``).

    The function must accept a :class:`cozmo.CozmoConnection` object as
    its only argument.
    This call will block until the supplied function completes.

    Args:
        f (callable): The function to execute
        conn_factory (callable): Override the factory function to generate a
            :class:`cozmo.conn.CozmoConnection` (or subclass) instance.
        connector (:class:`DeviceConnector`): Optional instance of a DeviceConnector
            subclass that handles opening the USB connection to a device.
            By default it will connect to the first Android or iOS device that
            has the Cozmo app running in SDK mode.
        force_on_top (bool): Specifies whether the window should be forced on top of all others
    '''
    try:
        from . import tkview
    except ImportError as exc:
        tkview = exc

    if isinstance(tkview, Exception):
        raise NotImplementedError(
            'tkviewer not available on this platform; '
            'make sure Tkinter, NumPy and Pillow packages are installed (%s)' %
            tkview)

    viewer = tkview.TkImageViewer(force_on_top=force_on_top)

    loop = asyncio.new_event_loop()
    abort_future = concurrent.futures.Future()

    async def view_connector(coz_conn):
        try:
            await viewer.connect(coz_conn)

            if inspect.iscoroutinefunction(f):
                await f(coz_conn)
            else:
                await coz_conn._loop.run_in_executor(None, f,
                                                     base._SyncProxy(coz_conn))
        finally:
            viewer.disconnect()

    try:
        if not inspect.iscoroutinefunction(f):
            conn_factory = functools.partial(conn_factory,
                                             _sync_abort_future=abort_future)
        lt = _LoopThread(loop,
                         f=view_connector,
                         conn_factory=conn_factory,
                         connector=connector)
        lt.start()
        viewer.mainloop()
    except BaseException as e:
        abort_future.set_exception(exceptions.SDKShutdown(repr(e)))
        raise
    finally:
        lt.stop()
Example #41
0
def pytest_collection_modifyitems(items: List[_pytest.nodes.Item]) -> None:
    for item in items:
        if iscoroutinefunction(item.obj):
            item.add_marker(pytest.mark.asyncio)
Example #42
0
    def setup_once():
        # type: () -> None
        import tornado  # type: ignore

        tornado_version = getattr(tornado, "version_info", None)
        if tornado_version is None or tornado_version < (5, 0):
            raise RuntimeError("Tornado 5+ required")

        if not HAS_REAL_CONTEXTVARS:
            # Tornado is async. We better have contextvars or we're going to leak
            # state between requests.
            raise RuntimeError(
                "The tornado integration for Sentry requires Python 3.6+ or the aiocontextvars package"
            )

        ignore_logger("tornado.application")
        ignore_logger("tornado.access")

        old_execute = RequestHandler._execute

        awaitable = iscoroutinefunction(old_execute)

        if awaitable:
            # Starting Tornado 6 RequestHandler._execute method is a standard Python coroutine (async/await)
            # In that case our method should be a coroutine function too
            async def sentry_execute_request_handler(self, *args, **kwargs):
                # type: (Any, *List, **Any) -> Any
                hub = Hub.current
                integration = hub.get_integration(TornadoIntegration)
                if integration is None:
                    return await old_execute(self, *args, **kwargs)

                weak_handler = weakref.ref(self)

                with Hub(hub) as hub:
                    with hub.configure_scope() as scope:
                        scope.clear_breadcrumbs()
                        scope.add_event_processor(_make_event_processor(weak_handler))
                    return await old_execute(self, *args, **kwargs)

        else:

            @coroutine  # type: ignore
            def sentry_execute_request_handler(self, *args, **kwargs):
                hub = Hub.current
                integration = hub.get_integration(TornadoIntegration)
                if integration is None:
                    return old_execute(self, *args, **kwargs)

                weak_handler = weakref.ref(self)

                with Hub(hub) as hub:
                    with hub.configure_scope() as scope:
                        scope.add_event_processor(_make_event_processor(weak_handler))
                    result = yield from old_execute(self, *args, **kwargs)
                    return result

        RequestHandler._execute = sentry_execute_request_handler

        old_log_exception = RequestHandler.log_exception

        def sentry_log_exception(self, ty, value, tb, *args, **kwargs):
            # type: (Any, type, BaseException, Any, *Any, **Any) -> Optional[Any]
            _capture_exception(ty, value, tb)
            return old_log_exception(self, ty, value, tb, *args, **kwargs)

        RequestHandler.log_exception = sentry_log_exception
def generate(t: Any) -> None:
    print("")
    class_name = short_name(t)
    base_class = t.__bases__[0].__name__
    base_sync_class = (
        "AsyncBase"
        if base_class == "ChannelOwner" or base_class == "object"
        else base_class
    )
    print(f"class {class_name}({base_sync_class}):")
    print("")
    print(f"    def __init__(self, obj: {class_name}Impl):")
    print("        super().__init__(obj)")
    for [name, type] in get_type_hints(t, api_globals).items():
        print("")
        print("    @property")
        print(f"    def {name}(self) -> {process_type(type)}:")
        documentation_provider.print_entry(class_name, name, {"return": type})
        [prefix, suffix] = return_value(type)
        prefix = "        return " + prefix + f"self._impl_obj.{name}"
        print(f"{prefix}{suffix}")
    for [name, value] in t.__dict__.items():
        if name.startswith("_"):
            continue
        if not name.startswith("_") and str(value).startswith("<property"):
            value = value.fget
            print("")
            print("    @property")
            print(
                f"    def {name}({signature(value, len(name) + 9)}) -> {return_type(value)}:"
            )
            documentation_provider.print_entry(
                class_name, name, get_type_hints(value, api_globals)
            )
            [prefix, suffix] = return_value(
                get_type_hints(value, api_globals)["return"]
            )
            prefix = "        return " + prefix + f"self._impl_obj.{name}"
            print(f"{prefix}{arguments(value, len(prefix))}{suffix}")
    for [name, value] in t.__dict__.items():
        if (
            not name.startswith("_")
            and isinstance(value, FunctionType)
            and "expect_" not in name
            and "remove_listener" != name
        ):
            print("")
            if inspect.iscoroutinefunction(value):
                print(
                    f"    async def {name}({signature(value, len(name) + 9)}) -> {return_type(value)}:"
                )
                documentation_provider.print_entry(
                    class_name, name, get_type_hints(value, api_globals)
                )
                [prefix, suffix] = return_value(
                    get_type_hints(value, api_globals)["return"]
                )
                prefix = "        return " + prefix + f"await self._impl_obj.{name}("
                suffix = ")" + suffix
                print(f"{prefix}{arguments(value, len(prefix))}{suffix}")
            else:
                print(
                    f"    def {name}({signature(value, len(name) + 9)}) -> {return_type(value)}:"
                )
                documentation_provider.print_entry(
                    class_name, name, get_type_hints(value, api_globals)
                )
                [prefix, suffix] = return_value(
                    get_type_hints(value, api_globals)["return"]
                )
                prefix = "        return " + prefix + f"self._impl_obj.{name}("
                suffix = ")" + suffix
                print(f"{prefix}{arguments(value, len(prefix))}{suffix}")
        if "expect_" in name:
            print("")
            return_type_value = return_type(value)
            return_type_value = re.sub(r"\"([^\"]+)Impl\"", r"\1", return_type_value)
            event_name = re.sub(r"expect_(.*)", r"\1", name)
            event_name = re.sub(r"_", "", event_name)
            event_name = re.sub(r"consolemessage", "console", event_name)

            print(
                f"""    def {name}({signature(value, len(name) + 9)}) -> Async{return_type_value}:
        \"\"\"{class_name}.{name}

        Returns context manager that waits for ``event`` to fire upon exit. It passes event's value
        into the ``predicate`` function and waits for the predicate to return a truthy value. Will throw
        an error if the page is closed before the ``event`` is fired.

        async with page.expect_{event_name}() as event_info:
            await page.click("button")
        value = event_info.value

        Parameters
        ----------
        predicate : Optional[typing.Callable[[Any], bool]]
            Predicate receiving event data.
        timeout : Optional[int]
            Maximum wait time in milliseconds, defaults to 30 seconds, pass `0` to disable the timeout.
            The default value can be changed by using the browserContext.setDefaultTimeout(timeout) or
            page.setDefaultTimeout(timeout) methods.
        \"\"\""""
            )

            wait_for_method = "waitForEvent(event, predicate, timeout)"
            if event_name == "request":
                wait_for_method = "waitForRequest(url, predicate, timeout)"
            elif event_name == "response":
                wait_for_method = "waitForResponse(url, predicate, timeout)"
            elif event_name == "loadstate":
                wait_for_method = "waitForLoadState(state, timeout)"
            elif event_name == "navigation":
                wait_for_method = "waitForNavigation(url, waitUntil, timeout)"
            elif event_name != "event":
                print(f'        event = "{event_name}"')

            print(
                f"        return AsyncEventContextManager(self._impl_obj.{wait_for_method})"
            )

    print("")
    print(f"mapping.register({class_name}Impl, {class_name})")
Example #44
0
 def is_coroutine_function(self) -> bool:
     return inspect.iscoroutinefunction(self.target)
Example #45
0
    async def list_keys(self, prefix='', deliminator='', suffix='', include_stats=False, callback=None, bucket=None, limit=None):
        """ return keys matching the arguments
        """
        if not bucket:
            log.error("list_keys - bucket not set")
            raise HTTPInternalServerError()

        log.info(f"list_keys('{prefix}','{deliminator}','{suffix}', include_stats={include_stats}")
        if deliminator and deliminator != '/':
            msg = "Only '/' is supported as deliminator"
            log.warn(msg)
            raise HTTPBadRequest(reason=msg)
        if include_stats:
            # use a dictionary to hold return values
            key_names = {}
        else:
            # just use a list
            key_names = []
        continuation_token = None
        page_result_count = 1000  # compatible with what S3 uses by default
        if prefix == '':
            prefix = None  # azure sdk expects None for no prefix
        try:
            async with self._client.get_container_client(container=bucket) as container_client:
                while True:
                    log.info(f"list_blobs: {prefix} continuation_token: {continuation_token}")
                    keyList = container_client.walk_blobs(name_starts_with=prefix, delimiter=deliminator, results_per_page=page_result_count).by_page(continuation_token)

                    async for key in await keyList.__anext__():
                        key_name = key["name"]
                        if include_stats:
                            ETag = key["etag"]
                            lastModified = int(key["last_modified"].timestamp())
                            data_size = key["size"]
                            key_names[key_name] = {"ETag": ETag, "Size": data_size, "LastModified": lastModified }
                        else:
                            if suffix and not key_name.endswith(suffix):
                                continue
                            if deliminator and key_name[-1] != '/':
                                # only return folders
                                continue
                            if limit and len(key_names) >= limit:
                                break
                            key_names.append(key_name)
                    if callback:
                        if iscoroutinefunction(callback):
                            await callback(self._app, key_names)
                        else:
                            callback(self._app, key_names)
                    if not keyList.continuation_token or (limit and len(key_names) >= limit):
                        # got all the keys (or as many as requested)
                        break
                    else:
                        # keep going
                        continuation_token = keyList.continuation_token

        except CancelledError as cle:
            self._azure_stats_increment("error_count")
            msg = f"azureBlobClient.CancelledError for list_keys: {cle}"
            log.error(msg)
            raise HTTPInternalServerError()
        except Exception as e:
            if isinstance(e, AzureError):
                if e.status_code == 404:
                    msg = "azureBlobClient not found error for list_keys"
                    log.warn(msg)
                    raise HTTPNotFound()
                elif e.status_code in (401, 403):
                    msg = "azureBlobClient.access denied for list_keys"
                    log.info(msg)
                    raise HTTPForbidden()
                else:
                    self._azure_stats_increment("error_count")
                    log.error(f"azureBlobClient.got unexpected AzureError for list_keys: {e.message}")
                    raise HTTPInternalServerError()
            else:
                log.error(f"azureBlobClient.Unexpected exception for list_keys: {e}")
                raise HTTPInternalServerError()

        log.info(f"list_keys done, got {len(key_names)} keys")
        if limit and len(key_names) > limit:
            # return requested number of keys
            if include_stats:
                keys = list(key_names.keys())
                keys.sort()
                for k in keys[limit:]:
                    del key_names[k]
            else:
                key_names = key_names[:limit]

        return key_names
Example #46
0
                            logger.error(
                                f"重试{attempts}次仍然出错,错误内容,{error_info}")
                            break
                    try:
                        result = func(*args, **_kwargs)
                        return result
                    except Exception as e:
                        retry_count += 1
                        if retry_count == attempts:
                            error_info = f"{traceback.format_exc()}"
                        if max_sleep_time:
                            sleep_time = random.randint(
                                min_sleep_time, max_sleep_time)
                            time.sleep(sleep_time)

        return decorator

    return retry


@aio_retry()
def retry_test():
    s = 1 + '1'
    return s


if __name__ == '__main__':
    print(iscoroutinefunction(retry_test))
    retry_test()
'''这种重试机制最好是用在异步方法中'''
Example #47
0
 async def run(self):
     if (inspect.iscoroutine(self.job_func.func)
             or inspect.iscoroutinefunction(self.job_func.func)):
         ret = await self.job_func()
     else:
         ret = self.job_func()
Example #48
0
def is_async_func(func: Any) -> bool:
    if inspect.iscoroutinefunction(func):
        return True
    if isinstance(func, functools.partial):
        return is_async_func(func.func)
    return False
Example #49
0
async def _invoke(
    actor: 'Actor',
    cid: str,
    chan: Channel,
    func: typing.Callable,
    kwargs: Dict[str, Any],
    task_status=trio.TASK_STATUS_IGNORED
):
    """Invoke local func and deliver result(s) over provided channel.
    """
    treat_as_gen = False
    cs = None
    cancel_scope = trio.CancelScope()
    ctx = Context(chan, cid, cancel_scope)
    _context.set(ctx)
    if getattr(func, '_tractor_stream_function', False):
        # handle decorated ``@tractor.stream`` async functions
        kwargs['ctx'] = ctx
        treat_as_gen = True
    try:
        is_async_partial = False
        is_async_gen_partial = False
        if isinstance(func, partial):
            is_async_partial = inspect.iscoroutinefunction(func.func)
            is_async_gen_partial = inspect.isasyncgenfunction(func.func)

        if (
            not inspect.iscoroutinefunction(func) and
            not inspect.isasyncgenfunction(func) and
            not is_async_partial and
            not is_async_gen_partial
        ):
            await chan.send({'functype': 'function', 'cid': cid})
            with cancel_scope as cs:
                task_status.started(cs)
                await chan.send({'return': func(**kwargs), 'cid': cid})
        else:
            coro = func(**kwargs)

            if inspect.isasyncgen(coro):
                await chan.send({'functype': 'asyncgen', 'cid': cid})
                # XXX: massive gotcha! If the containing scope
                # is cancelled and we execute the below line,
                # any ``ActorNursery.__aexit__()`` WON'T be
                # triggered in the underlying async gen! So we
                # have to properly handle the closing (aclosing)
                # of the async gen in order to be sure the cancel
                # is propagated!
                with cancel_scope as cs:
                    task_status.started(cs)
                    async with aclosing(coro) as agen:
                        async for item in agen:
                            # TODO: can we send values back in here?
                            # it's gonna require a `while True:` and
                            # some non-blocking way to retrieve new `asend()`
                            # values from the channel:
                            # to_send = await chan.recv_nowait()
                            # if to_send is not None:
                            #     to_yield = await coro.asend(to_send)
                            await chan.send({'yield': item, 'cid': cid})

                log.debug(f"Finished iterating {coro}")
                # TODO: we should really support a proper
                # `StopAsyncIteration` system here for returning a final
                # value if desired
                await chan.send({'stop': True, 'cid': cid})
            else:
                if treat_as_gen:
                    await chan.send({'functype': 'asyncgen', 'cid': cid})
                    # XXX: the async-func may spawn further tasks which push
                    # back values like an async-generator would but must
                    # manualy construct the response dict-packet-responses as
                    # above
                    with cancel_scope as cs:
                        task_status.started(cs)
                        await coro
                    if not cs.cancelled_caught:
                        # task was not cancelled so we can instruct the
                        # far end async gen to tear down
                        await chan.send({'stop': True, 'cid': cid})
                else:
                    await chan.send({'functype': 'asyncfunction', 'cid': cid})
                    with cancel_scope as cs:
                        task_status.started(cs)
                        await chan.send({'return': await coro, 'cid': cid})
    except (Exception, trio.MultiError) as err:
        # always ship errors back to caller
        log.exception("Actor errored:")
        err_msg = pack_error(err)
        err_msg['cid'] = cid
        try:
            await chan.send(err_msg)
        except trio.ClosedResourceError:
            log.exception(
                f"Failed to ship error to caller @ {chan.uid}")
        if cs is None:
            # error is from above code not from rpc invocation
            task_status.started(err)
    finally:
        # RPC task bookeeping
        try:
            scope, func, is_complete = actor._rpc_tasks.pop((chan, cid))
            is_complete.set()
        except KeyError:
            # If we're cancelled before the task returns then the
            # cancel scope will not have been inserted yet
            log.warn(
                f"Task {func} was likely cancelled before it was started")

        if not actor._rpc_tasks:
            log.info(f"All RPC tasks have completed")
            actor._ongoing_rpc_tasks.set()
Example #50
0
def _is_wrapped_coroutine_function(fn):
    while hasattr(fn, "__wrapped__"):
        fn = fn.__wrapped__

    return inspect.iscoroutinefunction(fn)
Example #51
0
    def __validate_and_wrap_mock_value(self, name: str, value: Any) -> Any:
        if self._template:
            if not self.__template_has_attr(name):
                if not (
                    name.startswith(f"_{type(self).__name__}__")
                    and not name.endswith("__")
                ):
                    raise NonExistentAttribute(self, name)

            self.__validate_attribute_type(name, value)

            if hasattr(self._template, name):
                template_value = getattr(self._template, name)
                if callable(template_value):
                    if not callable(value):
                        raise NonCallableValue(self, name)
                    if self.__dict__["_type_validation"]:
                        signature_validation_wrapper = (
                            testslide.lib._wrap_signature_and_type_validation(
                                value,
                                self._template,
                                name,
                                self.__dict__["_type_validation"],
                            )
                        )

                        if inspect.iscoroutinefunction(template_value):

                            async def awaitable_return_validation_wrapper(
                                *args, **kwargs
                            ):
                                result_awaitable = signature_validation_wrapper(
                                    *args, **kwargs
                                )
                                if not inspect.isawaitable(result_awaitable):
                                    raise NonAwaitableReturn(self, name)

                                return_value = await result_awaitable
                                if not testslide.lib._is_wrapped_for_signature_and_type_validation(
                                    # The original value was already wrapped for type
                                    # validation. Skipping additional validation to
                                    # allow, for example, mock_callable to disable
                                    # validation for a very specific mock call rather
                                    # for the whole StrictMock instance
                                    value
                                ) and not isinstance(
                                    # If the return value is a _BaseRunner then type
                                    # validation, if needed, has already been performed
                                    return_value,
                                    testslide.mock_callable._BaseRunner,
                                ):
                                    testslide.lib._validate_return_type(
                                        template_value,
                                        return_value,
                                        self.__dict__["_caller_frame_info"],
                                    )
                                return return_value

                            callable_value = awaitable_return_validation_wrapper
                        else:

                            def return_validation_wrapper(*args, **kwargs):
                                return_value = signature_validation_wrapper(
                                    *args, **kwargs
                                )
                                if not testslide.lib._is_wrapped_for_signature_and_type_validation(
                                    # The original value was already wrapped for type
                                    # validation. Skipping additional validation to
                                    # allow, for example, mock_callable to disable
                                    # validation for a very specific mock call rather
                                    # for the whole StrictMock instance
                                    value
                                ) and not isinstance(
                                    # If the return value is a _BaseRunner then type
                                    # validation, if needed, has already been performed
                                    return_value,
                                    testslide.mock_callable._BaseRunner,
                                ):
                                    testslide.lib._validate_return_type(
                                        template_value,
                                        return_value,
                                        self.__dict__["_caller_frame_info"],
                                    )
                                return return_value

                            callable_value = return_validation_wrapper
                    else:
                        callable_value = None
                    return _MethodProxy(value=value, callable_value=callable_value)
            else:
                if callable(value):
                    # We don't really need the proxy here, but it serves the
                    # double purpose of swallowing self / cls when needed.
                    return _MethodProxy(value=value)
        else:
            if callable(value):
                # We don't really need the proxy here, but it serves the
                # double purpose of swallowing self / cls when needed.
                return _MethodProxy(value=value)

        return value
Example #52
0
def prepare_middleware(middleware, independent_middleware=False, asgi=False):
    """Check middleware interfaces and prepare the methods for request handling.

    Note:
        This method is only applicable to WSGI apps.

    Arguments:
        middleware (iterable): An iterable of middleware objects.

    Keyword Args:
        independent_middleware (bool): ``True`` if the request and
            response middleware methods should be treated independently
            (default ``False``)
        asgi (bool): ``True`` if an ASGI app, ``False`` otherwise
            (default ``False``)

    Returns:
        tuple: A tuple of prepared middleware method tuples
    """

    # PERF(kgriffs): do getattr calls once, in advance, so we don't
    # have to do them every time in the request path.
    request_mw = []
    resource_mw = []
    response_mw = []

    for component in middleware:
        # NOTE(kgriffs): Middleware that supports both WSGI and ASGI can
        #   append an *_async postfix to the ASGI version of the method
        #   to distinguish the two. Otherwise, the prefix is unnecessary.

        if asgi:
            process_request = (
                util.get_bound_method(component, 'process_request_async')
                or _wrap_non_coroutine_unsafe(
                    util.get_bound_method(component, 'process_request')))

            process_resource = (
                util.get_bound_method(component, 'process_resource_async')
                or _wrap_non_coroutine_unsafe(
                    util.get_bound_method(component, 'process_resource')))

            process_response = (
                util.get_bound_method(component, 'process_response_async')
                or _wrap_non_coroutine_unsafe(
                    util.get_bound_method(component, 'process_response')))

            for m in (process_request, process_resource, process_response):
                # NOTE(kgriffs): iscoroutinefunction() always returns False
                #   for cythonized functions.
                #
                #   https://github.com/cython/cython/issues/2273
                #   https://bugs.python.org/issue38225
                #
                if m and not iscoroutinefunction(m) and util.is_python_func(m):
                    msg = (
                        '{} must be implemented as an awaitable coroutine. If '
                        'you would like to retain compatibility '
                        'with WSGI apps, the coroutine versions of the '
                        'middleware methods may be implemented side-by-side '
                        'by applying an *_async postfix to the method names. ')
                    raise CompatibilityError(msg.format(m))

        else:
            process_request = util.get_bound_method(component,
                                                    'process_request')
            process_resource = util.get_bound_method(component,
                                                     'process_resource')
            process_response = util.get_bound_method(component,
                                                     'process_response')

            for m in (process_request, process_resource, process_response):
                if m and iscoroutinefunction(m):
                    msg = ('{} may not implement coroutine methods and '
                           'remain compatible with WSGI apps without '
                           'using the *_async postfix to explicitly identify '
                           'the coroutine version of a given middleware '
                           'method.')
                    raise CompatibilityError(msg.format(component))

        if not (process_request or process_resource or process_response):
            if asgi and any(
                    hasattr(component, m) for m in [
                        'process_startup',
                        'process_shutdown',
                        'process_request_ws',
                        'process_resource_ws',
                    ]):
                # NOTE(kgriffs): This middleware only has ASGI lifespan
                #   event handlers
                continue

            msg = '{0} must implement at least one middleware method'
            raise TypeError(msg.format(component))

        # NOTE: depending on whether we want to execute middleware
        # independently, we group response and request middleware either
        # together or separately.
        if independent_middleware:
            if process_request:
                request_mw.append(process_request)
            if process_response:
                response_mw.insert(0, process_response)
        else:
            if process_request or process_response:
                request_mw.append((process_request, process_response))

        if process_resource:
            resource_mw.append(process_resource)

    return (tuple(request_mw), tuple(resource_mw), tuple(response_mw))
Example #53
0
    async def process_options(self,
                              guild: discord.Guild,
                              options: list,
                              connector: dict,
                              temporary_auto_convert: dict = None) -> dict:
        """
        Processes Role, User, and Channel option types to discord.py's models.

        :param guild: Guild of the command message.
        :type guild: discord.Guild
        :param options: Dict of options.
        :type options: list
        :param connector: Kwarg connector.
        :param temporary_auto_convert: Temporary parameter, use this if options doesn't have ``type`` keyword.
        :return: Union[list, dict]
        """

        if not guild or not isinstance(guild, discord.Guild):
            return {
                connector.get(x["name"]) or x["name"]: x["value"]
                for x in options
            }

        converters = [
            # If extra converters are added and some needs to fetch it,
            # you should pass as a list with 1st item as a cache get method
            # and 2nd as a actual fetching method.
            [guild.get_member, guild.fetch_member],
            guild.get_channel,
            guild.get_role
        ]

        types = {
            "user": 0,
            "USER": 0,
            model.SlashCommandOptionType.USER: 0,
            "6": 0,
            6: 0,
            "channel": 1,
            "CHANNEL": 1,
            model.SlashCommandOptionType.CHANNEL: 1,
            "7": 1,
            7: 1,
            "role": 2,
            "ROLE": 2,
            model.SlashCommandOptionType.ROLE: 2,
            8: 2,
            "8": 2
        }

        to_return = {}

        for x in options:
            processed = None  # This isn't the best way, but we should to reduce duplicate lines.

            # This is to temporarily fix Issue #97, that on Android device
            # does not give option type from API.
            if "type" not in x:
                x["type"] = temporary_auto_convert[x["name"]]

            if x["type"] not in types:
                processed = x["value"]
            else:
                loaded_converter = converters[types[x["type"]]]
                if isinstance(loaded_converter, list):  # For user type.
                    cache_first = loaded_converter[0](int(x["value"]))
                    if cache_first:
                        processed = cache_first
                    else:
                        loaded_converter = loaded_converter[1]
                if not processed:
                    try:
                        processed = await loaded_converter(int(x["value"])) \
                            if iscoroutinefunction(loaded_converter) else \
                            loaded_converter(int(x["value"]))
                    except (discord.Forbidden, discord.HTTPException,
                            discord.NotFound):  # Just in case.
                        self.logger.warning(
                            "Failed fetching discord object! Passing ID instead."
                        )
                        processed = int(x["value"])
            to_return[connector.get(x["name"]) or x["name"]] = processed
        return to_return
Example #54
0
 def is_async(self):
     true = unwrap(self._func)
     return (iscoroutinefunction(true) or isasyncgenfunction(true)
             or isawaitable(true))
Example #55
0
    def __new__(cls, *args: Any, **kwargs: Any) -> Self:
        name, bases, attrs = args
        if any(issubclass(base, app_commands.Group) for base in bases):
            raise TypeError(
                'Cannot inherit from app_commands.Group with commands.Cog, consider using commands.GroupCog instead'
            )

        # If name='...' is given but not group_name='...' then name='...' is used for both.
        # If neither is given then cog name is the class name but group name is kebab case
        try:
            cog_name = kwargs.pop('name')
        except KeyError:
            cog_name = name
            try:
                group_name = kwargs.pop('group_name')
            except KeyError:
                group_name = app_commands.commands._to_kebab_case(name)
        else:
            group_name = kwargs.pop('group_name', cog_name)

        attrs['__cog_settings__'] = kwargs.pop('command_attrs', {})
        attrs['__cog_name__'] = cog_name
        attrs['__cog_group_name__'] = group_name
        attrs['__cog_group_nsfw__'] = kwargs.pop('group_nsfw', False)

        description = kwargs.pop('description', None)
        if description is None:
            description = inspect.cleandoc(attrs.get('__doc__', ''))

        attrs['__cog_description__'] = description
        attrs['__cog_group_description__'] = kwargs.pop(
            'group_description', description or '\u2026')

        commands = {}
        cog_app_commands = {}
        listeners = {}
        no_bot_cog = 'Commands or listeners must not start with cog_ or bot_ (in method {0.__name__}.{1})'

        new_cls = super().__new__(cls, name, bases, attrs, **kwargs)
        for base in reversed(new_cls.__mro__):
            for elem, value in base.__dict__.items():
                if elem in commands:
                    del commands[elem]
                if elem in listeners:
                    del listeners[elem]

                is_static_method = isinstance(value, staticmethod)
                if is_static_method:
                    value = value.__func__
                if isinstance(value, _BaseCommand):
                    if is_static_method:
                        raise TypeError(
                            f'Command in method {base}.{elem!r} must not be staticmethod.'
                        )
                    if elem.startswith(('cog_', 'bot_')):
                        raise TypeError(no_bot_cog.format(base, elem))
                    commands[elem] = value
                elif isinstance(
                        value,
                    (app_commands.Group,
                     app_commands.Command)) and value.parent is None:
                    if is_static_method:
                        raise TypeError(
                            f'Command in method {base}.{elem!r} must not be staticmethod.'
                        )
                    if elem.startswith(('cog_', 'bot_')):
                        raise TypeError(no_bot_cog.format(base, elem))
                    cog_app_commands[elem] = value
                elif inspect.iscoroutinefunction(value):
                    try:
                        getattr(value, '__cog_listener__')
                    except AttributeError:
                        continue
                    else:
                        if elem.startswith(('cog_', 'bot_')):
                            raise TypeError(no_bot_cog.format(base, elem))
                        listeners[elem] = value

        new_cls.__cog_commands__ = list(
            commands.values())  # this will be copied in Cog.__new__
        new_cls.__cog_app_commands__ = list(cog_app_commands.values())

        listeners_as_list = []
        for listener in listeners.values():
            for listener_name in listener.__cog_listener_names__:
                # I use __name__ instead of just storing the value so I can inject
                # the self attribute when the time comes to add them to the bot
                listeners_as_list.append((listener_name, listener.__name__))

        new_cls.__cog_listeners__ = listeners_as_list
        return new_cls
Example #56
0
    module_instance = importlib.util.module_from_spec(spec)  # type: ignore
    spec.loader.exec_module(module_instance)  # type: ignore
    return module_instance  # type: ignore


def run(measure_filename: str, stats_filename: str, case: model.LoadedCase,
        scenario: model.Scenario, sslconfig: model.SslConfig,
        **kwargs) -> None:
    global MEASURE_FILENAME
    global STATS_FILENAME
    MEASURE_FILENAME = measure_filename
    STATS_FILENAME = stats_filename

    module = _import_module(case)
    main = module.main
    if not inspect.iscoroutinefunction(main):
        call_main = _call_sync_main
    elif 'trio' in sys.modules:
        call_main = _call_trio_main
    elif 'curio' in sys.modules:
        call_main = _call_curio_main
    else:
        call_main = _call_async_main

    call_main(main, scenario, sslconfig, **kwargs)


def get_parameters(parameter_filename: str, case: model.LoadedCase):
    parameters_list = []

    module = _import_module(case)
Example #57
0
def is_simgear_func(func):
    return (
        inspect.isgeneratorfunction(func) or inspect.iscoroutinefunction(func)
        or is_async_gen(func))
Example #58
0
    async def check_permissions(self, author, guild, locale, dm=False, permissions=None, **kwargs):
        permissions = permissions or self.permissions

        if author.id == OWNER:
            return True

        if permissions.developer_only or self.developer_only:
            if author.id != OWNER:
                raise PermissionError("This command is reserved for the Bloxlink Developer.")

        if (kwargs.get("premium", self.premium) or permissions.premium) and not kwargs.get("free_to_use", self.free_to_use):
            prem, _ = await get_features(Object(id=guild.owner_id), guild=guild)

            if not prem.features.get("premium"):
                prem, _ = await get_features(author)

                if not prem.attributes["PREMIUM_ANYWHERE"]:
                    raise Message("This command is reserved for Bloxlink Premium subscribers!\n"
                                  "The server owner must have premium for this to work. If you "
                                  "would like the server owner to have premium instead, please use the ``!transfer`` "
                                  "command.\nYou may subscribe to Bloxlink Premium on Patreon: https://patreon.com/bloxlink", type="silly")

        try:
            if not dm:
                author_perms = author.guild_permissions

                for role_exception in permissions.exceptions["roles"]:
                    if find(lambda r: r.name == role_exception, author.roles):
                        return True

                if permissions.bloxlink_role:
                    role_name = permissions.bloxlink_role

                    if find(lambda r: r.name == "Bloxlink Admin", author.roles):
                        return True
                    else:
                        if role_name == "Bloxlink Manager":
                            if author_perms.manage_guild or author_perms.administrator:
                                pass
                            else:
                                raise PermissionError("You need the ``Manage Server`` permission to run this command.")

                        elif role_name == "Bloxlink Moderator":
                            if author_perms.kick_members or author_perms.ban_members or author_perms.administrator:
                                pass
                            else:
                                raise PermissionError("You need the ``Kick`` or ``Ban`` permission to run this command.")

                        elif role_name == "Bloxlink Updater":
                            if author_perms.manage_guild or author_perms.administrator or author_perms.manage_roles or find(lambda r: r.name == "Bloxlink Updater", author.roles):
                                pass
                            else:
                                raise PermissionError("You either need: a role called ``Bloxlink Updater``, the ``Manage Roles`` "
                                                      "role permission, or the ``Manage Server`` role permission.")

                        elif role_name == "Bloxlink Admin":
                            if author_perms.administrator:
                                pass
                            else:
                                raise PermissionError("You need the ``Administrator`` role permission to run this command.")

                if permissions.allowed.get("discord_perms"):
                    for perm in permissions.allowed["discord_perms"]:
                        if perm == "Manage Server":
                            if author_perms.manage_guild or author_perms.administrator:
                                pass
                            else:
                                raise PermissionError("You need the ``Manage Server`` permission to run this command.")
                        else:
                            if not getattr(author_perms, perm, False) and not perm.administrator:
                                raise PermissionError(f"You need the ``{perm}`` permission to run this command.")


                for role in permissions.allowed["roles"]:
                    if not find(lambda r: r.name == role, author.roles):
                        raise PermissionError(f"Missing role: ``{role}``")

            if permissions.allowed.get("functions"):
                for function in permissions.allowed["functions"]:

                    if iscoroutinefunction(function):
                        data = [await function(author)]
                    else:
                        data = [function(author)]

                    if not data[0]:
                        raise PermissionError

                    if isinstance(data[0], tuple):
                        if not data[0][0]:
                            raise PermissionError(data[0][1])

        except PermissionError as e:
            if e.args:
                raise PermissionError(e)

            raise PermissionError("You do not meet the required permissions for this command.")
Example #59
0
    def decorator(func):
        if iscoroutinefunction(func) or is_async:
            return _validate_async(func, req_schema, resp_schema)

        return _validate(func, req_schema, resp_schema)
Example #60
0
def pytest_fixture_setup(fixturedef, request):
    """Adjust the event loop policy when an event loop is produced."""
    if isasyncgenfunction(fixturedef.func):
        # This is an async generator function. Wrap it accordingly.
        f = fixturedef.func

        strip_event_loop = False
        if 'event_loop' not in fixturedef.argnames:
            fixturedef.argnames += ('event_loop', )
            strip_event_loop = True
        strip_request = False
        if 'request' not in fixturedef.argnames:
            fixturedef.argnames += ('request', )
            strip_request = True

        def wrapper(*args, **kwargs):
            loop = kwargs['event_loop']
            request = kwargs['request']
            if strip_event_loop:
                del kwargs['event_loop']
            if strip_request:
                del kwargs['request']

            gen_obj = f(*args, **kwargs)

            async def setup():
                res = await gen_obj.__anext__()
                return res

            def finalizer():
                """Yield again, to finalize."""
                async def async_finalizer():
                    try:
                        await gen_obj.__anext__()
                    except StopAsyncIteration:
                        pass
                    else:
                        msg = "Async generator fixture didn't stop."
                        msg += "Yield only once."
                        raise ValueError(msg)

                loop.run_until_complete(async_finalizer())

            request.addfinalizer(finalizer)

            return loop.run_until_complete(setup())

        fixturedef.func = wrapper

    elif inspect.iscoroutinefunction(fixturedef.func):
        # Just a coroutine, not an async generator.
        f = fixturedef.func

        strip_event_loop = False
        if 'event_loop' not in fixturedef.argnames:
            fixturedef.argnames += ('event_loop', )
            strip_event_loop = True

        def wrapper(*args, **kwargs):
            loop = kwargs['event_loop']
            if strip_event_loop:
                del kwargs['event_loop']

            async def setup():
                res = await f(*args, **kwargs)
                return res

            return loop.run_until_complete(setup())

        fixturedef.func = wrapper

    outcome = yield

    if fixturedef.argname == "event_loop" and 'asyncio' in request.keywords:
        loop = outcome.get_result()
        for kw in _markers_2_fixtures.keys():
            if kw not in request.keywords:
                continue
            policy = asyncio.get_event_loop_policy()
            try:
                old_loop = policy.get_event_loop()
            except RuntimeError as exc:
                if 'no current event loop' not in str(exc):
                    raise
                old_loop = None
            policy.set_event_loop(loop)
            fixturedef.addfinalizer(lambda: policy.set_event_loop(old_loop))