Debian Codegraph @

src/launchpadlib/tests/test_http.py

raw
1 # Copyright 2010 Canonical Ltd.
2
3 # This file is part of launchpadlib.
4 #
5 # launchpadlib is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU Lesser General Public License as published by the
7 # Free Software Foundation, version 3 of the License.
8 #
9 # launchpadlib is distributed in the hope that it will be useful, but WITHOUT
10 # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
12 # for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public License
15 # along with launchpadlib. If not, see <http://www.gnu.org/licenses/>.
16
17 """Tests for the LaunchpadOAuthAwareHTTP class."""
18
19 from collections import deque
20 from json import dumps, JSONDecodeError
21 import tempfile
22 import unittest
23
24 from launchpadlib.errors import Unauthorized
25 from launchpadlib.credentials import UnencryptedFileCredentialStore
26 from launchpadlib.launchpad import (
27 Launchpad,
28 LaunchpadOAuthAwareHttp,
29 )
30 from launchpadlib.testing.helpers import NoNetworkAuthorizationEngine
31
32
33 # The simplest WADL that looks like a representation of the service root.
34 SIMPLE_WADL = b"""<?xml version="1.0"?>
35 <application xmlns="http://research.sun.com/wadl/2006/10">
36 <resources base="http://www.example.com/">
37 <resource path="" type="#service-root"/>
38 </resources>
39
40 <resource_type id="service-root">
41 <method name="GET" id="service-root-get">
42 <response>
43 <representation href="#service-root-json"/>
44 </response>
45 </method>
46 </resource_type>
47
48 <representation id="service-root-json" mediaType="application/json"/>
49 </application>
50 """
51
52 # The simplest JSON that looks like a representation of the service root.
53 SIMPLE_JSON = dumps({}).encode("utf-8")
54
55
56 class Response:
57 """A fake HTTP response object."""
58
59 def __init__(self, status, content):
60 self.status = status
61 self.content = content
62
63
64 class SimulatedResponsesHttp(LaunchpadOAuthAwareHttp):
65 """Responds to HTTP requests by shifting responses off a stack."""
66
67 def __init__(self, responses, *args):
68 """Constructor.
69
70 :param responses: A list of HttpResponse objects to use
71 in response to requests.
72 """
73 super().__init__(*args)
74 self.sent_responses = []
75 self.unsent_responses = responses
76 self.cache = None
77
78 def _request(self, *args):
79 response = self.unsent_responses.popleft()
80 self.sent_responses.append(response)
81 return self.retry_on_bad_token(response, response.content, *args)
82
83
84 class SimulatedResponsesLaunchpad(Launchpad):
85
86 # Every Http object generated by this class will return these
87 # responses, in order.
88 responses = []
89
90 def httpFactory(self, *args):
91 return SimulatedResponsesHttp(
92 deque(self.responses), self, self.authorization_engine, *args
93 )
94
95 @classmethod
96 def credential_store_factory(cls, credential_save_failed):
97 return UnencryptedFileCredentialStore(
98 tempfile.mkstemp()[1], credential_save_failed
99 )
100
101
102 class SimulatedResponsesTestCase(unittest.TestCase):
103 """Test cases that give fake responses to launchpad's HTTP requests."""
104
105 def setUp(self):
106 """Clear out the list of simulated responses."""
107 SimulatedResponsesLaunchpad.responses = []
108 self.engine = NoNetworkAuthorizationEngine(
109 "http://api.example.com/", "application name"
110 )
111
112 def launchpad_with_responses(self, *responses):
113 """Use simulated HTTP responses to get a Launchpad object.
114
115 The given Response objects will be sent, in order, in response
116 to launchpadlib's requests.
117
118 :param responses: Some number of Response objects.
119 :return: The Launchpad object, assuming that errors in the
120 simulated requests didn't prevent one from being created.
121 """
122 SimulatedResponsesLaunchpad.responses = responses
123 return SimulatedResponsesLaunchpad.login_with(
124 "application name", authorization_engine=self.engine
125 )
126
127
128 class TestAbilityToParseData(SimulatedResponsesTestCase):
129 """Test launchpadlib's ability to handle the sample data.
130
131 To create a Launchpad object, two HTTP requests must succeed and
132 return usable data: the requests for the WADL and JSON
133 representations of the service root. This test shows that the
134 minimal data in SIMPLE_WADL and SIMPLE_JSON is good enough to
135 create a Launchpad object.
136 """
137
138 def test_minimal_data(self):
139 """Make sure that launchpadlib can use the minimal data."""
140 self.launchpad_with_responses(
141 Response(200, SIMPLE_WADL), Response(200, SIMPLE_JSON)
142 )
143
144 def test_bad_wadl(self):
145 """Show that bad WADL causes an exception."""
146 self.assertRaises(
147 SyntaxError,
148 self.launchpad_with_responses,
149 Response(200, b"This is not WADL."),
150 Response(200, SIMPLE_JSON),
151 )
152
153 def test_bad_json(self):
154 """Show that bad JSON causes an exception."""
155 self.assertRaises(
156 JSONDecodeError,
157 self.launchpad_with_responses,
158 Response(200, SIMPLE_WADL),
159 Response(200, b"This is not JSON."),
160 )
161
162
163 class TestTokenFailureDuringRequest(SimulatedResponsesTestCase):
164 """Test access token failures during a request.
165
166 launchpadlib makes two HTTP requests on startup, to get the WADL
167 and JSON representations of the service root. If Launchpad
168 receives a 401 error during this process, it will acquire a fresh
169 access token and try again.
170 """
171
172 def test_good_token(self):
173 """If our token is good, we never get another one."""
174 SimulatedResponsesLaunchpad.responses = [
175 Response(200, SIMPLE_WADL),
176 Response(200, SIMPLE_JSON),
177 ]
178
179 self.assertEqual(self.engine.access_tokens_obtained, 0)
180 SimulatedResponsesLaunchpad.login_with(
181 "application name", authorization_engine=self.engine
182 )
183 self.assertEqual(self.engine.access_tokens_obtained, 1)
184
185 def test_bad_token(self):
186 """If our token is bad, we get another one."""
187 SimulatedResponsesLaunchpad.responses = [
188 Response(401, b"Invalid token."),
189 Response(200, SIMPLE_WADL),
190 Response(200, SIMPLE_JSON),
191 ]
192
193 self.assertEqual(self.engine.access_tokens_obtained, 0)
194 SimulatedResponsesLaunchpad.login_with(
195 "application name", authorization_engine=self.engine
196 )
197 self.assertEqual(self.engine.access_tokens_obtained, 2)
198
199 def test_expired_token(self):
200 """If our token is expired, we get another one."""
201
202 SimulatedResponsesLaunchpad.responses = [
203 Response(401, b"Expired token."),
204 Response(200, SIMPLE_WADL),
205 Response(200, SIMPLE_JSON),
206 ]
207
208 self.assertEqual(self.engine.access_tokens_obtained, 0)
209 SimulatedResponsesLaunchpad.login_with(
210 "application name", authorization_engine=self.engine
211 )
212 self.assertEqual(self.engine.access_tokens_obtained, 2)
213
214 def test_unknown_token(self):
215 """If our token is unknown, we get another one."""
216
217 SimulatedResponsesLaunchpad.responses = [
218 Response(401, b"Unknown access token."),
219 Response(200, SIMPLE_WADL),
220 Response(200, SIMPLE_JSON),
221 ]
222
223 self.assertEqual(self.engine.access_tokens_obtained, 0)
224 SimulatedResponsesLaunchpad.login_with(
225 "application name", authorization_engine=self.engine
226 )
227 self.assertEqual(self.engine.access_tokens_obtained, 2)
228
229 def test_delayed_error(self):
230 """We get another token no matter when the error happens."""
231 SimulatedResponsesLaunchpad.responses = [
232 Response(200, SIMPLE_WADL),
233 Response(401, b"Expired token."),
234 Response(200, SIMPLE_JSON),
235 ]
236
237 self.assertEqual(self.engine.access_tokens_obtained, 0)
238 SimulatedResponsesLaunchpad.login_with(
239 "application name", authorization_engine=self.engine
240 )
241 self.assertEqual(self.engine.access_tokens_obtained, 2)
242
243 def test_many_errors(self):
244 """We'll keep getting new tokens as long as tokens are the problem."""
245 SimulatedResponsesLaunchpad.responses = [
246 Response(401, b"Invalid token."),
247 Response(200, SIMPLE_WADL),
248 Response(401, b"Expired token."),
249 Response(401, b"Invalid token."),
250 Response(200, SIMPLE_JSON),
251 ]
252 self.assertEqual(self.engine.access_tokens_obtained, 0)
253 SimulatedResponsesLaunchpad.login_with(
254 "application name", authorization_engine=self.engine
255 )
256 self.assertEqual(self.engine.access_tokens_obtained, 4)
257
258 def test_other_unauthorized(self):
259 """If the token is not at fault, a 401 error raises an exception."""
260
261 SimulatedResponsesLaunchpad.responses = [
262 Response(401, b"Some other error.")
263 ]
264
265 self.assertRaises(
266 Unauthorized,
267 SimulatedResponsesLaunchpad.login_with,
268 "application name",
269 authorization_engine=self.engine,
270 )