| 1 |
# Copyright 2012 Canonical Ltd. This software is licensed under the GNU |
| 2 |
# General Public License version 3 (see the file LICENSE). |
| 3 |
|
| 4 |
|
| 5 |
__metaclass__ = type |
| 6 |
|
| 7 |
|
| 8 |
import urllib.request, urllib.error, urllib.parse |
| 9 |
from unittest import TestCase |
| 10 |
import base64 |
| 11 |
|
| 12 |
import pycurl |
| 13 |
from io import BytesIO |
| 14 |
|
| 15 |
from rscalib import ( |
| 16 |
CertificateVerificationFailed, |
| 17 |
CouldNotConnect, |
| 18 |
GetMazaData, |
| 19 |
GetMazaDataAPI1, |
| 20 |
GetMazaDataAPI2, |
| 21 |
GetMazaDataAPI3, |
| 22 |
GetMazaDataAPI4, |
| 23 |
GetMazaDataAPI5, |
| 24 |
PycURLGetter, |
| 25 |
Unauthorized, |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
class FakeGetResponseBody: |
| 30 |
"""Fake to raise a 401 when get_response_body is called.""" |
| 31 |
|
| 32 |
def get_response_body(self, request, verify_ssl): |
| 33 |
raise urllib.error.HTTPError(None, 401, None, None, None) |
| 34 |
|
| 35 |
|
| 36 |
class GetMazaDataFaked(GetMazaData): |
| 37 |
"""Subclass of GetMazaData for testing.""" |
| 38 |
|
| 39 |
api_version = 34 |
| 40 |
|
| 41 |
def __init__(self, username=None, server_root=None): |
| 42 |
super(GetMazaDataFaked, self).__init__(username, username, server_root) |
| 43 |
|
| 44 |
def make_request(self): |
| 45 |
pass |
| 46 |
|
| 47 |
|
| 48 |
class TestGetMazaData(TestCase): |
| 49 |
|
| 50 |
def test_get_data_unauthorized(self): |
| 51 |
"""If a 401 is encountered, Unauthorized is raised.""" |
| 52 |
api_client = GetMazaDataFaked() |
| 53 |
api_client.getter = FakeGetResponseBody() |
| 54 |
with self.assertRaises(Unauthorized): |
| 55 |
api_client.get_data() |
| 56 |
|
| 57 |
def test_get_api_url_default(self): |
| 58 |
"""Default URL is as expected.""" |
| 59 |
url = GetMazaDataFaked().get_api_url() |
| 60 |
self.assertEqual('https://uccs.landscape.canonical.com/api/34/', |
| 61 |
url) |
| 62 |
|
| 63 |
def test_get_api_url_explicit(self): |
| 64 |
"""URL is as expected with specified server_root.""" |
| 65 |
url = GetMazaDataFaked(server_root='http://foo').get_api_url() |
| 66 |
self.assertEqual('http://foo/api/34/', url) |
| 67 |
|
| 68 |
|
| 69 |
class TestGetMazaDataAPI1(TestCase): |
| 70 |
|
| 71 |
def test_make_request(self): |
| 72 |
"""v1 requests have correct URL and no Auth header.""" |
| 73 |
getter = GetMazaDataAPI1('foo', 'bar') |
| 74 |
request = getter.make_request() |
| 75 |
self.assertEqual('https://uccs.landscape.canonical.com/api/1/foo/bar', |
| 76 |
request.get_full_url()) |
| 77 |
self.assertIs(None, request.headers.get('Authorization')) |
| 78 |
|
| 79 |
|
| 80 |
class TestGetMazaDataAPI2(TestCase): |
| 81 |
|
| 82 |
def test_make_request(self): |
| 83 |
"""v2 requests have correct URL and Auth header.""" |
| 84 |
getter = GetMazaDataAPI2('foo', 'bar') |
| 85 |
request = getter.make_request() |
| 86 |
credentials = base64.encodebytes(b'foo:bar').decode('ascii') |
| 87 |
expected = 'Basic %s' % credentials |
| 88 |
self.assertEqual('GET', request.get_method()) |
| 89 |
self.assertEqual('https://uccs.landscape.canonical.com/api/2/foo', |
| 90 |
request.get_full_url()) |
| 91 |
self.assertEqual(expected, request.headers['Authorization']) |
| 92 |
|
| 93 |
|
| 94 |
class TestGetMazaDataAPI3(TestCase): |
| 95 |
|
| 96 |
def test_make_request(self): |
| 97 |
"""v3 requests have correct URL and Auth header.""" |
| 98 |
getter = GetMazaDataAPI3('foo', 'bar') |
| 99 |
request = getter.make_request() |
| 100 |
credentials = base64.encodebytes(b'foo:bar').decode('ascii') |
| 101 |
expected = 'Basic %s' % credentials |
| 102 |
self.assertEqual('GET', request.get_method()) |
| 103 |
self.assertEqual('https://uccs.landscape.canonical.com/api/3/foo', |
| 104 |
request.get_full_url()) |
| 105 |
self.assertEqual(expected, request.headers['Authorization']) |
| 106 |
|
| 107 |
|
| 108 |
class TestGetMazaDataAPI4(TestCase): |
| 109 |
|
| 110 |
def test_make_request(self): |
| 111 |
"""v4 requests have correct URL and Auth header.""" |
| 112 |
getter = GetMazaDataAPI4('foo', 'bar') |
| 113 |
request = getter.make_request() |
| 114 |
credentials = base64.encodebytes(b'foo:bar').decode('ascii') |
| 115 |
expected = 'Basic %s' % credentials |
| 116 |
self.assertEqual('GET', request.get_method()) |
| 117 |
self.assertEqual('https://uccs.landscape.canonical.com/api/4/', |
| 118 |
request.get_full_url()) |
| 119 |
self.assertEqual(expected, request.headers['Authorization']) |
| 120 |
|
| 121 |
|
| 122 |
class TestGetMazaDataAPI5(TestCase): |
| 123 |
|
| 124 |
def test_make_request(self): |
| 125 |
"""v5 requests have correct URL and Auth header.""" |
| 126 |
getter = GetMazaDataAPI5('foo', 'bar') |
| 127 |
request = getter.make_request() |
| 128 |
credentials = base64.encodebytes(b'foo:bar').decode('ascii') |
| 129 |
expected = 'Basic %s' % credentials |
| 130 |
self.assertEqual('GET', request.get_method()) |
| 131 |
self.assertEqual('https://uccs.landscape.canonical.com/api/5/', |
| 132 |
request.get_full_url()) |
| 133 |
self.assertEqual(expected, request.headers['Authorization']) |
| 134 |
|
| 135 |
|
| 136 |
class FakeCurl: |
| 137 |
"""Fake pycurl.Curl for testing PycURLGetter.""" |
| 138 |
|
| 139 |
def __init__(self, response_status=200, body='', header='', |
| 140 |
effective_url='http://example.org/', perform_error=None): |
| 141 |
self.options = {} |
| 142 |
self.info = {} |
| 143 |
self.response_status = response_status |
| 144 |
self.response_header = bytes(header, 'UTF-8') |
| 145 |
self.response_body = bytes(body, 'UTF-8') |
| 146 |
self.effective_url=effective_url |
| 147 |
self.perform_error = perform_error |
| 148 |
|
| 149 |
def setopt(self, key, value): |
| 150 |
self.options[key] = value |
| 151 |
|
| 152 |
def perform(self): |
| 153 |
if self.perform_error is not None: |
| 154 |
raise self.perform_error |
| 155 |
self.info[pycurl.EFFECTIVE_URL] = self.effective_url |
| 156 |
self.info[pycurl.HTTP_CODE] = self.response_status |
| 157 |
self.options[pycurl.HEADERFUNCTION](self.response_header) |
| 158 |
self.options[pycurl.WRITEFUNCTION](self.response_body) |
| 159 |
|
| 160 |
def getinfo(self, key): |
| 161 |
return self.info[key] |
| 162 |
|
| 163 |
|
| 164 |
class TestPycURLGetter(TestCase): |
| 165 |
|
| 166 |
def test_init(self): |
| 167 |
"""Init should set the WRITEFUNCTION and HEADERFUNCTION.""" |
| 168 |
getter = PycURLGetter(FakeCurl()) |
| 169 |
options = getter.curl.options |
| 170 |
self.assertIsNot(None, options[pycurl.WRITEFUNCTION]) |
| 171 |
self.assertIsNot(None, options[pycurl.HEADERFUNCTION]) |
| 172 |
|
| 173 |
@staticmethod |
| 174 |
def make_request(): |
| 175 |
return GetMazaDataAPI3('pete', 'pass').make_request() |
| 176 |
|
| 177 |
def test_prepare_curl(self): |
| 178 |
"""prepare_curl sets URL and auth header.""" |
| 179 |
curl = FakeCurl() |
| 180 |
getter = PycURLGetter(curl) |
| 181 |
request = self.make_request() |
| 182 |
getter.prepare_curl(request) |
| 183 |
self.assertEqual(request.get_full_url(), curl.options[pycurl.URL]) |
| 184 |
self.assertEqual(['Authorization: Basic cGV0ZTpwYXNz\n'], |
| 185 |
curl.options[pycurl.HTTPHEADER]) |
| 186 |
|
| 187 |
def test_prepare_curl_ssl_verify(self): |
| 188 |
"""SSL cert verification can be disabled for testing purposes.""" |
| 189 |
curl = FakeCurl() |
| 190 |
getter = PycURLGetter(curl) |
| 191 |
getter.prepare_curl(self.make_request()) |
| 192 |
self.assertTrue(curl.options[pycurl.SSL_VERIFYPEER]) |
| 193 |
getter.verify_ssl = False |
| 194 |
getter.prepare_curl(self.make_request()) |
| 195 |
self.assertFalse(curl.options[pycurl.SSL_VERIFYPEER]) |
| 196 |
|
| 197 |
def test_handle_reponse(self): |
| 198 |
"""On success, handle_response returns response body.""" |
| 199 |
curl = FakeCurl(body='My body!', header='My header!', |
| 200 |
effective_url='http://example.com/') |
| 201 |
getter = PycURLGetter(curl) |
| 202 |
output = getter.handle_response() |
| 203 |
self.assertEqual('My body!', output) |
| 204 |
self.assertEqual('My header!', getter.response_header.getvalue().decode('UTF-8')) |
| 205 |
self.assertEqual('http://example.com/', |
| 206 |
getter.curl.getinfo(pycurl.EFFECTIVE_URL)) |
| 207 |
|
| 208 |
def test_handle_response_http_error(self): |
| 209 |
"""On http error, handle_response raises urllib.error.HTTPError.""" |
| 210 |
curl = FakeCurl(500, 'My body!', '\nContent-type: fake\n\n') |
| 211 |
getter = PycURLGetter(curl) |
| 212 |
try: |
| 213 |
getter.handle_response() |
| 214 |
except urllib.error.HTTPError as e: |
| 215 |
httpe = e |
| 216 |
else: |
| 217 |
self.fail('No error was raised.') |
| 218 |
try: |
| 219 |
httpe.geturl() |
| 220 |
except AttributeError as attre: |
| 221 |
self.assertEqual("'HTTPError' object has no attribute 'url'", |
| 222 |
str(attre)) |
| 223 |
self.assertEqual(500, httpe.getcode()) |
| 224 |
self.assertEqual('My body!', httpe.msg.decode('UTF-8')) |
| 225 |
self.assertEqual([('Content-type', 'fake')], httpe.hdrs.items()) |
| 226 |
|
| 227 |
def test_handle_response_connection_error(self): |
| 228 |
"""On connection error, handle_response raises CouldNotConnect.""" |
| 229 |
error = pycurl.error(pycurl.E_COULDNT_CONNECT) |
| 230 |
getter = PycURLGetter(FakeCurl(perform_error=error)) |
| 231 |
with self.assertRaises(CouldNotConnect): |
| 232 |
getter.handle_response() |
| 233 |
|
| 234 |
def test_cert_verification_failed(self): |
| 235 |
"""Cert verification error raises CertificateVerificationFailed.""" |
| 236 |
error = pycurl.error(pycurl.E_SSL_CACERT) |
| 237 |
getter = PycURLGetter(FakeCurl(perform_error=error)) |
| 238 |
with self.assertRaises(CertificateVerificationFailed): |
| 239 |
getter.handle_response() |
| 240 |
|
| 241 |
def test_handle_response_pycurl_error(self): |
| 242 |
"""PycURLGetter allows other errors to propagate.""" |
| 243 |
error = pycurl.error(pycurl.E_MULTI_OUT_OF_MEMORY) |
| 244 |
getter = PycURLGetter(FakeCurl(perform_error=error)) |
| 245 |
with self.assertRaises(pycurl.error): |
| 246 |
getter.handle_response() |
| 247 |
|
| 248 |
def test_get_response_body(self): |
| 249 |
"""On success, get_response_body returns response body.""" |
| 250 |
curl = FakeCurl(body='My body!', header='My header!', |
| 251 |
effective_url='http://example.com/') |
| 252 |
request = GetMazaDataAPI3('pete', 'pass').make_request() |
| 253 |
output = PycURLGetter.get_response_body(request, _curl=curl) |
| 254 |
self.assertEqual('My body!', output) |