Statistics
| Branch: | Tag: | Revision:

root / kamaki / clients / test.py @ 058ee9a8

History | View | Annotate | Download (18.6 kB)

1 85898ca4 Stavros Sachtouris
# Copyright 2013 GRNET S.A. All rights reserved.
2 c1004a00 Stavros Sachtouris
#
3 c1004a00 Stavros Sachtouris
# Redistribution and use in source and binary forms, with or
4 c1004a00 Stavros Sachtouris
# without modification, are permitted provided that the following
5 c1004a00 Stavros Sachtouris
# conditions are met:
6 c1004a00 Stavros Sachtouris
#
7 c1004a00 Stavros Sachtouris
#   1. Redistributions of source code must retain the above
8 c1004a00 Stavros Sachtouris
#      copyright notice, this list of conditions and the following
9 c1004a00 Stavros Sachtouris
#      disclaimer.
10 c1004a00 Stavros Sachtouris
#
11 c1004a00 Stavros Sachtouris
#   2. Redistributions in binary form must reproduce the above
12 c1004a00 Stavros Sachtouris
#      copyright notice, this list of conditions and the following
13 c1004a00 Stavros Sachtouris
#      disclaimer in the documentation and/or other materials
14 c1004a00 Stavros Sachtouris
#      provided with the distribution.
15 c1004a00 Stavros Sachtouris
#
16 c1004a00 Stavros Sachtouris
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17 c1004a00 Stavros Sachtouris
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 c1004a00 Stavros Sachtouris
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19 c1004a00 Stavros Sachtouris
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20 c1004a00 Stavros Sachtouris
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 c1004a00 Stavros Sachtouris
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 c1004a00 Stavros Sachtouris
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23 c1004a00 Stavros Sachtouris
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24 c1004a00 Stavros Sachtouris
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 c1004a00 Stavros Sachtouris
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26 c1004a00 Stavros Sachtouris
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 c1004a00 Stavros Sachtouris
# POSSIBILITY OF SUCH DAMAGE.
28 c1004a00 Stavros Sachtouris
#
29 c1004a00 Stavros Sachtouris
# The views and conclusions contained in the software and
30 c1004a00 Stavros Sachtouris
# documentation are those of the authors and should not be
31 c1004a00 Stavros Sachtouris
# interpreted as representing official policies, either expressed
32 c1004a00 Stavros Sachtouris
# or implied, of GRNET S.A.
33 c1004a00 Stavros Sachtouris
34 97baa5c3 Stavros Sachtouris
from mock import patch, call
35 db113224 Stavros Sachtouris
from unittest import makeSuite, TestSuite, TextTestRunner, TestCase
36 db113224 Stavros Sachtouris
from time import sleep
37 85898ca4 Stavros Sachtouris
from inspect import getmembers, isclass
38 97baa5c3 Stavros Sachtouris
from itertools import product
39 9c6c3d69 Stavros Sachtouris
from random import randint
40 c1004a00 Stavros Sachtouris
41 480585cd Stavros Sachtouris
from kamaki.clients.utils.test import Utils
42 3c50df2e Stavros Sachtouris
from kamaki.clients.astakos.test import AstakosClient
43 3c50df2e Stavros Sachtouris
from kamaki.clients.compute.test import ComputeClient, ComputeRestClient
44 058ee9a8 Stavros Sachtouris
from kamaki.clients.network.test import NetworkClient, NetworkRestClient
45 3c50df2e Stavros Sachtouris
from kamaki.clients.cyclades.test import CycladesClient
46 3c50df2e Stavros Sachtouris
from kamaki.clients.cyclades.test import CycladesRestClient
47 3c50df2e Stavros Sachtouris
from kamaki.clients.image.test import ImageClient
48 3c50df2e Stavros Sachtouris
from kamaki.clients.storage.test import StorageClient
49 776b275c Stavros Sachtouris
from kamaki.clients.pithos.test import (
50 776b275c Stavros Sachtouris
    PithosClient, PithosRestClient, PithosMethods)
51 c1004a00 Stavros Sachtouris
52 c1004a00 Stavros Sachtouris
53 f4de4c91 Stavros Sachtouris
class ClientError(TestCase):
54 f4de4c91 Stavros Sachtouris
55 f4de4c91 Stavros Sachtouris
    def test___init__(self):
56 f4de4c91 Stavros Sachtouris
        from kamaki.clients import ClientError
57 f4de4c91 Stavros Sachtouris
        for msg, status, details, exp_msg, exp_status, exp_details in (
58 f4de4c91 Stavros Sachtouris
                ('some msg', 42, 0.28, 0, 0, 0),
59 f4de4c91 Stavros Sachtouris
                ('some msg', 'fail', [], 0, 0, 0),
60 f4de4c91 Stavros Sachtouris
                ('some msg', 42, 'details on error', 0, 0, 0),
61 f4de4c91 Stavros Sachtouris
                (
62 f4de4c91 Stavros Sachtouris
                    '404 {"ExampleError":'
63 f4de4c91 Stavros Sachtouris
                    ' {"message": "a msg", "code": 42, "details": "dets"}}',
64 f4de4c91 Stavros Sachtouris
                    404,
65 f4de4c91 Stavros Sachtouris
                    0,
66 f4de4c91 Stavros Sachtouris
                    '404 ExampleError (a msg)\n',
67 f4de4c91 Stavros Sachtouris
                    42,
68 f4de4c91 Stavros Sachtouris
                    ['dets']),
69 f4de4c91 Stavros Sachtouris
                (
70 f4de4c91 Stavros Sachtouris
                    '404 {"ExampleError":'
71 f4de4c91 Stavros Sachtouris
                    ' {"message": "a msg", "code": 42}}',
72 f4de4c91 Stavros Sachtouris
                    404,
73 f4de4c91 Stavros Sachtouris
                    'details on error',
74 f4de4c91 Stavros Sachtouris
                    '404 ExampleError (a msg)\n',
75 f4de4c91 Stavros Sachtouris
                    42,
76 f4de4c91 Stavros Sachtouris
                    0),
77 f4de4c91 Stavros Sachtouris
                (
78 f4de4c91 Stavros Sachtouris
                    '404 {"ExampleError":'
79 f4de4c91 Stavros Sachtouris
                    ' {"details": "Explain your error"}}',
80 f4de4c91 Stavros Sachtouris
                    404,
81 f4de4c91 Stavros Sachtouris
                    'details on error',
82 f4de4c91 Stavros Sachtouris
                    '404 ExampleError',
83 f4de4c91 Stavros Sachtouris
                    0,
84 f4de4c91 Stavros Sachtouris
                    ['details on error', 'Explain your error']),
85 f4de4c91 Stavros Sachtouris
                ('some msg\n', -10, ['details', 'on', 'error'], 0, 0, 0)):
86 f4de4c91 Stavros Sachtouris
            ce = ClientError(msg, status, details)
87 f4de4c91 Stavros Sachtouris
            exp_msg = exp_msg or (msg if msg.endswith('\n') else msg + '\n')
88 f4de4c91 Stavros Sachtouris
            exp_status = exp_status or status
89 f4de4c91 Stavros Sachtouris
            exp_details = exp_details or details
90 f4de4c91 Stavros Sachtouris
            self.assertEqual('%s' % ce, exp_msg)
91 f4de4c91 Stavros Sachtouris
            self.assertEqual(
92 f4de4c91 Stavros Sachtouris
                exp_status if isinstance(exp_status, int) else 0,
93 f4de4c91 Stavros Sachtouris
                ce.status)
94 f4de4c91 Stavros Sachtouris
            self.assertEqual(exp_details, ce.details)
95 db113224 Stavros Sachtouris
96 f4de4c91 Stavros Sachtouris
97 7fa5c263 Stavros Sachtouris
class RequestManager(TestCase):
98 7fa5c263 Stavros Sachtouris
99 7fa5c263 Stavros Sachtouris
    def setUp(self):
100 7fa5c263 Stavros Sachtouris
        from kamaki.clients import RequestManager
101 7fa5c263 Stavros Sachtouris
        self.RM = RequestManager
102 7fa5c263 Stavros Sachtouris
103 7fa5c263 Stavros Sachtouris
    def test___init__(self):
104 7fa5c263 Stavros Sachtouris
        from kamaki.clients import HTTP_METHODS
105 7fa5c263 Stavros Sachtouris
        method_values = HTTP_METHODS + [v.lower() for v in HTTP_METHODS]
106 7fa5c263 Stavros Sachtouris
        for args in product(
107 7fa5c263 Stavros Sachtouris
                tuple(method_values),
108 7fa5c263 Stavros Sachtouris
                ('http://www.example.com', 'https://example.com', ''),
109 7fa5c263 Stavros Sachtouris
                ('/some/path', '/' ''),
110 7fa5c263 Stavros Sachtouris
                ('Some data', '', None),
111 7fa5c263 Stavros Sachtouris
                (dict(k1='v1', k2='v2'), dict()),
112 7fa5c263 Stavros Sachtouris
                (dict(k='v', k2=None, k3='v3'), dict(k=0), dict(k='v'), {})):
113 7fa5c263 Stavros Sachtouris
            req = self.RM(*args)
114 7fa5c263 Stavros Sachtouris
            method, url, path, data, headers, params = args
115 7fa5c263 Stavros Sachtouris
            self.assertEqual(req.method, method.upper())
116 7fa5c263 Stavros Sachtouris
            for i, (k, v) in enumerate(params.items()):
117 7fa5c263 Stavros Sachtouris
                path += '%s%s%s' % (
118 7fa5c263 Stavros Sachtouris
                    '&' if '?' in path or i else '?',
119 7fa5c263 Stavros Sachtouris
                    k,
120 7fa5c263 Stavros Sachtouris
                    ('=%s' % v) if v else '')
121 7fa5c263 Stavros Sachtouris
            self.assertEqual(req.path, path)
122 7fa5c263 Stavros Sachtouris
            self.assertEqual(req.data, data)
123 7fa5c263 Stavros Sachtouris
            self.assertEqual(req.headers, headers)
124 7fa5c263 Stavros Sachtouris
        self.assertRaises(AssertionError, self.RM, 'GOT', '', '', '', {}, {})
125 7fa5c263 Stavros Sachtouris
126 f8eea8ec Stavros Sachtouris
    @patch('httplib.HTTPConnection.getresponse')
127 f8eea8ec Stavros Sachtouris
    @patch('httplib.HTTPConnection.request')
128 f8eea8ec Stavros Sachtouris
    def test_perform(self, request, getresponse):
129 f8eea8ec Stavros Sachtouris
        from httplib import HTTPConnection
130 f8eea8ec Stavros Sachtouris
        self.RM('GET', 'http://example.com', '/').perform(
131 f8eea8ec Stavros Sachtouris
            HTTPConnection('http', 'example.com'))
132 f8eea8ec Stavros Sachtouris
        expected = dict(body=None, headers={}, url='/', method='GET')
133 f8eea8ec Stavros Sachtouris
        request.assert_called_once_with(**expected)
134 f8eea8ec Stavros Sachtouris
        getresponse.assert_called_once_with()
135 f8eea8ec Stavros Sachtouris
136 f8eea8ec Stavros Sachtouris
137 f8eea8ec Stavros Sachtouris
class FakeResp(object):
138 f8eea8ec Stavros Sachtouris
139 f8eea8ec Stavros Sachtouris
    READ = 'something to read'
140 f8eea8ec Stavros Sachtouris
    HEADERS = dict(k='v', k1='v1', k2='v2')
141 f8eea8ec Stavros Sachtouris
    reason = 'some reason'
142 f8eea8ec Stavros Sachtouris
    status = 42
143 c088076b Stavros Sachtouris
    status_code = 200
144 f8eea8ec Stavros Sachtouris
145 f8eea8ec Stavros Sachtouris
    def read(self):
146 f8eea8ec Stavros Sachtouris
        return self.READ
147 f8eea8ec Stavros Sachtouris
148 f8eea8ec Stavros Sachtouris
    def getheaders(self):
149 f8eea8ec Stavros Sachtouris
        return self.HEADERS.items()
150 f8eea8ec Stavros Sachtouris
151 f8eea8ec Stavros Sachtouris
152 f8eea8ec Stavros Sachtouris
class ResponseManager(TestCase):
153 f8eea8ec Stavros Sachtouris
154 f8eea8ec Stavros Sachtouris
    def setUp(self):
155 f8eea8ec Stavros Sachtouris
        from kamaki.clients import ResponseManager, RequestManager
156 f8eea8ec Stavros Sachtouris
        from httplib import HTTPConnection
157 f8eea8ec Stavros Sachtouris
        self.RM = ResponseManager(RequestManager('GET', 'http://ok', '/'))
158 f8eea8ec Stavros Sachtouris
        self.HTTPC = HTTPConnection
159 f8eea8ec Stavros Sachtouris
160 f8eea8ec Stavros Sachtouris
    def tearDown(self):
161 f8eea8ec Stavros Sachtouris
        FakeResp.READ = 'something to read'
162 f8eea8ec Stavros Sachtouris
163 f8eea8ec Stavros Sachtouris
    @patch('kamaki.clients.RequestManager.perform', return_value=FakeResp())
164 f8eea8ec Stavros Sachtouris
    def test_content(self, perform):
165 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.content, FakeResp.READ)
166 f8eea8ec Stavros Sachtouris
        self.assertTrue(isinstance(perform.call_args[0][0], self.HTTPC))
167 f8eea8ec Stavros Sachtouris
168 f8eea8ec Stavros Sachtouris
    @patch('kamaki.clients.RequestManager.perform', return_value=FakeResp())
169 f8eea8ec Stavros Sachtouris
    def test_text(self, perform):
170 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.text, FakeResp.READ)
171 f8eea8ec Stavros Sachtouris
        self.assertTrue(isinstance(perform.call_args[0][0], self.HTTPC))
172 f8eea8ec Stavros Sachtouris
173 f8eea8ec Stavros Sachtouris
    @patch('kamaki.clients.RequestManager.perform', return_value=FakeResp())
174 f8eea8ec Stavros Sachtouris
    def test_status(self, perform):
175 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.status, FakeResp.reason)
176 f8eea8ec Stavros Sachtouris
        self.assertTrue(isinstance(perform.call_args[0][0], self.HTTPC))
177 f8eea8ec Stavros Sachtouris
178 f8eea8ec Stavros Sachtouris
    @patch('kamaki.clients.RequestManager.perform', return_value=FakeResp())
179 f8eea8ec Stavros Sachtouris
    def test_status_code(self, perform):
180 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.status_code, FakeResp.status)
181 f8eea8ec Stavros Sachtouris
        self.assertTrue(isinstance(perform.call_args[0][0], self.HTTPC))
182 f8eea8ec Stavros Sachtouris
183 f8eea8ec Stavros Sachtouris
    @patch('kamaki.clients.RequestManager.perform', return_value=FakeResp())
184 f8eea8ec Stavros Sachtouris
    def test_headers(self, perform):
185 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.headers, FakeResp.HEADERS)
186 f8eea8ec Stavros Sachtouris
        self.assertTrue(isinstance(perform.call_args[0][0], self.HTTPC))
187 f8eea8ec Stavros Sachtouris
188 f8eea8ec Stavros Sachtouris
    @patch('kamaki.clients.RequestManager.perform', return_value=FakeResp())
189 f8eea8ec Stavros Sachtouris
    def test_json(self, perform):
190 f8eea8ec Stavros Sachtouris
        try:
191 f8eea8ec Stavros Sachtouris
            self.RM.json
192 f8eea8ec Stavros Sachtouris
        except Exception as e:
193 f8eea8ec Stavros Sachtouris
            self.assertEqual(
194 f8eea8ec Stavros Sachtouris
                '%s' % e,
195 f8eea8ec Stavros Sachtouris
                'Response not formated in JSON - '
196 f8eea8ec Stavros Sachtouris
                'No JSON object could be decoded\n')
197 f8eea8ec Stavros Sachtouris
198 f8eea8ec Stavros Sachtouris
        from json import dumps
199 f8eea8ec Stavros Sachtouris
        FakeResp.READ = dumps(FakeResp.HEADERS)
200 f8eea8ec Stavros Sachtouris
        self.RM._request_performed = False
201 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.json, FakeResp.HEADERS)
202 f8eea8ec Stavros Sachtouris
        self.assertTrue(isinstance(perform.call_args[0][0], self.HTTPC))
203 f8eea8ec Stavros Sachtouris
204 f8eea8ec Stavros Sachtouris
    @patch('kamaki.clients.RequestManager.perform', return_value=FakeResp())
205 f8eea8ec Stavros Sachtouris
    def test_all(self, perform):
206 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.content, FakeResp.READ)
207 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.text, FakeResp.READ)
208 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.status, FakeResp.reason)
209 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.status_code, FakeResp.status)
210 f8eea8ec Stavros Sachtouris
        self.assertEqual(self.RM.headers, FakeResp.HEADERS)
211 f8eea8ec Stavros Sachtouris
        perform.assert_called_only_once
212 f8eea8ec Stavros Sachtouris
213 7fa5c263 Stavros Sachtouris
214 f4de4c91 Stavros Sachtouris
class SilentEvent(TestCase):
215 db113224 Stavros Sachtouris
216 27abfa9f Stavros Sachtouris
    def thread_content(self, methodid, raiseException=0):
217 db113224 Stavros Sachtouris
        wait = 0.1
218 f4de4c91 Stavros Sachtouris
        self.can_finish = -1
219 db113224 Stavros Sachtouris
        while self.can_finish < methodid and wait < 4:
220 db113224 Stavros Sachtouris
            sleep(wait)
221 db113224 Stavros Sachtouris
            wait = 2 * wait
222 27abfa9f Stavros Sachtouris
        if raiseException and raiseException == methodid:
223 27abfa9f Stavros Sachtouris
            raise Exception('Some exception')
224 03493855 Stavros Sachtouris
        self._value = methodid
225 db113224 Stavros Sachtouris
        self.assertTrue(wait < 4)
226 db113224 Stavros Sachtouris
227 db113224 Stavros Sachtouris
    def setUp(self):
228 db113224 Stavros Sachtouris
        from kamaki.clients import SilentEvent
229 db113224 Stavros Sachtouris
        self.SE = SilentEvent
230 db113224 Stavros Sachtouris
231 27abfa9f Stavros Sachtouris
    def test_run(self):
232 27abfa9f Stavros Sachtouris
        threads = [self.SE(self.thread_content, i) for i in range(4)]
233 db113224 Stavros Sachtouris
        for t in threads:
234 db113224 Stavros Sachtouris
            t.start()
235 db113224 Stavros Sachtouris
236 db113224 Stavros Sachtouris
        for i in range(4):
237 db113224 Stavros Sachtouris
            self.assertTrue(threads[i].is_alive())
238 db113224 Stavros Sachtouris
            self.can_finish = i
239 db113224 Stavros Sachtouris
            threads[i].join()
240 db113224 Stavros Sachtouris
            self.assertFalse(threads[i].is_alive())
241 db113224 Stavros Sachtouris
242 27abfa9f Stavros Sachtouris
    def test_value(self):
243 27abfa9f Stavros Sachtouris
        threads = [self.SE(self.thread_content, i) for i in range(4)]
244 27abfa9f Stavros Sachtouris
        for t in threads:
245 27abfa9f Stavros Sachtouris
            t.start()
246 27abfa9f Stavros Sachtouris
247 27abfa9f Stavros Sachtouris
        for mid, t in enumerate(threads):
248 27abfa9f Stavros Sachtouris
            if t.is_alive():
249 27abfa9f Stavros Sachtouris
                self.can_finish = mid
250 27abfa9f Stavros Sachtouris
                continue
251 27abfa9f Stavros Sachtouris
            self.assertTrue(mid, t.value)
252 27abfa9f Stavros Sachtouris
253 27abfa9f Stavros Sachtouris
    def test_exception(self):
254 27abfa9f Stavros Sachtouris
        threads = [self.SE(self.thread_content, i, (i % 2)) for i in range(4)]
255 27abfa9f Stavros Sachtouris
        for t in threads:
256 27abfa9f Stavros Sachtouris
            t.start()
257 27abfa9f Stavros Sachtouris
258 27abfa9f Stavros Sachtouris
        for i, t in enumerate(threads):
259 27abfa9f Stavros Sachtouris
            if t.is_alive():
260 27abfa9f Stavros Sachtouris
                self.can_finish = i
261 27abfa9f Stavros Sachtouris
                continue
262 27abfa9f Stavros Sachtouris
            if i % 2:
263 27abfa9f Stavros Sachtouris
                self.assertTrue(isinstance(t.exception, Exception))
264 27abfa9f Stavros Sachtouris
            else:
265 27abfa9f Stavros Sachtouris
                self.assertFalse(t.exception)
266 27abfa9f Stavros Sachtouris
267 db113224 Stavros Sachtouris
268 6a6175c0 Stavros Sachtouris
class FR(object):
269 6a6175c0 Stavros Sachtouris
    json = None
270 6a6175c0 Stavros Sachtouris
    text = None
271 6a6175c0 Stavros Sachtouris
    headers = dict()
272 6a6175c0 Stavros Sachtouris
    content = json
273 6a6175c0 Stavros Sachtouris
    status = None
274 6a6175c0 Stavros Sachtouris
    status_code = 200
275 6a6175c0 Stavros Sachtouris
276 6a6175c0 Stavros Sachtouris
277 5a71b3a1 Stavros Sachtouris
class Client(TestCase):
278 5a71b3a1 Stavros Sachtouris
279 5a71b3a1 Stavros Sachtouris
    def assert_dicts_are_equal(self, d1, d2):
280 5a71b3a1 Stavros Sachtouris
        for k, v in d1.items():
281 5a71b3a1 Stavros Sachtouris
            self.assertTrue(k in d2)
282 5a71b3a1 Stavros Sachtouris
            if isinstance(v, dict):
283 5a71b3a1 Stavros Sachtouris
                self.assert_dicts_are_equal(v, d2[k])
284 5a71b3a1 Stavros Sachtouris
            else:
285 5a71b3a1 Stavros Sachtouris
                self.assertEqual(unicode(v), unicode(d2[k]))
286 5a71b3a1 Stavros Sachtouris
287 5a71b3a1 Stavros Sachtouris
    def setUp(self):
288 5a71b3a1 Stavros Sachtouris
        from kamaki.clients import Client
289 5dde4c83 Stavros Sachtouris
        from kamaki.clients import ClientError as CE
290 5a71b3a1 Stavros Sachtouris
        self.base_url = 'http://example.com'
291 5a71b3a1 Stavros Sachtouris
        self.token = 's0m370k3n=='
292 c088076b Stavros Sachtouris
        self.client = Client(self.base_url, self.token)
293 5dde4c83 Stavros Sachtouris
        self.CE = CE
294 5dde4c83 Stavros Sachtouris
295 5dde4c83 Stavros Sachtouris
    def tearDown(self):
296 5dde4c83 Stavros Sachtouris
        FR.text = None
297 5dde4c83 Stavros Sachtouris
        FR.status = None
298 5dde4c83 Stavros Sachtouris
        FR.status_code = 200
299 6a6175c0 Stavros Sachtouris
        self.client.token = self.token
300 5a71b3a1 Stavros Sachtouris
301 5a71b3a1 Stavros Sachtouris
    def test___init__(self):
302 5a71b3a1 Stavros Sachtouris
        self.assertEqual(self.client.base_url, self.base_url)
303 5a71b3a1 Stavros Sachtouris
        self.assertEqual(self.client.token, self.token)
304 5a71b3a1 Stavros Sachtouris
        self.assert_dicts_are_equal(self.client.headers, {})
305 776b275c Stavros Sachtouris
        DATE_FORMATS = ['%a %b %d %H:%M:%S %Y']
306 5a71b3a1 Stavros Sachtouris
        self.assertEqual(self.client.DATE_FORMATS, DATE_FORMATS)
307 5a71b3a1 Stavros Sachtouris
308 9c6c3d69 Stavros Sachtouris
    def test__init_thread_limit(self):
309 9c6c3d69 Stavros Sachtouris
        exp = 'Nothing set here'
310 9c6c3d69 Stavros Sachtouris
        for faulty in (-1, 0.5, 'a string', {}):
311 9c6c3d69 Stavros Sachtouris
            self.assertRaises(
312 9c6c3d69 Stavros Sachtouris
                AssertionError,
313 9c6c3d69 Stavros Sachtouris
                self.client._init_thread_limit,
314 9c6c3d69 Stavros Sachtouris
                faulty)
315 9c6c3d69 Stavros Sachtouris
            self.assertEqual(exp, getattr(self.client, '_thread_limit', exp))
316 9c6c3d69 Stavros Sachtouris
            self.assertEqual(exp, getattr(self.client, '_elapsed_old', exp))
317 9c6c3d69 Stavros Sachtouris
            self.assertEqual(exp, getattr(self.client, '_elapsed_new', exp))
318 9c6c3d69 Stavros Sachtouris
        self.client._init_thread_limit(42)
319 9c6c3d69 Stavros Sachtouris
        self.assertEqual(42, self.client._thread_limit)
320 9c6c3d69 Stavros Sachtouris
        self.assertEqual(0.0, self.client._elapsed_old)
321 9c6c3d69 Stavros Sachtouris
        self.assertEqual(0.0, self.client._elapsed_new)
322 9c6c3d69 Stavros Sachtouris
323 9c6c3d69 Stavros Sachtouris
    def test__watch_thread_limit(self):
324 9c6c3d69 Stavros Sachtouris
        waits = (
325 9c6c3d69 Stavros Sachtouris
            dict(args=((0.1, 1), (0.1, 2), (0.2, 1), (0.7, 1), (0.3, 2))),
326 9c6c3d69 Stavros Sachtouris
            dict(args=((1.0 - (i / 10.0), (i + 1)) for i in range(7))),
327 9c6c3d69 Stavros Sachtouris
            dict(max=1, args=tuple([(randint(1, 10) / 3.0, 1), ] * 10)),
328 9c6c3d69 Stavros Sachtouris
            dict(
329 9c6c3d69 Stavros Sachtouris
                limit=5,
330 9c6c3d69 Stavros Sachtouris
                args=tuple([
331 9c6c3d69 Stavros Sachtouris
                    (1.0 + (i / 10.0), (5 - i - 1)) for i in range(4)] + [
332 9c6c3d69 Stavros Sachtouris
                    (2.0, 1), (1.9, 2), (2.0, 1), (2.0, 2)])),
333 9c6c3d69 Stavros Sachtouris
            dict(args=tuple(
334 9c6c3d69 Stavros Sachtouris
                [(1.0 - (i / 10.0), (i + 1)) for i in range(7)] + [
335 9c6c3d69 Stavros Sachtouris
                (0.1, 7), (0.2, 6), (0.4, 5), (0.3, 6), (0.2, 7), (0.1, 7)])),)
336 9c6c3d69 Stavros Sachtouris
        for wait_dict in waits:
337 9c6c3d69 Stavros Sachtouris
            if 'max' in wait_dict:
338 9c6c3d69 Stavros Sachtouris
                self.client.MAX_THREADS = wait_dict['max']
339 9c6c3d69 Stavros Sachtouris
            else:
340 9c6c3d69 Stavros Sachtouris
                self.client.MAX_THREADS = 7
341 9c6c3d69 Stavros Sachtouris
            if 'limit' in wait_dict:
342 9c6c3d69 Stavros Sachtouris
                self.client._init_thread_limit(wait_dict['limit'])
343 9c6c3d69 Stavros Sachtouris
            else:
344 9c6c3d69 Stavros Sachtouris
                self.client._init_thread_limit()
345 9c6c3d69 Stavros Sachtouris
                self.client._watch_thread_limit(list())
346 9c6c3d69 Stavros Sachtouris
                self.assertEqual(1, self.client._thread_limit)
347 9c6c3d69 Stavros Sachtouris
            for wait, exp_limit in wait_dict['args']:
348 9c6c3d69 Stavros Sachtouris
                self.client._elapsed_new = wait
349 9c6c3d69 Stavros Sachtouris
                self.client._watch_thread_limit(list())
350 9c6c3d69 Stavros Sachtouris
                self.assertEqual(exp_limit, self.client._thread_limit)
351 9c6c3d69 Stavros Sachtouris
352 5dde4c83 Stavros Sachtouris
    def test__raise_for_status(self):
353 5dde4c83 Stavros Sachtouris
        r = FR()
354 5dde4c83 Stavros Sachtouris
        for txt, sts_code, sts in (('err msg', 10, None), ('', 42, 'Err St')):
355 5dde4c83 Stavros Sachtouris
            r.text, r.status_code, r.status = txt, sts_code, sts
356 5dde4c83 Stavros Sachtouris
            try:
357 5dde4c83 Stavros Sachtouris
                self.client._raise_for_status(r)
358 5dde4c83 Stavros Sachtouris
            except self.CE as ce:
359 5dde4c83 Stavros Sachtouris
                self.assertEqual('%s' % ce, '%s %s\n' % (sts or '', txt))
360 5dde4c83 Stavros Sachtouris
                self.assertEqual(ce.status, sts_code)
361 5dde4c83 Stavros Sachtouris
362 5dde4c83 Stavros Sachtouris
        for msg, sts_code in (('err msg', 32), ('', 42), ('an err', None)):
363 5dde4c83 Stavros Sachtouris
            err = self.CE(msg, sts_code) if sts_code else Exception(msg)
364 5dde4c83 Stavros Sachtouris
            try:
365 5dde4c83 Stavros Sachtouris
                self.client._raise_for_status(err)
366 5dde4c83 Stavros Sachtouris
            except self.CE as ce:
367 5dde4c83 Stavros Sachtouris
                self.assertEqual('%s' % ce, '%s %s\n' % (sts_code or '', msg))
368 5dde4c83 Stavros Sachtouris
                self.assertEqual(ce.status, sts_code or 0)
369 5dde4c83 Stavros Sachtouris
370 c088076b Stavros Sachtouris
    @patch('kamaki.clients.Client.set_header')
371 97baa5c3 Stavros Sachtouris
    def test_set_header(self, SH):
372 97baa5c3 Stavros Sachtouris
        for name, value, condition in product(
373 97baa5c3 Stavros Sachtouris
                ('n4m3', '', None),
374 97baa5c3 Stavros Sachtouris
                ('v41u3', None, 42),
375 97baa5c3 Stavros Sachtouris
                (True, False, None, 1, '')):
376 97baa5c3 Stavros Sachtouris
            self.client.set_header(name, value, iff=condition)
377 c088076b Stavros Sachtouris
            self.assertEqual(
378 c088076b Stavros Sachtouris
                SH.mock_calls[-1], call(name, value, iff=condition))
379 97baa5c3 Stavros Sachtouris
380 c088076b Stavros Sachtouris
    @patch('kamaki.clients.Client.set_param')
381 9af3a427 Stavros Sachtouris
    def test_set_param(self, SP):
382 9af3a427 Stavros Sachtouris
        for name, value, condition in product(
383 9af3a427 Stavros Sachtouris
                ('n4m3', '', None),
384 9af3a427 Stavros Sachtouris
                ('v41u3', None, 42),
385 9af3a427 Stavros Sachtouris
                (True, False, None, 1, '')):
386 9af3a427 Stavros Sachtouris
            self.client.set_param(name, value, iff=condition)
387 c088076b Stavros Sachtouris
            self.assertEqual(
388 c088076b Stavros Sachtouris
                SP.mock_calls[-1], call(name, value, iff=condition))
389 9af3a427 Stavros Sachtouris
390 c088076b Stavros Sachtouris
    @patch('kamaki.clients.RequestManager', return_value=FR)
391 c088076b Stavros Sachtouris
    @patch('kamaki.clients.ResponseManager', return_value=FakeResp())
392 c088076b Stavros Sachtouris
    @patch('kamaki.clients.ResponseManager.__init__')
393 c088076b Stavros Sachtouris
    def test_request(self, Requ, RespInit, Resp):
394 6a6175c0 Stavros Sachtouris
        for args in product(
395 6a6175c0 Stavros Sachtouris
                ('get', '', dict(method='get')),
396 6a6175c0 Stavros Sachtouris
                ('/some/path', None, ['some', 'path']),
397 6a6175c0 Stavros Sachtouris
                (dict(), dict(h1='v1'), dict(h1='v2', h2='v2')),
398 6a6175c0 Stavros Sachtouris
                (dict(), dict(p1='v1'), dict(p1='v2', p2=None, p3='v3')),
399 6a6175c0 Stavros Sachtouris
                (dict(), dict(data='some data'), dict(
400 6a6175c0 Stavros Sachtouris
                    success=400,
401 6a6175c0 Stavros Sachtouris
                    json=dict(k2='v2', k1='v1')))):
402 6a6175c0 Stavros Sachtouris
            method, path, kwargs = args[0], args[1], args[-1]
403 c088076b Stavros Sachtouris
            FakeResp.status_code = kwargs.get('success', 200)
404 c088076b Stavros Sachtouris
            if not (method and (
405 c088076b Stavros Sachtouris
                    isinstance(method, str) or isinstance(
406 c088076b Stavros Sachtouris
                        method, unicode)) and (
407 c088076b Stavros Sachtouris
                    isinstance(path, str) or isinstance(path, unicode))):
408 6a6175c0 Stavros Sachtouris
                self.assertRaises(
409 c088076b Stavros Sachtouris
                    AssertionError, self.client.request, method, path,
410 c088076b Stavros Sachtouris
                    **kwargs)
411 c088076b Stavros Sachtouris
                continue
412 c088076b Stavros Sachtouris
            self.client.request(method, path, **kwargs)
413 c088076b Stavros Sachtouris
            self.assertEqual(
414 c088076b Stavros Sachtouris
                RespInit.mock_calls[-1], call(FR, connection_retry_limit=0))
415 6a6175c0 Stavros Sachtouris
416 6a6175c0 Stavros Sachtouris
    @patch('kamaki.clients.Client.request', return_value='lala')
417 6a6175c0 Stavros Sachtouris
    def _test_foo(self, foo, request):
418 6a6175c0 Stavros Sachtouris
        method = getattr(self.client, foo)
419 6a6175c0 Stavros Sachtouris
        r = method('path', k='v')
420 6a6175c0 Stavros Sachtouris
        self.assertEqual(r, 'lala')
421 6a6175c0 Stavros Sachtouris
        request.assert_called_once_with(foo, 'path', k='v')
422 6a6175c0 Stavros Sachtouris
423 6a6175c0 Stavros Sachtouris
    def test_delete(self):
424 6a6175c0 Stavros Sachtouris
        self._test_foo('delete')
425 6a6175c0 Stavros Sachtouris
426 6a6175c0 Stavros Sachtouris
    def test_get(self):
427 6a6175c0 Stavros Sachtouris
        self._test_foo('get')
428 6a6175c0 Stavros Sachtouris
429 6a6175c0 Stavros Sachtouris
    def test_head(self):
430 6a6175c0 Stavros Sachtouris
        self._test_foo('head')
431 6a6175c0 Stavros Sachtouris
432 6a6175c0 Stavros Sachtouris
    def test_post(self):
433 6a6175c0 Stavros Sachtouris
        self._test_foo('post')
434 6a6175c0 Stavros Sachtouris
435 6a6175c0 Stavros Sachtouris
    def test_put(self):
436 6a6175c0 Stavros Sachtouris
        self._test_foo('put')
437 6a6175c0 Stavros Sachtouris
438 6a6175c0 Stavros Sachtouris
    def test_copy(self):
439 6a6175c0 Stavros Sachtouris
        self._test_foo('copy')
440 6a6175c0 Stavros Sachtouris
441 6a6175c0 Stavros Sachtouris
    def test_move(self):
442 6a6175c0 Stavros Sachtouris
        self._test_foo('move')
443 6a6175c0 Stavros Sachtouris
444 5a71b3a1 Stavros Sachtouris
445 85898ca4 Stavros Sachtouris
#  TestCase auxiliary methods
446 85898ca4 Stavros Sachtouris
447 657dc0c8 Stavros Sachtouris
def runTestCase(cls, test_name, args=[], failure_collector=[]):
448 657dc0c8 Stavros Sachtouris
    """
449 657dc0c8 Stavros Sachtouris
    :param cls: (TestCase) a set of Tests
450 657dc0c8 Stavros Sachtouris

451 657dc0c8 Stavros Sachtouris
    :param test_name: (str)
452 657dc0c8 Stavros Sachtouris

453 657dc0c8 Stavros Sachtouris
    :param args: (list) these are prefixed with test_ and used as params when
454 657dc0c8 Stavros Sachtouris
        instantiating cls
455 657dc0c8 Stavros Sachtouris

456 657dc0c8 Stavros Sachtouris
    :param failure_collector: (list) collects info of test failures
457 657dc0c8 Stavros Sachtouris

458 657dc0c8 Stavros Sachtouris
    :returns: (int) total # of run tests
459 657dc0c8 Stavros Sachtouris
    """
460 85898ca4 Stavros Sachtouris
    suite = TestSuite()
461 85898ca4 Stavros Sachtouris
    if args:
462 85898ca4 Stavros Sachtouris
        suite.addTest(cls('_'.join(['test'] + args)))
463 85898ca4 Stavros Sachtouris
    else:
464 85898ca4 Stavros Sachtouris
        suite.addTest(makeSuite(cls))
465 85898ca4 Stavros Sachtouris
    print('* Test * %s *' % test_name)
466 657dc0c8 Stavros Sachtouris
    r = TextTestRunner(verbosity=2).run(suite)
467 657dc0c8 Stavros Sachtouris
    failure_collector += r.failures
468 657dc0c8 Stavros Sachtouris
    return r.testsRun
469 85898ca4 Stavros Sachtouris
470 85898ca4 Stavros Sachtouris
471 85898ca4 Stavros Sachtouris
def _add_value(foo, value):
472 85898ca4 Stavros Sachtouris
    def wrap(self):
473 85898ca4 Stavros Sachtouris
        return foo(self, value)
474 85898ca4 Stavros Sachtouris
    return wrap
475 85898ca4 Stavros Sachtouris
476 85898ca4 Stavros Sachtouris
477 85898ca4 Stavros Sachtouris
def get_test_classes(module=__import__(__name__), name=''):
478 85898ca4 Stavros Sachtouris
    module_stack = [module]
479 85898ca4 Stavros Sachtouris
    while module_stack:
480 85898ca4 Stavros Sachtouris
        module = module_stack[-1]
481 85898ca4 Stavros Sachtouris
        module_stack = module_stack[:-1]
482 85898ca4 Stavros Sachtouris
        for objname, obj in getmembers(module):
483 85898ca4 Stavros Sachtouris
            if (objname == name or not name):
484 85898ca4 Stavros Sachtouris
                if isclass(obj) and objname != 'TestCase' and (
485 85898ca4 Stavros Sachtouris
                        issubclass(obj, TestCase)):
486 85898ca4 Stavros Sachtouris
                    yield (obj, objname)
487 85898ca4 Stavros Sachtouris
488 85898ca4 Stavros Sachtouris
489 c1004a00 Stavros Sachtouris
def main(argv):
490 d86c3c7d Stavros Sachtouris
    found = False
491 657dc0c8 Stavros Sachtouris
    failure_collector = list()
492 657dc0c8 Stavros Sachtouris
    num_of_tests = 0
493 c1004a00 Stavros Sachtouris
    for cls, name in get_test_classes(name=argv[1] if len(argv) > 1 else ''):
494 d86c3c7d Stavros Sachtouris
        found = True
495 657dc0c8 Stavros Sachtouris
        num_of_tests += runTestCase(cls, name, argv[2:], failure_collector)
496 d86c3c7d Stavros Sachtouris
    if not found:
497 d86c3c7d Stavros Sachtouris
        print('Test "%s" not found' % ' '.join(argv[1:]))
498 657dc0c8 Stavros Sachtouris
    else:
499 657dc0c8 Stavros Sachtouris
        for i, failure in enumerate(failure_collector):
500 657dc0c8 Stavros Sachtouris
            print('Failure %s: ' % (i + 1))
501 657dc0c8 Stavros Sachtouris
            for field in failure:
502 657dc0c8 Stavros Sachtouris
                print('\t%s' % field)
503 657dc0c8 Stavros Sachtouris
        print('\nTotal tests run: %s' % num_of_tests)
504 657dc0c8 Stavros Sachtouris
        print('Total failures: %s' % len(failure_collector))
505 c1004a00 Stavros Sachtouris
506 c1004a00 Stavros Sachtouris
507 c1004a00 Stavros Sachtouris
if __name__ == '__main__':
508 c1004a00 Stavros Sachtouris
    from sys import argv
509 c1004a00 Stavros Sachtouris
    main(argv)