Beispiel #1
0
async def test_user_can_retrieve_their_operations(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
    wallet_factory: WalletFactory,
    operation_factory: OperationFactory,
) -> None:
    user = await login()
    wallet = wallet_factory.create(user=user)

    for id in [
            '3fa85f64-5717-4562-b3fc-2c963f66afa6',
            '1bb41739-afb5-41c5-aaee-b344f7066bf9',
            'c49ef2aa-ca2d-4c71-aaab-4e1cca2c899a',
    ]:
        operation_factory.create(
            id=id,
            wallet=wallet,
            destination_wallet=wallet,
        )

    response = await cli.get('/v1/wallets/operations')
    response_json = await response.json()

    actual = {entry['id'] for entry in response_json['data']}
    expected = {
        '3fa85f64-5717-4562-b3fc-2c963f66afa6',
        '1bb41739-afb5-41c5-aaee-b344f7066bf9',
        'c49ef2aa-ca2d-4c71-aaab-4e1cca2c899a',
    }

    assert actual == expected
Beispiel #2
0
def ssr(
    *,
    props: Type[P],
    params: None = None
) -> Callable[[NoArgsView[P]], Callable[
    [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]]:
    ...
Beispiel #3
0
def skip_if(
    check_skip: t.Callable[[VarArg(t.Any), KwArg(t.Any)], bool],
    skip_return: t.Callable[[VarArg(t.Any), KwArg(t.Any)],
                            t.Any] = lambda *a, **kw: None,
) -> t.Any:
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs) -> t.Optional[t.Any]:
            if not check_skip(*args, **kwargs):
                result = func(*args, **kwargs)
                return result
            else:
                return skip_return(*args, **kwargs)

        return wrapper

    return decorator
Beispiel #4
0
    def wrap_with_jsx(
        original: View[K, P]
    ) -> Callable[
        [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]:
        def wrapper(request: HttpRequest, **kwargs: Any) -> HttpResponse:
            props = original(request, cast(Any, params)(**kwargs))
            template_name = to_camel_case(original.__name__)

            return render_jsx(request, template_name, props)

        return wrapper
Beispiel #5
0
    def __getattr__(self, attr: str) -> Callable[
        [VarArg(Any), KwArg(Any)], Any]:
        '''Proxy calls to settings store.'''
        if hasattr(self.__dict__.get('data'), attr):

            def wrapper(*args, **kwargs):
                '''Call query for data store.'''
                return getattr(self.data, attr)(*args, **kwargs)

            return wrapper
        raise AttributeError(attr)
async def test_user_can_logout(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
) -> None:
    await login()
    await cli.post('/v1/auth/logout')

    response = await cli.get('/__test__/identity')
    response_json = await response.json()

    assert response_json["authorized_userid"] is None
Beispiel #7
0
    def help_factory(
        self, parser: SlackArgumentParser, **kwarg: Any
    ) -> Callable[[Arg(SlackEventContextMessage, "context"
                       ), KwArg(Any)], None]:
        def help_func(context: SlackEventContextMessage, **kwarg: Any) -> None:
            text = ""
            if "message" in kwarg:
                text += kwarg["message"]
                text += "\n"
            text += parser.format_help()
            context.reply_ephemeral(text=text)

        return help_func
async def test_register_user_validation_errors(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
    body: Dict[str, str],
    error: Dict[str, str],
) -> None:
    await login()

    response = await cli.post('/v1/wallets/transfer', json=body)
    response_json = await response.json()

    assert response.status == 422
    assert response_json["status"]["errors"] == [error]
Beispiel #9
0
def ssr(
    *,
    props: Type[P],
    params: Optional[Type[K]] = None
) -> Union[Callable[[NoArgsView[P]], Callable[
    [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]], Callable[
        [View[K, P]], Callable[[Arg(HttpRequest, 'request'
                                    ), KwArg(Any)], HttpResponse]], ]:
    type_registry[props.__name__] = props  # type: ignore

    def no_args_wrap_with_jsx(
        original: NoArgsView[P]
    ) -> Callable[
        [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]:
        def wrapper(request: HttpRequest, **kwargs: Any) -> HttpResponse:
            props = original(request)
            template_name = to_camel_case(original.__name__)

            return render_jsx(request, template_name, props)

        return wrapper

    def wrap_with_jsx(
        original: View[K, P]
    ) -> Callable[
        [Arg(HttpRequest, 'request'), KwArg(Any)], HttpResponse]:
        def wrapper(request: HttpRequest, **kwargs: Any) -> HttpResponse:
            props = original(request, cast(Any, params)(**kwargs))
            template_name = to_camel_case(original.__name__)

            return render_jsx(request, template_name, props)

        return wrapper

    if params is None:
        return no_args_wrap_with_jsx
    else:
        return wrap_with_jsx
async def test_user_can_perform_deposit(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
    amount: Optional[str],
    wallet_factory: WalletFactory,
) -> None:
    user = await login()
    wallet_factory.create(user=user)

    response = await cli.post('/v1/wallets/deposit', json={'amount': amount})
    response_json = await response.json()

    actual = (response.status, response_json['data']['amount'])
    expected = (200, amount)

    assert actual == expected
Beispiel #11
0
async def test_user_without_wallet_gets_not_found_error(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
) -> None:
    await login()

    response = await cli.get('/v1/wallets/operations')
    response_json = await response.json()

    actual = (response.status, response_json['status']['errors'])
    expected = (404, [{
        'code': 'NOT_FOUND',
        'message': "Wallet does not exist.",
        'target': '__all__',
    }])

    assert actual == expected
async def test_deposit_requires_existing_wallet(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
) -> None:
    await login()

    response = await cli.post('/v1/wallets/deposit', json={'amount': '10.00'})
    response_json = await response.json()

    actual = (response.status, response_json['status']['errors'])
    expected = (404, [{
        'code': 'NOT_FOUND',
        'message': "Wallet does not exist.",
        'target': '__all__',
    }])

    assert actual == expected
async def test_user_can_retrieve_their_wallet(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
    wallet_factory: WalletFactory,
) -> None:
    user = await login()
    wallet_factory.create(
        id='3fa85f64-5717-4562-b3fc-2c963f66afa6',
        user=user,
    )

    response = await cli.get('/v1/wallets')
    response_json = await response.json()

    actual = response_json['data']['id']
    expected = '3fa85f64-5717-4562-b3fc-2c963f66afa6'

    assert actual == expected
Beispiel #14
0
async def login(
    cli: TestClient,
    user_factory: UserFactory,
) -> Callable[[KwArg(Any)], Awaitable[UserModel]]:
    async def login_(
        user: Optional[UserModel] = None,
        **kwargs: Any,
    ) -> UserModel:
        kwargs.setdefault('password_raw', 'pass')
        user = user or user_factory.create(**kwargs)

        await cli.post('/v1/auth/login',
                       json={
                           'username': user.username,
                           'password': kwargs['password_raw'],
                       })

        return user

    return login_
async def test_user_cannot_deposit_wallet_with_invalid_amount(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
) -> None:
    await login()

    response = await cli.post('/v1/wallets/deposit', json={'amount': 'string'})
    response_json = await response.json()

    actual = (response.status, response_json['status']['errors'])
    expected = (
        422,
        [{
            'code': 'UNPROCESSABLE_ENTITY',
            'message': 'Not a valid number.',
            'target': 'amount',
        }],
    )

    assert actual == expected
async def test_user_can_transfer_money_to_another_user(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
    user_factory: UserFactory,
    wallet_factory: WalletFactory,
    operation_factory: OperationFactory,
) -> None:
    source_user = user_factory.create(password_raw='pass')
    destination_user = user_factory.create(password_raw='pass')

    source_wallet = wallet_factory.create(user=source_user)
    destination_wallet = wallet_factory.create(user=destination_user)

    operation_factory.create(
        wallet=source_wallet,
        destination_wallet=source_wallet,
        amount=decimal.Decimal('1000'),
    )

    await login(user=source_user)
    await cli.post('/v1/wallets/transfer',
                   json={
                       'destination': destination_wallet.id,
                       'amount': '50.00',
                   })

    source_response = await cli.get('/v1/wallets')
    source_response_json = await source_response.json()

    await login(user=destination_user)

    destination_response = await cli.get('/v1/wallets')
    destination_response_json = await destination_response.json()

    actual = (
        source_response_json['data']['balance'],
        destination_response_json['data']['balance'],
    )
    expected = ('950.00', '50.00')

    assert actual == expected
Beispiel #17
0
def load(region: str) -> Spec:
    specs = json.loads(
        importlib.resources.read_text(__package__, f"{region}.json"))
    rescs: MutableMapping[str, MutableMapping[str, MutableMapping[
        str, Callable[[VarArg(), KwArg()], Resource]]], ] = {}
    for typ, spec in specs["ResourceTypes"].items():
        rvnd, rsvc, rcom = typ.split("::")
        vnd, svc, com = TRANS[rvnd], TRANS[rsvc], TRANS[rcom]
        svc = "lambda_" if svc == "lambda" else svc
        attrs: MutableMapping[str, Union[Type[types.Ref],
                                         Type[types.Attr]]] = {
                                             TRANS[a]: _resolve_attr(a, s)
                                             for a, s in spec.get(
                                                 "Attributes", {}).items()
                                         }
        attrs["ref"] = types.Ref
        check = _resolve_check(typ, spec, specs)

        def bake(vnd_, svc_, com_, typ_, attrs_, check_):
            def factory(*args, **kwargs) -> Resource:
                name = next(iter(args), "")
                # props = dict(kwargs) if kwargs else None
                res = Resource(name, vnd_, svc_, com_, typ_, attrs_, check_,
                               dict(kwargs))
                return res

            factory.__module__ = ".".join(["ic", vnd_, svc_])
            factory.__name__ = com_
            factory.__qualname__ = com_
            sigs = [
                inspect.Parameter(p, inspect.Parameter.KEYWORD_ONLY)
                for p in check_.items
            ]
            # python/myp#5958
            factory.__signature__ = inspect.Signature(sigs)  # type: ignore
            return factory

        resc = bake(vnd, svc, com, typ, attrs, check)
        rescs.setdefault(vnd, {}).setdefault(svc, {})[com] = resc
    return rescs
Beispiel #18
0
async def test_user_cannot_see_operations_of_another_user(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
    wallet_factory: WalletFactory,
    operation_factory: OperationFactory,
) -> None:
    user = await login()
    wallet = wallet_factory.create(user=user)

    operation_factory.create(
        id='c49ef2aa-ca2d-4c71-aaab-4e1cca2c899a',
        wallet=wallet,
        destination_wallet=wallet,
    )

    response = await cli.get('/v1/wallets/operations')
    response_json = await response.json()

    actual = [entry['id'] for entry in response_json['data']]
    expected = ['c49ef2aa-ca2d-4c71-aaab-4e1cca2c899a']

    assert actual == expected
async def test_user_without_wallet_gets_not_found_error(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
) -> None:
    await login()

    response = await cli.post('/v1/wallets/transfer',
                              json={
                                  'destination':
                                  '1bb41739-afb5-41c5-aaee-b344f7066bf9',
                                  'amount': '50.00',
                              })
    response_json = await response.json()

    actual = (response.status, response_json['status']['errors'])
    expected = (404, [{
        'code': 'NOT_FOUND',
        'message': "Wallet does not exist.",
        'target': '__all__',
    }])

    assert actual == expected
Beispiel #20
0
def bound_to_logger(**vals: object
                    ) -> t.Generator[t.Callable[[KwArg()], None], None, None]:
    """Bind values to logger for a certain block.

    :param **vals: The parameters you want to bind to the logger in this block.

    :yields: A method that you can the same way you called this method to bind
             more items to the logger that will also be dropped as soon as this
             context manager exists.
    """
    bound = list(vals.keys())
    logger.bind(**vals)
    # Remove reference to ``vals``
    del vals

    def bind_extra(**to_bind: object) -> None:
        bound.extend(to_bind.keys())
        logger.bind(**to_bind)

    try:
        yield bind_extra
    finally:
        logger.try_unbind(*bound)
async def test_user_cannot_transfer_if_them_has_insufficient_funds(
    cli: TestClient,
    login: Callable[[KwArg(Any)], Awaitable[UserModel]],
    wallet_factory: WalletFactory,
) -> None:
    user = await login()
    wallet_factory.create(user=user)

    response = await cli.post('/v1/wallets/transfer',
                              json={
                                  'destination':
                                  '1bb41739-afb5-41c5-aaee-b344f7066bf9',
                                  'amount': '50.00',
                              })
    response_json = await response.json()

    actual = (response.status, response_json['status']['errors'])
    expected = (400, [{
        'code': 'BAD_REQUEST',
        'message': "Insufficient funds.",
        'target': '__all__',
    }])

    assert actual == expected
Beispiel #22
0
        if sentSecurely or not request.isSecure():
            # Do not cache the insecure session on the secure request, thanks.
            request.setComponent(ISession, session)
        returnValue(session)


_procureProcurerType = Union[
    Callable[[Any], ISessionProcurer],
    Callable[[], ISessionProcurer]
]

_kleinRenderable = Any
_routeCallable = Any
_kleinCallable = Callable[..., _kleinRenderable]
_kleinDecorator = Callable[[_kleinCallable], _kleinCallable]
_requirerResult = Callable[[Arg(_routeCallable, 'route'), KwArg(Any)],
                           Callable[[_kleinCallable], _kleinCallable]]


class AuthorizationDenied(Resource, object):
    def __init__(self, interface, instance):
        # type: (IInterface, Any) -> None
        self._interface = interface
        super(AuthorizationDenied, self).__init__()

    def render(self, request):
        # type: (IRequest) -> bytes
        request.setResponseCode(UNAUTHORIZED)
        return "{} DENIED".format(qual(self._interface)).encode('utf-8')

Beispiel #23
0
import logging
from typing import Any, Callable, List
# from typing import Iterator, List, Tuple, NewType, Dict, Callable, Any
from mypy_extensions import KwArg, Arg

from coinpy.core import JsonDict
from coinpy.core.crypto import Serializable
from coinpy.core.transaction import Transaction
from coinpy.core.block import Block

from coinpy.core.errors import (ValidationError)

logger = logging.getLogger(__name__)

CommandHandler = Callable[[Arg(Any, 'ctx'), KwArg(Any)], None]


class Command(Serializable):
    name = 'undefined'

    def __init__(self, **params: Any) -> None:
        self.params = params

    def _serialize(self) -> JsonDict:
        return {
            'name': self.name,
            'params': self.params,
        }

    def validate(self) -> None:
        if self.name == 'undefined':
Beispiel #24
0
else:
    from mypy_extensions import Arg, DefaultNamedArg, KwArg, NamedArg

    # TODO:1: Split to specialised LoginFn, ProbeFn, StartupFn, etc. -- with different result types.
    # TODO:2: Try using ParamSpec to support index type checking in callbacks
    #         when PEP 612 is released (https://www.python.org/dev/peps/pep-0612/)
    ActivityFn = Callable[[
        NamedArg(configuration.OperatorSettings, "settings"),
        NamedArg(ephemera.Index, "*"),
        NamedArg(int, "retry"),
        NamedArg(datetime.datetime, "started"),
        NamedArg(datetime.timedelta, "runtime"),
        NamedArg(typedefs.Logger, "logger"),
        NamedArg(Any, "memo"),
        DefaultNamedArg(Any, "param"),
        KwArg(Any),
    ], invocation.SyncOrAsync[Optional[object]]]

    IndexingFn = Callable[[
        NamedArg(bodies.Annotations, "annotations"),
        NamedArg(bodies.Labels, "labels"),
        NamedArg(bodies.Body, "body"),
        NamedArg(bodies.Meta, "meta"),
        NamedArg(bodies.Spec, "spec"),
        NamedArg(bodies.Status, "status"),
        NamedArg(references.Resource, "resource"),
        NamedArg(Optional[str], "uid"),
        NamedArg(Optional[str], "name"),
        NamedArg(Optional[str], "namespace"),
        NamedArg(patches.Patch, "patch"),
        NamedArg(typedefs.Logger, "logger"),
    pass


class InsertOptions(OptionBlock, ServerDurableOption, ClientDurableOption):
    pass


class GetFromReplicaOptions(OptionBlock):
    pass


T = TypeVar('T', bound='CBCollection')
R = TypeVar("R")

RawCollectionMethodDefault = Callable[
    [Arg('CBCollection', 'self'), Arg(str, 'key'), VarArg(OptionBlockDeriv), KwArg(Any)], R]
RawCollectionMethodInt = Callable[
    [Arg('CBCollection', 'self'), Arg(str, 'key'), int, VarArg(OptionBlockDeriv), KwArg(Any)], R]
RawCollectionMethod = Union[RawCollectionMethodDefault, RawCollectionMethodInt]
RawCollectionMethodSpecial = TypeVar('RawCollectionMethodSpecial',bound=RawCollectionMethod)


def _get_result_and_inject(func  # type: RawCollectionMethod
                           ):
    # type: (...) ->RawCollectionMethod
    result = _inject_scope_and_collection(get_result_wrapper(func))
    result.__doc__=func.__doc__
    result.__name__=func.__name__
    return result

Beispiel #26
0
    async def run_task(self,
                       async_fn: Callable[[VarArg()], Awaitable[Any]],
                       *args: Any,
                       daemon: bool = False,
                       name: str = None) -> None:
        """
        Run a task in the background.  If the function throws an exception it
        will trigger the service to be cancelled and be propogated.

        If `daemon == True` then the the task is expected to run indefinitely
        and will trigger cancellation if the task finishes.
        """
        ...


LogicFnType = Callable[[ManagerAPI, VarArg(), KwArg()], Awaitable[Any]]


class Service(ServiceAPI):
    pass


def as_service(service_fn: LogicFnType) -> Type[Service]:
    """
    Create a service out of a simple function
    """
    class _Service(Service):
        def __init__(self, *args: Any, **kwargs: Any):
            self._args = args
            self._kwargs = kwargs
Beispiel #27
0
 def __init__(self, features: List[str] = None) -> None:
     self.basis_defs: Dict[Tuple[Path, str], str] = {}
     self.speciedirs: Dict[Tuple[str, str], Path] = {}
     self.features: List[Callable[[KwArg(Any)], Dict[str, Any]]] = [
         getattr(self, feat) for feat in features or self.default_features
     ]
Beispiel #28
0
    'Request',
    'Response',
    'View',
    'ViewHandlerMethod',
    'ViewHandlerFun',
    'ViewDecorator',
    'PageArg',
    'HttpClientT',
    'Web',
    'CacheBackendT',
    'CacheT',
    'BlueprintT',
]

ViewHandlerMethod = Callable[
    [Arg(Request), VarArg(Any), KwArg(Any)], Awaitable[Response], ]

ViewHandlerFun = Callable[
    [Arg(View), Arg(Request), VarArg(Any),
     KwArg(Any)], Awaitable[Response], ]

ViewGetHandler = ViewHandlerFun  # XXX compat
ViewDecorator = Callable[[ViewHandlerFun], ViewHandlerFun]
RoutedViewGetHandler = ViewDecorator  # XXX compat
PageArg = Union[Type[View], ViewHandlerFun]
RouteDecoratorRet = Callable[[PageArg], PageArg]


class CacheBackendT(ServiceT):
    @abc.abstractmethod
    def __init__(self,
    'Response',
    'ResourceOptions',
    'View',
    'ViewHandlerMethod',
    'ViewHandlerFun',
    'ViewDecorator',
    'PageArg',
    'HttpClientT',
    'Web',
    'CacheBackendT',
    'CacheT',
    'BlueprintT',
]

ViewHandlerMethod = Callable[
    [Arg(Request), VarArg(Any), KwArg(Any)],
    Awaitable[Response],
]

ViewHandler2ArgsFun = Callable[
    [Arg(View), Arg(Request)],
    Union[Coroutine[Any, Any, Response], Awaitable[Response]],
]

ViewHandlerVarArgsFun = Callable[
    [Arg(View), Arg(Request), VarArg(Any), KwArg(Any)],
    Union[Coroutine[Any, Any, Response], Awaitable[Response]],
]

ViewHandlerFun = Union[ViewHandler2ArgsFun, ViewHandlerVarArgsFun]
Beispiel #30
0
            )
        if sentSecurely or not request.isSecure():
            # Do not cache the insecure session on the secure request, thanks.
            request.setComponent(ISession, session)  # type: ignore[misc]
        returnValue(session)


_procureProcurerType = Union[Callable[[Any], ISessionProcurer],
                             Callable[[], ISessionProcurer]]

_kleinRenderable = Any
_routeCallable = Any
_kleinCallable = Callable[..., _kleinRenderable]
_kleinDecorator = Callable[[_kleinCallable], _kleinCallable]
_requirerResult = Callable[
    [Arg(_routeCallable, "route"), KwArg(Any)], Callable[[_kleinCallable],
                                                         _kleinCallable], ]


class AuthorizationDenied(Resource, object):
    def __init__(self, interface, instance):
        # type: (IInterface, Any) -> None
        self._interface = interface
        super(AuthorizationDenied, self).__init__()

    def render(self, request):
        # type: (IRequest) -> bytes
        request.setResponseCode(UNAUTHORIZED)
        return "{} DENIED".format(qual(self._interface)).encode("utf-8")