Debian Codegraph @

src/globus_sdk/testing/models.py

raw
1 from __future__ import annotations
2
3 import types
4 import typing as t
5
6 import responses
7
8 from globus_sdk._internal.utils import slash_join
9
10
11 class RegisteredResponse:
12 """
13 A mock response along with descriptive metadata to let a fixture "pass data
14 forward" to the consuming test cases. (e.g. a ``GET Task`` fixture which
15 shares the ``task_id`` it uses with consumers via ``.metadata["task_id"]``)
16
17 When initializing a ``RegisteredResponse``, you can use ``path`` and ``service``
18 to describe a path on a Globus service rather than a full URL. The ``metadata``
19 data container is also globus-sdk specific. Most other parameters are wrappers
20 over ``responses`` response characteristics.
21
22 :param path: Path on the target service or full URL if service is null
23 :param service: A known service name like ``"transfer"`` or ``"compute"``. This will
24 be used to deduce the base URL onto which ``path`` should be joined
25 :param method: A string HTTP Method
26 :param headers: HTTP headers for the response
27 :param json: A dict or list structure for a JSON response (mutex with ``body``)
28 :param body: A string response body (mutex with ``json``)
29 :param status: The HTTP status code for the response
30 :param content_type: A Content-Type header value for the response
31 :param match: A tuple or list of ``responses`` matchers
32 :param metadata: A dict of data to store on the response, which allows the usage
33 site which declares the response to pass information forward to the site which
34 activates and tests against the response.
35 """
36
37 _url_map = {
38 "auth": "https://auth.globus.org/",
39 "nexus": "https://nexus.api.globusonline.org/",
40 "transfer": "https://transfer.api.globus.org/",
41 "search": "https://search.api.globus.org/",
42 "gcs": "https://abc.xyz.data.globus.org/api/",
43 "groups": "https://groups.api.globus.org/",
44 "timer": "https://timer.automate.globus.org/",
45 "flows": "https://flows.automate.globus.org/",
46 "compute": "https://compute.api.globus.org/",
47 }
48
49 def __init__(
50 self,
51 *,
52 # path and service are glbous-sdk specific
53 # in `responses`, these are just `url`
54 path: str,
55 service: (
56 t.Literal[
57 "auth",
58 "nexus",
59 "transfer",
60 "search",
61 "gcs",
62 "groups",
63 "timer",
64 "flows",
65 "compute",
66 ]
67 | None
68 ) = None,
69 # method will be passed through to `responses.Response`, so we
70 # support all of the values which it supports
71 method: t.Literal[
72 "GET",
73 "PUT",
74 "POST",
75 "PATCH",
76 "HEAD",
77 "DELETE",
78 "OPTIONS",
79 "CONNECT",
80 "TRACE",
81 ] = "GET",
82 # these parameters are passed through to `response.Response` (or omitted)
83 body: str | None = None,
84 content_type: str | None = None,
85 headers: dict[str, str] | None = None,
86 json: None | list[t.Any] | dict[str, t.Any] = None,
87 status: int = 200,
88 stream: bool | None = None,
89 match: t.Sequence[t.Callable[..., tuple[bool, str]]] | None = None,
90 # metadata is globus-sdk specific
91 metadata: dict[str, t.Any] | None = None,
92 # the following are known parameters to `responses.Response` which
93 # `RegisteredResponse` does not support:
94 # - url: calculated from (path, service)
95 # - auto_calculate_content_length: a bool setting, usually not needed and can
96 # be achieved in user code via `headers`
97 # - passthrough: bool setting allowing calls to be emitted to the services
98 # (undesirable in any ordinary cases)
99 # - match_querystring: legacy param which has been replaced with `match`
100 ) -> None:
101 self.service = service
102
103 if service:
104 self.full_url = slash_join(self._url_map[service], path)
105 else:
106 self.full_url = path
107
108 self.path = path
109
110 # convert the method to uppercase so that specifying `method="post"` will match
111 # correctly -- method matching is case sensitive but we don't need to expose the
112 # possibility of a non-uppercase method
113 self.method = method.upper()
114
115 self.body = body
116 self.content_type = content_type
117 self.headers = headers
118 self.json = json
119 self.status = status
120 self.stream = stream
121
122 self.match = match
123
124 self._metadata = metadata
125
126 self.parent: ResponseSet | ResponseList | None = None
127
128 @property
129 def metadata(self) -> dict[str, t.Any]:
130 if self._metadata is not None:
131 return self._metadata
132 if self.parent is not None:
133 return self.parent.metadata
134 return {}
135
136 def _add_or_replace(
137 self,
138 method: t.Literal["add", "replace"],
139 *,
140 requests_mock: responses.RequestsMock | None = None,
141 ) -> RegisteredResponse:
142 kwargs: dict[str, t.Any] = {
143 "headers": self.headers,
144 "status": self.status,
145 "stream": self.stream,
146 "match_querystring": None,
147 }
148 if self.json is not None:
149 kwargs["json"] = self.json
150 if self.body is not None:
151 kwargs["body"] = self.body
152 if self.content_type is not None:
153 kwargs["content_type"] = self.content_type
154 if self.match is not None:
155 kwargs["match"] = self.match
156
157 if requests_mock is None:
158 use_requests_mock: responses.RequestsMock | types.ModuleType = responses
159 else:
160 use_requests_mock = requests_mock
161
162 if method == "add":
163 use_requests_mock.add(self.method, self.full_url, **kwargs)
164 else:
165 use_requests_mock.replace(self.method, self.full_url, **kwargs)
166 return self
167
168 def add(
169 self, *, requests_mock: responses.RequestsMock | None = None
170 ) -> RegisteredResponse:
171 """
172 Activate the response, adding it to a mocked requests object.
173
174 :param requests_mock: The mocked requests object to use. Defaults to the default
175 provided by the ``responses`` library
176 """
177 return self._add_or_replace("add", requests_mock=requests_mock)
178
179 def replace(
180 self, *, requests_mock: responses.RequestsMock | None = None
181 ) -> RegisteredResponse:
182 """
183 Activate the response, adding it to a mocked requests object and replacing any
184 existing response for the particular path and method.
185
186 :param requests_mock: The mocked requests object to use. Defaults to the default
187 provided by the ``responses`` library
188 """
189 return self._add_or_replace("replace", requests_mock=requests_mock)
190
191
192 class ResponseList:
193 """
194 A series of unnamed responses, meant to be used and referred to as a single case
195 within a ResponseSet.
196
197 This can be stored in a ``ResponseSet`` as a case, describing a series
198 of responses registered to a specific name (e.g. to describe a paginated API).
199 """
200
201 def __init__(
202 self,
203 *data: RegisteredResponse,
204 metadata: dict[str, t.Any] | None = None,
205 ) -> None:
206 self.responses = list(data)
207 self._metadata = metadata
208 self.parent: ResponseSet | None = None
209 for r in data:
210 r.parent = self
211
212 @property
213 def metadata(self) -> dict[str, t.Any]:
214 if self._metadata is not None:
215 return self._metadata
216 if self.parent is not None:
217 return self.parent.metadata
218 return {}
219
220 def add(
221 self, *, requests_mock: responses.RequestsMock | None = None
222 ) -> ResponseList:
223 for r in self.responses:
224 r.add(requests_mock=requests_mock)
225 return self
226
227
228 class ResponseSet:
229 """
230 A collection of mock responses, potentially all meant to be activated together
231 (``.activate_all()``), or to be individually selected as options/alternatives
232 (``.activate("case_foo")``).
233
234 On init, this implicitly sets the parent of any response objects to this response
235 set. On register() it does not do so automatically.
236 """
237
238 def __init__(
239 self,
240 metadata: dict[str, t.Any] | None = None,
241 **kwargs: RegisteredResponse | ResponseList,
242 ) -> None:
243 self.metadata = metadata or {}
244 self._data: dict[str, RegisteredResponse | ResponseList] = {**kwargs}
245 for res in self._data.values():
246 res.parent = self
247
248 def register(self, case: str, value: RegisteredResponse) -> None:
249 self._data[case] = value
250
251 def lookup(self, case: str) -> RegisteredResponse | ResponseList:
252 try:
253 return self._data[case]
254 except KeyError as e:
255 raise LookupError("did not find a matching registered response") from e
256
257 def __bool__(self) -> bool:
258 return bool(self._data)
259
260 def __iter__(
261 self,
262 ) -> t.Iterator[RegisteredResponse | ResponseList]:
263 return iter(self._data.values())
264
265 def cases(self) -> t.Iterator[str]:
266 return iter(self._data)
267
268 def activate(
269 self,
270 case: str,
271 *,
272 requests_mock: responses.RequestsMock | None = None,
273 ) -> RegisteredResponse | ResponseList:
274 return self.lookup(case).add(requests_mock=requests_mock)
275
276 def activate_all(
277 self, *, requests_mock: responses.RequestsMock | None = None
278 ) -> ResponseSet:
279 for x in self:
280 x.add(requests_mock=requests_mock)
281 return self
282
283 @classmethod
284 def from_dict(
285 cls,
286 data: t.Mapping[
287 str,
288 (dict[str, t.Any] | list[dict[str, t.Any]]),
289 ],
290 metadata: dict[str, t.Any] | None = None,
291 **kwargs: dict[str, dict[str, t.Any]],
292 ) -> ResponseSet:
293 # constructor which expects native dicts and converts them to RegisteredResponse
294 # objects, then puts them into the ResponseSet
295 def handle_value(
296 v: dict[str, t.Any] | list[dict[str, t.Any]],
297 ) -> RegisteredResponse | ResponseList:
298 if isinstance(v, dict):
299 return RegisteredResponse(**v)
300 else:
301 return ResponseList(*(RegisteredResponse(**subv) for subv in v))
302
303 reassembled_data: dict[str, RegisteredResponse | ResponseList] = {
304 k: handle_value(v) for k, v in data.items()
305 }
306 return cls(metadata=metadata, **reassembled_data)