astrada.testing

Test your code that uses the SDK without calling Astrada. Hand-written; not generated.

MockAstrada gives you an astrada.Astrada client whose requests never leave the process: every operation of the API answers with the example from the API definition (responses.json next to this file, regenerated with each release so it follows the API), and you can set the answer of any operation yourself.

from astrada.testing import MockAstrada

def test_lists_subaccounts():
    with MockAstrada() as mock:
        mock.respond("list_subaccounts", body={"_embedded": {"subaccounts": []},
                                               "_links": {"self": {"href": "/subaccounts"}}})
        page = mock.client.subaccounts.list_subaccounts()
        assert page.embedded.subaccounts == []
        assert mock.calls[-1].operation == "list_subaccounts"

To mock an HTTP server instead (for code in another language, or a whole app), run Prism on the definition; see the README.

  1# coding: utf-8
  2"""Test your code that uses the SDK without calling Astrada. Hand-written; not generated.
  3
  4:class:`MockAstrada` gives you an :class:`astrada.Astrada` client whose requests never leave the
  5process: every operation of the API answers with the example from the API definition
  6(``responses.json`` next to this file, regenerated with each release so it follows the API),
  7and you can set the answer of any operation yourself.
  8
  9    from astrada.testing import MockAstrada
 10
 11    def test_lists_subaccounts():
 12        with MockAstrada() as mock:
 13            mock.respond("list_subaccounts", body={"_embedded": {"subaccounts": []},
 14                                                   "_links": {"self": {"href": "/subaccounts"}}})
 15            page = mock.client.subaccounts.list_subaccounts()
 16            assert page.embedded.subaccounts == []
 17            assert mock.calls[-1].operation == "list_subaccounts"
 18
 19To mock an HTTP server instead (for code in another language, or a whole app), run Prism on the
 20definition; see the README.
 21"""
 22
 23import io
 24import json
 25import re
 26from pathlib import Path
 27from typing import Any, Callable, Dict, List, Optional, Tuple, Union
 28from urllib.parse import parse_qs, urlsplit
 29
 30import urllib3
 31
 32from astrada.client import Astrada
 33
 34_RESPONSES = Path(__file__).resolve().parent / "responses.json"
 35
 36Handler = Callable[["MockCall"], Union[Tuple[int, Any], Tuple[int, Any, Dict[str, str]]]]
 37
 38
 39class MockCall:
 40    """One request the mock received."""
 41
 42    def __init__(
 43        self, operation: Optional[str], method: str, path: str, query: Dict[str, List[str]],
 44        body: Any, headers: Dict[str, str],
 45    ) -> None:
 46        self.operation = operation
 47        """The method name (``"list_subaccounts"``), or None for a path no operation has."""
 48        self.method = method
 49        self.path = path
 50        self.query = query
 51        self.body = body
 52        """The JSON request body, parsed."""
 53        self.headers = headers
 54
 55    def __repr__(self) -> str:
 56        return "MockCall(%r, %s %s)" % (self.operation, self.method, self.path)
 57
 58
 59class _Route:
 60    def __init__(self, answer: Dict[str, Any]) -> None:
 61        self.operation: str = answer["operation"]
 62        self.method: str = answer["method"]
 63        self.template: str = answer["path"]
 64        self.pattern = re.compile("^" + re.sub(r"\{[^/]+\}", "[^/]+", answer["path"]) + "$")
 65        self.status: int = answer["status"]
 66        self.body: Any = answer["body"]
 67
 68
 69def _load_routes() -> List[_Route]:
 70    routes = [_Route(answer) for answer in json.loads(_RESPONSES.read_text(encoding="utf-8"))]
 71    # Literal paths before templated ones (/network-bulk-enrollments/open before /{id}).
 72    routes.sort(key=lambda route: route.template.count("{"))
 73    return routes
 74
 75
 76def _response(status: int, body: Any, headers: Optional[Dict[str, str]] = None) -> Any:
 77    data = b"" if body is None else json.dumps(body).encode("utf-8")
 78    all_headers = {"Content-Type": "application/json"} if body is not None else {}
 79    all_headers.update(headers or {})
 80    return urllib3.HTTPResponse(
 81        body=io.BytesIO(data), status=status, headers=all_headers, preload_content=False,
 82        reason="Mock",
 83    )
 84
 85
 86class _MockPool:
 87    def __init__(self, mock: "MockAstrada") -> None:
 88        self.mock = mock
 89
 90    def request(self, method: str, url: str, body: Any = None, fields: Any = None,
 91                headers: Optional[Dict[str, str]] = None, **_: Any) -> Any:
 92        return self.mock._answer(method, url, body, headers or {})
 93
 94    def clear(self) -> None:
 95        return None
 96
 97
 98class MockAstrada:
 99    """An Astrada client that answers from the API definition's examples, in-process.
100
101    :param client: an :class:`astrada.Astrada` client to answer for; default: a new sandbox client
102        with made-up credentials
103    :param environment: the new client's environment (``"sandbox"`` or ``"production"``)
104
105    ``mock.client`` is the client. Its login always succeeds (unless you
106    :meth:`refuse_login`), every operation answers its example, and ``mock.calls`` records what
107    was sent. Retries are turned off on a client the mock makes.
108    """
109
110    def __init__(self, client: Optional[Astrada] = None, *, environment: str = "sandbox") -> None:
111        self.routes = _load_routes()
112        self.calls: List[MockCall] = []
113        self._overrides: Dict[str, Handler] = {}
114        self._login_refused = False
115        self.client = client or Astrada(
116            "mock_account", "mock_client", "mock_secret", environment=environment, retries=0
117        )
118        pool = _MockPool(self)
119        for api_client in (
120            self.client.api_client, self.client.banking_api_client, self.client.sandbox_api_client
121        ):
122            api_client.rest_client.pool_manager = pool  # type: ignore[assignment]
123        if self.client.auth is not None:
124            self.client.auth.pool_manager = pool  # type: ignore[assignment]
125            self.client.auth.clear_cache()
126
127    def __enter__(self) -> "MockAstrada":
128        return self
129
130    def __exit__(self, *exc: Any) -> None:
131        self.client.close()
132
133    def respond(
134        self,
135        operation: str,
136        body: Any = None,
137        status: int = 200,
138        headers: Optional[Dict[str, str]] = None,
139        handler: Optional[Handler] = None,
140    ) -> None:
141        """Set the answer of one operation, by its method name (``"get_subaccount"``).
142
143        Give ``body`` and ``status`` (and ``headers``), or a ``handler`` that receives the
144        :class:`MockCall` and returns ``(status, body)`` or ``(status, body, headers)``. An error
145        status raises the SDK's matching exception, as the real API would.
146        """
147        if operation not in {route.operation for route in self.routes}:
148            raise ValueError("No operation named %r" % operation)
149        if handler is None:
150            fixed = (status, body, headers or {})
151            handler = lambda call: fixed  # noqa: E731
152        self._overrides[operation] = handler
153
154    def reset(self) -> None:
155        """Forget the recorded calls and every answer set with :meth:`respond`."""
156        self.calls.clear()
157        self._overrides.clear()
158        self._login_refused = False
159
160    def refuse_login(self) -> None:
161        """Make the next login fail as wrong credentials do (``AuthenticationError``)."""
162        self._login_refused = True
163        if self.client.auth is not None:
164            self.client.auth.clear_cache()
165
166    def _answer(self, method: str, url: str, body: Any, headers: Dict[str, str]) -> Any:
167        parts = urlsplit(url)
168        path = parts.path
169        if path.endswith("/protocol/openid-connect/token"):
170            if self._login_refused:
171                return _response(401, {"error": "invalid_client",
172                                       "error_description": "Invalid client or Invalid client credentials"})
173            return _response(200, {"access_token": "mock-token", "token_type": "Bearer",
174                                   "expires_in": 3600})
175        base = urlsplit(self.client.base_url).path.rstrip("/")
176        if base and path.startswith(base):
177            path = path[len(base):]
178        try:
179            parsed = json.loads(body) if isinstance(body, (str, bytes)) and body else body
180        except ValueError:
181            parsed = body
182        route = next(
183            (r for r in self.routes if r.method == method.upper() and r.pattern.match(path)), None
184        )
185        call = MockCall(route.operation if route else None, method.upper(), path,
186                        parse_qs(parts.query), parsed, dict(headers))
187        self.calls.append(call)
188        if route is None:
189            return _response(404, {"title": "Not Found", "detail": "No operation for %s %s" % (
190                method.upper(), path)})
191        override = self._overrides.get(route.operation)
192        if override is not None:
193            answer = override(call)
194            status, answer_body = answer[0], answer[1]
195            extra = answer[2] if len(answer) > 2 else {}
196            return _response(status, answer_body, extra)
197        return _response(route.status, route.body)
Handler = typing.Callable[[ForwardRef('MockCall')], typing.Union[typing.Tuple[int, typing.Any], typing.Tuple[int, typing.Any, typing.Dict[str, str]]]]
class MockCall:
40class MockCall:
41    """One request the mock received."""
42
43    def __init__(
44        self, operation: Optional[str], method: str, path: str, query: Dict[str, List[str]],
45        body: Any, headers: Dict[str, str],
46    ) -> None:
47        self.operation = operation
48        """The method name (``"list_subaccounts"``), or None for a path no operation has."""
49        self.method = method
50        self.path = path
51        self.query = query
52        self.body = body
53        """The JSON request body, parsed."""
54        self.headers = headers
55
56    def __repr__(self) -> str:
57        return "MockCall(%r, %s %s)" % (self.operation, self.method, self.path)

One request the mock received.

MockCall( operation: Optional[str], method: str, path: str, query: Dict[str, List[str]], body: Any, headers: Dict[str, str])
43    def __init__(
44        self, operation: Optional[str], method: str, path: str, query: Dict[str, List[str]],
45        body: Any, headers: Dict[str, str],
46    ) -> None:
47        self.operation = operation
48        """The method name (``"list_subaccounts"``), or None for a path no operation has."""
49        self.method = method
50        self.path = path
51        self.query = query
52        self.body = body
53        """The JSON request body, parsed."""
54        self.headers = headers
operation

The method name ("list_subaccounts"), or None for a path no operation has.

method
path
query
body

The JSON request body, parsed.

headers
class MockAstrada:
 99class MockAstrada:
100    """An Astrada client that answers from the API definition's examples, in-process.
101
102    :param client: an :class:`astrada.Astrada` client to answer for; default: a new sandbox client
103        with made-up credentials
104    :param environment: the new client's environment (``"sandbox"`` or ``"production"``)
105
106    ``mock.client`` is the client. Its login always succeeds (unless you
107    :meth:`refuse_login`), every operation answers its example, and ``mock.calls`` records what
108    was sent. Retries are turned off on a client the mock makes.
109    """
110
111    def __init__(self, client: Optional[Astrada] = None, *, environment: str = "sandbox") -> None:
112        self.routes = _load_routes()
113        self.calls: List[MockCall] = []
114        self._overrides: Dict[str, Handler] = {}
115        self._login_refused = False
116        self.client = client or Astrada(
117            "mock_account", "mock_client", "mock_secret", environment=environment, retries=0
118        )
119        pool = _MockPool(self)
120        for api_client in (
121            self.client.api_client, self.client.banking_api_client, self.client.sandbox_api_client
122        ):
123            api_client.rest_client.pool_manager = pool  # type: ignore[assignment]
124        if self.client.auth is not None:
125            self.client.auth.pool_manager = pool  # type: ignore[assignment]
126            self.client.auth.clear_cache()
127
128    def __enter__(self) -> "MockAstrada":
129        return self
130
131    def __exit__(self, *exc: Any) -> None:
132        self.client.close()
133
134    def respond(
135        self,
136        operation: str,
137        body: Any = None,
138        status: int = 200,
139        headers: Optional[Dict[str, str]] = None,
140        handler: Optional[Handler] = None,
141    ) -> None:
142        """Set the answer of one operation, by its method name (``"get_subaccount"``).
143
144        Give ``body`` and ``status`` (and ``headers``), or a ``handler`` that receives the
145        :class:`MockCall` and returns ``(status, body)`` or ``(status, body, headers)``. An error
146        status raises the SDK's matching exception, as the real API would.
147        """
148        if operation not in {route.operation for route in self.routes}:
149            raise ValueError("No operation named %r" % operation)
150        if handler is None:
151            fixed = (status, body, headers or {})
152            handler = lambda call: fixed  # noqa: E731
153        self._overrides[operation] = handler
154
155    def reset(self) -> None:
156        """Forget the recorded calls and every answer set with :meth:`respond`."""
157        self.calls.clear()
158        self._overrides.clear()
159        self._login_refused = False
160
161    def refuse_login(self) -> None:
162        """Make the next login fail as wrong credentials do (``AuthenticationError``)."""
163        self._login_refused = True
164        if self.client.auth is not None:
165            self.client.auth.clear_cache()
166
167    def _answer(self, method: str, url: str, body: Any, headers: Dict[str, str]) -> Any:
168        parts = urlsplit(url)
169        path = parts.path
170        if path.endswith("/protocol/openid-connect/token"):
171            if self._login_refused:
172                return _response(401, {"error": "invalid_client",
173                                       "error_description": "Invalid client or Invalid client credentials"})
174            return _response(200, {"access_token": "mock-token", "token_type": "Bearer",
175                                   "expires_in": 3600})
176        base = urlsplit(self.client.base_url).path.rstrip("/")
177        if base and path.startswith(base):
178            path = path[len(base):]
179        try:
180            parsed = json.loads(body) if isinstance(body, (str, bytes)) and body else body
181        except ValueError:
182            parsed = body
183        route = next(
184            (r for r in self.routes if r.method == method.upper() and r.pattern.match(path)), None
185        )
186        call = MockCall(route.operation if route else None, method.upper(), path,
187                        parse_qs(parts.query), parsed, dict(headers))
188        self.calls.append(call)
189        if route is None:
190            return _response(404, {"title": "Not Found", "detail": "No operation for %s %s" % (
191                method.upper(), path)})
192        override = self._overrides.get(route.operation)
193        if override is not None:
194            answer = override(call)
195            status, answer_body = answer[0], answer[1]
196            extra = answer[2] if len(answer) > 2 else {}
197            return _response(status, answer_body, extra)
198        return _response(route.status, route.body)

An Astrada client that answers from the API definition's examples, in-process.

Parameters
  • client: an astrada.Astrada client to answer for; default: a new sandbox client with made-up credentials
  • environment: the new client's environment ("sandbox" or "production")

mock.client is the client. Its login always succeeds (unless you refuse_login()), every operation answers its example, and mock.calls records what was sent. Retries are turned off on a client the mock makes.

MockAstrada( client: Optional[astrada.Astrada] = None, *, environment: str = 'sandbox')
111    def __init__(self, client: Optional[Astrada] = None, *, environment: str = "sandbox") -> None:
112        self.routes = _load_routes()
113        self.calls: List[MockCall] = []
114        self._overrides: Dict[str, Handler] = {}
115        self._login_refused = False
116        self.client = client or Astrada(
117            "mock_account", "mock_client", "mock_secret", environment=environment, retries=0
118        )
119        pool = _MockPool(self)
120        for api_client in (
121            self.client.api_client, self.client.banking_api_client, self.client.sandbox_api_client
122        ):
123            api_client.rest_client.pool_manager = pool  # type: ignore[assignment]
124        if self.client.auth is not None:
125            self.client.auth.pool_manager = pool  # type: ignore[assignment]
126            self.client.auth.clear_cache()
routes
calls: List[MockCall]
client
def respond( self, operation: str, body: Any = None, status: int = 200, headers: Optional[Dict[str, str]] = None, handler: Optional[Callable[[MockCall], Union[Tuple[int, Any], Tuple[int, Any, Dict[str, str]]]]] = None) -> None:
134    def respond(
135        self,
136        operation: str,
137        body: Any = None,
138        status: int = 200,
139        headers: Optional[Dict[str, str]] = None,
140        handler: Optional[Handler] = None,
141    ) -> None:
142        """Set the answer of one operation, by its method name (``"get_subaccount"``).
143
144        Give ``body`` and ``status`` (and ``headers``), or a ``handler`` that receives the
145        :class:`MockCall` and returns ``(status, body)`` or ``(status, body, headers)``. An error
146        status raises the SDK's matching exception, as the real API would.
147        """
148        if operation not in {route.operation for route in self.routes}:
149            raise ValueError("No operation named %r" % operation)
150        if handler is None:
151            fixed = (status, body, headers or {})
152            handler = lambda call: fixed  # noqa: E731
153        self._overrides[operation] = handler

Set the answer of one operation, by its method name ("get_subaccount").

Give body and status (and headers), or a handler that receives the MockCall and returns (status, body) or (status, body, headers). An error status raises the SDK's matching exception, as the real API would.

def reset(self) -> None:
155    def reset(self) -> None:
156        """Forget the recorded calls and every answer set with :meth:`respond`."""
157        self.calls.clear()
158        self._overrides.clear()
159        self._login_refused = False

Forget the recorded calls and every answer set with respond().

def refuse_login(self) -> None:
161    def refuse_login(self) -> None:
162        """Make the next login fail as wrong credentials do (``AuthenticationError``)."""
163        self._login_refused = True
164        if self.client.auth is not None:
165            self.client.auth.clear_cache()

Make the next login fail as wrong credentials do (AuthenticationError).