Debian Codegraph @

keystoneclient/tests/unit/test_http.py

raw symbols SCIP
1 # Copyright 2013 OpenStack Foundation
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 import io
16 import logging
17
18 from testtools import matchers
19
20 from keystoneclient import exceptions
21 from keystoneclient import httpclient
22 from keystoneclient import session
23 from keystoneclient.tests.unit import utils
24
25
26 RESPONSE_BODY = '{"hi": "there"}'
27
28
29 def get_client():
30 cl = httpclient.HTTPClient(username="username", password="password",
31 project_id="tenant", auth_url="auth_test")
32 return cl
33
34
35 def get_authed_client():
36 cl = get_client()
37 cl.management_url = "http://127.0.0.1:5000"
38 cl.auth_token = "token"
39 return cl
40
41
42 class ClientTest(utils.TestCase):
43
44 TEST_URL = 'http://127.0.0.1:5000/hi'
45
46 def test_unauthorized_client_requests(self):
47 # Creating a HTTPClient not using session is deprecated.
48 with self.deprecations.expect_deprecations_here():
49 cl = get_client()
50 self.assertRaises(exceptions.AuthorizationFailure, cl.get, '/hi')
51 self.assertRaises(exceptions.AuthorizationFailure, cl.post, '/hi')
52 self.assertRaises(exceptions.AuthorizationFailure, cl.put, '/hi')
53 self.assertRaises(exceptions.AuthorizationFailure, cl.delete, '/hi')
54
55 def test_get(self):
56 # Creating a HTTPClient not using session is deprecated.
57 with self.deprecations.expect_deprecations_here():
58 cl = get_authed_client()
59
60 self.stub_url('GET', text=RESPONSE_BODY)
61
62 with self.deprecations.expect_deprecations_here():
63 resp, body = cl.get("/hi")
64 self.assertEqual(self.requests_mock.last_request.method, 'GET')
65 self.assertEqual(self.requests_mock.last_request.url, self.TEST_URL)
66
67 self.assertRequestHeaderEqual('X-Auth-Token', 'token')
68 self.assertRequestHeaderEqual('User-Agent', httpclient.USER_AGENT)
69
70 # Automatic JSON parsing
71 self.assertEqual(body, {"hi": "there"})
72
73 def test_get_error_with_plaintext_resp(self):
74 # Creating a HTTPClient not using session is deprecated.
75 with self.deprecations.expect_deprecations_here():
76 cl = get_authed_client()
77 self.stub_url('GET', status_code=400,
78 text='Some evil plaintext string')
79
80 self.assertRaises(exceptions.BadRequest, cl.get, '/hi')
81
82 def test_get_error_with_json_resp(self):
83 # Creating a HTTPClient not using session is deprecated.
84 with self.deprecations.expect_deprecations_here():
85 cl = get_authed_client()
86 err_response = {
87 "error": {
88 "code": 400,
89 "title": "Error title",
90 "message": "Error message string"
91 }
92 }
93 self.stub_url('GET', status_code=400, json=err_response)
94 exc_raised = False
95 try:
96 with self.deprecations.expect_deprecations_here():
97 cl.get('/hi')
98 except exceptions.BadRequest as exc:
99 exc_raised = True
100 self.assertEqual(exc.message, "Error message string (HTTP 400)")
101 self.assertTrue(exc_raised, 'Exception not raised.')
102
103 def test_post(self):
104 # Creating a HTTPClient not using session is deprecated.
105 with self.deprecations.expect_deprecations_here():
106 cl = get_authed_client()
107
108 self.stub_url('POST')
109 with self.deprecations.expect_deprecations_here():
110 cl.post("/hi", body=[1, 2, 3])
111
112 self.assertEqual(self.requests_mock.last_request.method, 'POST')
113 self.assertEqual(self.requests_mock.last_request.body, '[1, 2, 3]')
114
115 self.assertRequestHeaderEqual('X-Auth-Token', 'token')
116 self.assertRequestHeaderEqual('Content-Type', 'application/json')
117 self.assertRequestHeaderEqual('User-Agent', httpclient.USER_AGENT)
118
119 def test_forwarded_for(self):
120 ORIGINAL_IP = "10.100.100.1"
121 # Creating a HTTPClient not using session is deprecated.
122 with self.deprecations.expect_deprecations_here():
123 cl = httpclient.HTTPClient(username="username",
124 password="password",
125 project_id="tenant",
126 auth_url="auth_test",
127 original_ip=ORIGINAL_IP)
128
129 self.stub_url('GET')
130
131 with self.deprecations.expect_deprecations_here():
132 cl.request(self.TEST_URL, 'GET')
133 forwarded = "for=%s;by=%s" % (ORIGINAL_IP, httpclient.USER_AGENT)
134 self.assertRequestHeaderEqual('Forwarded', forwarded)
135
136 def test_client_deprecated(self):
137 # Can resolve symbols from the keystoneclient.client module.
138 # keystoneclient.client was deprecated and renamed to
139 # keystoneclient.httpclient. This tests that keystoneclient.client
140 # can still be used.
141
142 from keystoneclient import client
143
144 # These statements will raise an AttributeError if the symbol isn't
145 # defined in the module.
146
147 client.HTTPClient
148
149
150 class BasicRequestTests(utils.TestCase):
151
152 url = 'http://keystone.test.com/'
153
154 def setUp(self):
155 super(BasicRequestTests, self).setUp()
156 self.logger_message = io.StringIO()
157 handler = logging.StreamHandler(self.logger_message)
158 handler.setLevel(logging.DEBUG)
159
160 self.logger = logging.getLogger(session.__name__)
161 level = self.logger.getEffectiveLevel()
162 self.logger.setLevel(logging.DEBUG)
163 self.logger.addHandler(handler)
164
165 self.addCleanup(self.logger.removeHandler, handler)
166 self.addCleanup(self.logger.setLevel, level)
167
168 def request(self, method='GET', response='Test Response', status_code=200,
169 url=None, headers={}, **kwargs):
170 if not url:
171 url = self.url
172
173 self.requests_mock.register_uri(method, url, text=response,
174 status_code=status_code,
175 headers=headers)
176
177 with self.deprecations.expect_deprecations_here():
178 return httpclient.request(url, method, headers=headers, **kwargs)
179
180 def test_basic_params(self):
181 method = 'GET'
182 response = 'Test Response'
183 status = 200
184
185 self.request(method=method, status_code=status, response=response,
186 headers={'Content-Type': 'application/json'})
187
188 self.assertEqual(self.requests_mock.last_request.method, method)
189
190 logger_message = self.logger_message.getvalue()
191
192 self.assertThat(logger_message, matchers.Contains('curl'))
193 self.assertThat(logger_message, matchers.Contains('-X %s' %
194 method))
195 self.assertThat(logger_message, matchers.Contains(self.url))
196
197 self.assertThat(logger_message, matchers.Contains(str(status)))
198 self.assertThat(logger_message, matchers.Contains(response))
199
200 def test_headers(self):
201 headers = {'key': 'val', 'test': 'other'}
202
203 self.request(headers=headers)
204
205 for k, v in headers.items():
206 self.assertRequestHeaderEqual(k, v)
207
208 for header in headers.items():
209 self.assertThat(self.logger_message.getvalue(),
210 matchers.Contains('-H "%s: %s"' % header))
211
212 def test_body(self):
213 data = "BODY DATA"
214 self.request(response=data,
215 headers={'Content-Type': 'application/json'})
216 logger_message = self.logger_message.getvalue()
217 self.assertThat(logger_message, matchers.Contains('BODY:'))
218 self.assertThat(logger_message, matchers.Contains(data))