Debian Codegraph @

src/globus_sdk/testing/registry.py

raw
1 from __future__ import annotations
2
3 import importlib
4 import re
5 import typing as t
6
7 import responses
8
9 import globus_sdk
10 import globus_sdk.experimental
11
12 from .models import RegisteredResponse, ResponseList, ResponseSet
13
14 # matches "V2", "V11", etc as a string suffix
15 # see usage in _resolve_qualname for details
16 _SUFFIX_VERSION_MATCH_PATTERN = re.compile(r"V\d+$")
17
18 _RESPONSE_SET_REGISTRY: dict[t.Any, ResponseSet] = {}
19
20
21 def register_response_set(
22 set_id: t.Any,
23 rset: ResponseSet | dict[str, dict[str, t.Any]],
24 metadata: dict[str, t.Any] | None = None,
25 ) -> ResponseSet:
26 """
27 Register a new ``ResponseSet`` object.
28
29 The response set may be specified as a dict or a ResponseSet object.
30
31 :param set_id: The ID used to retrieve the response set later
32 :param rset: The response set to register
33 :param metadata: Metadata dict to assign to the response set when it is specified
34 as a dict. If the response set is an object, this argument is ignored.
35 """
36 if isinstance(rset, dict):
37 rset = ResponseSet.from_dict(rset, metadata=metadata)
38 _RESPONSE_SET_REGISTRY[set_id] = rset
39 return rset
40
41
42 def _resolve_qualname(name: str) -> str:
43 if "." not in name:
44 return name
45 prefix, suffix = name.split(".", 1)
46
47 # something from globus_sdk, could be a client class
48 if hasattr(globus_sdk, prefix):
49 maybe_client = getattr(globus_sdk, prefix)
50 elif hasattr(globus_sdk.experimental, prefix):
51 maybe_client = getattr(globus_sdk.experimental, prefix)
52 else:
53 return name
54
55 # there are a dozen ways of writing this check, but the point is
56 # "if it's not a client class"
57 if not (
58 isinstance(maybe_client, type)
59 and issubclass(maybe_client, globus_sdk.BaseClient)
60 ):
61 return name
62
63 assert issubclass(maybe_client, globus_sdk.BaseClient)
64 service_name = maybe_client.service_name
65
66 # TODO: Consider alternative strategies for mapping versioned clients
67 # to subdirs. For now, we do it by name matching.
68 #
69 # 'prefix' is the client name, and it may end in `V2`, `V3`, etc.
70 # in which case we want to map it to a subdir
71 suffix_version_match = _SUFFIX_VERSION_MATCH_PATTERN.search(prefix)
72 if suffix_version_match:
73 suffix = f"{suffix_version_match.group(0).lower()}.{suffix}"
74
75 return f"{service_name}.{suffix}"
76
77
78 def get_response_set(set_id: t.Any) -> ResponseSet:
79 """
80 Lookup a ``ResponseSet`` as in ``load_response_set``, but without
81 activating it.
82
83 :param set_id: The ID used to retrieve the response set. Typically a string, but
84 could be any key used to register a response set.
85 """
86 # first priority: check the explicit registry
87 if set_id in _RESPONSE_SET_REGISTRY:
88 return _RESPONSE_SET_REGISTRY[set_id]
89
90 # if ID is a string, it's the (optionally dotted) name of a module
91 if isinstance(set_id, str):
92 module_name = f"globus_sdk.testing.data.{set_id}"
93 else:
94 assert hasattr(
95 set_id, "__qualname__"
96 ), f"cannot load response set from {type(set_id)}"
97 # support modules like
98 # globus_sdk/testing/data/auth/get_identities.py
99 # for lookups like
100 # get_response_set(AuthClient.get_identities)
101 module_name = (
102 f"globus_sdk.testing.data.{_resolve_qualname(set_id.__qualname__)}"
103 )
104
105 # after that, check the built-in "registry" built from modules
106 try:
107 module = importlib.import_module(module_name)
108 except ModuleNotFoundError as e:
109 raise ValueError(f"no fixtures defined for {module_name}") from e
110 assert isinstance(module.RESPONSES, ResponseSet)
111 return module.RESPONSES
112
113
114 def load_response_set(
115 set_id: t.Any, *, requests_mock: responses.RequestsMock | None = None
116 ) -> ResponseSet:
117 """
118 Optionally lookup a response set and activate all of its responses. If
119 passed a ``ResponseSet``, activate it, otherwise the first argument is an
120 ID used for lookup.
121
122 :param set_id: The ID used to retrieve the response set. Typically a string, but
123 could be any key used to register a response set.
124 :param requests_mock: A ``responses`` library mock to use for response mocking,
125 defaults to the ``responses`` default
126 """
127 if isinstance(set_id, ResponseSet):
128 return set_id.activate_all(requests_mock=requests_mock)
129 ret = get_response_set(set_id)
130 ret.activate_all(requests_mock=requests_mock)
131 return ret
132
133
134 def load_response(
135 set_id: t.Any,
136 *,
137 case: str = "default",
138 requests_mock: responses.RequestsMock | None = None,
139 ) -> RegisteredResponse | ResponseList:
140 """
141 Optionally lookup and activate an individual response. If given a
142 ``RegisteredResponse``, activate it, otherwise the first argument is an ID
143 of a ``ResponseSet`` used for lookup. By default, looks for the response
144 registered under ``case="default"``.
145
146 :param set_id: The ID used to retrieve the response set. Typically a string, but
147 could be any key used to register a response set.
148 :param case: The name of a case within the response set to load, ignoring all other
149 registered mocks in the response set
150 :param requests_mock: A ``responses`` library mock to use for response mocking,
151 defaults to the ``responses`` default
152 """
153 if isinstance(set_id, RegisteredResponse):
154 return set_id.add(requests_mock=requests_mock)
155 rset = get_response_set(set_id)
156 return rset.activate(case, requests_mock=requests_mock)