Debian Codegraph @

src/launchpadlib/testing/helpers.py

raw
1 # Copyright 2008 Canonical Ltd.
2
3 # This file is part of launchpadlib.
4 #
5 # launchpadlib is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Lesser General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 #
10 # launchpadlib is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
14 #
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with launchpadlib. If not, see
17 # <http://www.gnu.org/licenses/>.
18
19 """launchpadlib testing helpers."""
20
21 __all__ = [
22 "BadSaveKeyring",
23 "fake_keyring",
24 "FauxSocketModule",
25 "InMemoryKeyring",
26 "NoNetworkAuthorizationEngine",
27 "NoNetworkLaunchpad",
28 "TestableLaunchpad",
29 "nopriv_read_nonprivate",
30 "salgado_read_nonprivate",
31 "salgado_with_full_permissions",
32 ]
33
34 from contextlib import contextmanager
35
36 import launchpadlib
37 from launchpadlib.launchpad import Launchpad
38 from launchpadlib.credentials import (
39 AccessToken,
40 Credentials,
41 RequestTokenAuthorizationEngine,
42 )
43
44
45 missing = object()
46
47
48 def assert_keyring_not_imported():
49 assert (
50 getattr(launchpadlib.credentials, "keyring", missing) is missing
51 ), "During tests the real keyring module should never be imported."
52
53
54 class NoNetworkAuthorizationEngine(RequestTokenAuthorizationEngine):
55 """An authorization engine that doesn't open a web browser.
56
57 You can use this to test the creation of Launchpad objects and the
58 storing of credentials. You can't use it to interact with the web
59 service, since it only pretends to authorize its OAuth request tokens.
60 """
61
62 ACCESS_TOKEN_KEY = "access_key:84"
63
64 def __init__(self, *args, **kwargs):
65 super().__init__(*args, **kwargs)
66 # Set up some instrumentation.
67 self.request_tokens_obtained = 0
68 self.access_tokens_obtained = 0
69
70 def get_request_token(self, credentials):
71 """Pretend to get a request token from the server.
72
73 We do this by simply returning a static token ID.
74 """
75 self.request_tokens_obtained += 1
76 return "request_token:42"
77
78 def make_end_user_authorize_token(self, credentials, request_token):
79 """Pretend to exchange a request token for an access token.
80
81 We do this by simply setting the access_token property.
82 """
83 credentials.access_token = AccessToken(
84 self.ACCESS_TOKEN_KEY, "access_secret:168"
85 )
86 self.access_tokens_obtained += 1
87
88
89 class NoNetworkLaunchpad(Launchpad):
90 """A Launchpad instance for tests with no network access.
91
92 It's only useful for making sure that certain methods were called.
93 It can't be used to interact with the API.
94 """
95
96 def __init__(
97 self,
98 credentials,
99 authorization_engine,
100 credential_store,
101 service_root,
102 cache,
103 timeout,
104 proxy_info,
105 version,
106 ):
107 self.credentials = credentials
108 self.authorization_engine = authorization_engine
109 self.credential_store = credential_store
110 self.passed_in_args = dict(
111 service_root=service_root,
112 cache=cache,
113 timeout=timeout,
114 proxy_info=proxy_info,
115 version=version,
116 )
117
118 @classmethod
119 def authorization_engine_factory(cls, *args):
120 return NoNetworkAuthorizationEngine(*args)
121
122
123 class TestableLaunchpad(Launchpad):
124 """A base class for talking to the testing root service."""
125
126 def __init__(
127 self,
128 credentials,
129 authorization_engine=None,
130 credential_store=None,
131 service_root="test_dev",
132 cache=None,
133 timeout=None,
134 proxy_info=None,
135 version=Launchpad.DEFAULT_VERSION,
136 ):
137 """Provide test-friendly defaults.
138
139 :param authorization_engine: Defaults to None, since a test
140 environment can't use an authorization engine.
141 :param credential_store: Defaults to None, since tests
142 generally pass in fully-formed Credentials objects.
143 :param service_root: Defaults to 'test_dev'.
144 """
145 super().__init__(
146 credentials,
147 authorization_engine,
148 credential_store,
149 service_root=service_root,
150 cache=cache,
151 timeout=timeout,
152 proxy_info=proxy_info,
153 version=version,
154 )
155
156
157 @contextmanager
158 def fake_keyring(fake):
159 """A context manager which injects a testing keyring implementation."""
160 # The real keyring package should never be imported during tests.
161 assert_keyring_not_imported()
162 launchpadlib.credentials.keyring = fake
163 launchpadlib.credentials.NoKeyringError = RuntimeError
164 try:
165 yield
166 finally:
167 del launchpadlib.credentials.keyring
168 del launchpadlib.credentials.NoKeyringError
169
170
171 class FauxSocketModule:
172 """A socket module replacement that provides a fake hostname."""
173
174 def gethostname(self):
175 return "HOSTNAME"
176
177
178 class BadSaveKeyring:
179 """A keyring that generates errors when saving passwords."""
180
181 def get_password(self, service, username):
182 return None
183
184 def set_password(self, service, username, password):
185 raise RuntimeError
186
187
188 class InMemoryKeyring:
189 """A keyring that saves passwords only in memory."""
190
191 def __init__(self):
192 self.data = {}
193
194 def set_password(self, service, username, password):
195 self.data[service, username] = password
196
197 def get_password(self, service, username):
198 return self.data.get((service, username))
199
200
201 class KnownTokens:
202 """Known access token/secret combinations."""
203
204 def __init__(self, token_string, access_secret):
205 self.token_string = token_string
206 self.access_secret = access_secret
207 self.token = AccessToken(token_string, access_secret)
208 self.credentials = Credentials(
209 consumer_name="launchpad-library", access_token=self.token
210 )
211
212 def login(
213 self,
214 cache=None,
215 timeout=None,
216 proxy_info=None,
217 version=Launchpad.DEFAULT_VERSION,
218 ):
219 """Create a Launchpad object using these credentials."""
220 return TestableLaunchpad(
221 self.credentials,
222 cache=cache,
223 timeout=timeout,
224 proxy_info=proxy_info,
225 version=version,
226 )
227
228
229 salgado_with_full_permissions = KnownTokens("salgado-change-anything", "test")
230 salgado_read_nonprivate = KnownTokens("salgado-read-nonprivate", "secret")
231 nopriv_read_nonprivate = KnownTokens("nopriv-read-nonprivate", "mystery")