Revision 283a43e9 astakosclient/astakosclient/tests.py

b/astakosclient/astakosclient/tests.py
44 44
import sys
45 45
import socket
46 46
import simplejson
47
from mock import patch
48
from contextlib import contextmanager
47 49

  
48 50
import astakosclient
49 51
from astakosclient import AstakosClient
52
from astakosclient.utils import join_urls
50 53
from astakosclient.errors import \
51 54
    AstakosClientException, Unauthorized, BadRequest, NotFound, \
52 55
    NoUserName, NoUUID, BadValue, QuotaLimit
......
62 65

  
63 66
# --------------------------------------------------------------------
64 67
# Helper functions
68
auth_url = "https://example.org/identity/v2.0"
69
account_prefix = "/account_prefix"
70
ui_prefix = "/ui_prefix"
71
api_authenticate = join_urls(account_prefix, "authenticate")
72
api_usercatalogs = join_urls(account_prefix, "user_catalogs")
73
api_resources = join_urls(account_prefix, "resources")
74
api_quotas = join_urls(account_prefix, "quotas")
75
api_commissions = join_urls(account_prefix, "commissions")
76

  
77
# --------------------------------------
78
# Local users
79
token_1 = "skzleaFlBl+fasFdaf24sx"
80
user_1 = \
81
    {"username": "user1@example.com",
82
     "name": "Example User One",
83
     "email": ["user1@example.com"],
84
     "uuid": "73917abc-abcd-477e-a1f1-1763abcdefab"}
85

  
86
resources = {
87
    "cyclades.ram": {
88
        "unit": "bytes",
89
        "description": "Virtual machine memory",
90
        "service": "cyclades"}}
91

  
92
endpoints = {
93
    "access": {
94
        "serviceCatalog": [{
95
            "endpoints": [{"SNF:uiURL": join_urls("https://example.org/",
96
                                                  ui_prefix),
97
                           "publicURL": join_urls("https://example.org/",
98
                                                  account_prefix),
99
                           "region": "default",
100
                           "versionId": "v1.0"}],
101
            "name": "astakos_account",
102
            "type": "account"}]
103
        }
104
    }
105

  
106
quotas = {
107
    "system": {
108
        "cyclades.ram": {
109
            "pending": 0,
110
            "limit": 1073741824,
111
            "usage": 536870912},
112
        "cyclades.vm": {
113
            "pending": 0,
114
            "limit": 2,
115
            "usage": 2}},
116
    "project:1": {
117
        "cyclades.ram": {
118
            "pending": 0,
119
            "limit": 2147483648,
120
            "usage": 2147483648},
121
        "cyclades.vm": {
122
            "pending": 1,
123
            "limit": 5,
124
            "usage": 2}}}
125

  
126
commission_request = {
127
    "force": False,
128
    "auto_accept": False,
129
    "name": "my commission",
130
    "provisions": [
131
        {
132
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
133
            "source": "system",
134
            "resource": "cyclades.vm",
135
            "quantity": 1
136
        },
137
        {
138
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
139
            "source": "system",
140
            "resource": "cyclades.ram",
141
            "quantity": 30000
142
        }]}
143

  
144
commission_successful_response = {"serial": 57}
145

  
146
commission_failure_response = {
147
    "overLimit": {
148
        "message": "a human-readable error message",
149
        "code": 413,
150
        "data": {
151
            "provision": {
152
                "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
153
                "source": "system",
154
                "resource": "cyclades.ram",
155
                "quantity": 520000000},
156
            "name": "NoCapacityError",
157
            "limit": 600000000,
158
            "usage": 180000000}}}
159

  
160
pending_commissions = [100, 200]
161

  
162
commission_description = {
163
    "serial": 57,
164
    "issue_time": "2013-04-08T10:19:15.0373+00:00",
165
    "name": "a commission",
166
    "provisions": [
167
        {
168
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
169
            "source": "system",
170
            "resource": "cyclades.vm",
171
            "quantity": 1
172
        },
173
        {
174
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
175
            "source": "system",
176
            "resource": "cyclades.ram",
177
            "quantity": 536870912
178
        }]}
179

  
180
resolve_commissions_req = {
181
    "accept": [56, 57],
182
    "reject": [56, 58, 59]}
183

  
184
resolve_commissions_rep = {
185
    "accepted": [57],
186
    "rejected": [59],
187
    "failed": [
188
        [56, {
189
            "badRequest": {
190
                "message": "cannot both accept and reject serial 56",
191
                "code": 400}}],
192
        [58, {
193
            "itemNotFound": {
194
                "message": "serial 58 does not exist",
195
                "code": 404}}]]}
196

  
65 197

  
66 198
# ----------------------------
67
# This functions will be used as mocked requests
199
# These functions will be used as mocked requests
68 200
def _request_offline(conn, method, url, **kwargs):
69 201
    """This request behaves as we were offline"""
70 202
    raise socket.gaierror
......
74 206
    """This request returns 302"""
75 207
    message = "FOUND"
76 208
    status = 302
77
    data = '<html>\r\n<head><title>302 Found</title></head>\r\n' \
78
        '<body bgcolor="white">\r\n<center><h1>302 Found</h1></center>\r\n' \
79
        '<hr><center>nginx/0.7.67</center>\r\n</body>\r\n</html>\r\n'
209
    data = "302 Found"
80 210
    return (message, data, status)
81 211

  
82 212

  
......
84 214
    """This request returns 404"""
85 215
    message = "Not Found"
86 216
    status = 404
87
    data = '<html><head><title>404 Not Found</title></head>' \
88
        '<body><h1>Not Found</h1><p>The requested URL /foo was ' \
89
        'not found on this server.</p><hr><address>Apache Server ' \
90
        'at example.com Port 80</address></body></html>'
217
    data = "404 Not Found"
91 218
    return (message, data, status)
92 219

  
93 220

  
......
117 244

  
118 245
def _request_ok(conn, method, url, **kwargs):
119 246
    """This request behaves like original Astakos does"""
120
    if re.match('/?' + astakosclient.API_AUTHENTICATE, url) is not None:
121
        print "here 1"
247
    if api_authenticate == url:
122 248
        return _req_authenticate(conn, method, url, **kwargs)
123
    elif re.match('/?' + astakosclient.API_USERCATALOGS, url) is not None:
124
        print "here 2"
249
    elif api_usercatalogs == url:
125 250
        return _req_catalogs(conn, method, url, **kwargs)
126
    elif re.match('/?' + astakosclient.API_RESOURCES, url) is not None:
127
        print "here 3"
251
    elif api_resources == url:
128 252
        return _req_resources(conn, method, url, **kwargs)
129
    elif re.match('/?' + astakosclient.API_QUOTAS, url) is not None:
253
    elif api_quotas == url:
130 254
        return _req_quotas(conn, method, url, **kwargs)
131
    elif re.match('/?' + astakosclient.API_COMMISSIONS, url) is not None:
255
    elif url.startswith(api_commissions):
132 256
        return _req_commission(conn, method, url, **kwargs)
133
    elif re.match('/?' + astakosclient.API_TOKENS, url) is not None:
134
        return _req_endpoints(conn, method, url, **kwargs)
135 257
    else:
136
        print "here 4"
137 258
        return _request_status_404(conn, method, url, **kwargs)
138 259

  
139 260

  
140 261
def _req_authenticate(conn, method, url, **kwargs):
141 262
    """Check if user exists and return his profile"""
142
    global user_1, user_2, token_1, token_2
263
    global user_1, token_1
143 264

  
144 265
    # Check input
145 266
    if conn.__class__.__name__ != "HTTPSConnection":
......
149 270
    token = kwargs['headers'].get('X-Auth-Token')
150 271
    if token == token_1:
151 272
        user = dict(user_1)
152
    elif token == token_2:
153
        user = dict(user_2)
273
        return ("", simplejson.dumps(user), 200)
154 274
    else:
155 275
        # No user found
156 276
        return _request_status_401(conn, method, url, **kwargs)
157 277

  
158
    # Return
159
    if "usage=1" not in url:
160
        # Strip `usage' key from `user'
161
        del user['usage']
162
    return ("", simplejson.dumps(user), 200)
163

  
164 278

  
165 279
def _req_catalogs(conn, method, url, **kwargs):
166 280
    """Return user catalogs"""
......
172 286
    if method != "POST":
173 287
        return _request_status_400(conn, method, url, **kwargs)
174 288
    token = kwargs['headers'].get('X-Auth-Token')
175
    if token != token_1 and token != token_2:
289
    if token != token_1:
176 290
        return _request_status_401(conn, method, url, **kwargs)
177 291

  
178 292
    # Return
......
183 297
        catalogs = {}
184 298
        if user_1['uuid'] in uuids:
185 299
            catalogs[user_1['uuid']] = user_1['username']
186
        if user_2['uuid'] in uuids:
187
            catalogs[user_2['uuid']] = user_2['username']
188 300
        return_catalog = {"displayname_catalog": {}, "uuid_catalog": catalogs}
189 301
    elif 'displaynames' in body:
190 302
        # Return displayname_catalog
......
192 304
        catalogs = {}
193 305
        if user_1['username'] in names:
194 306
            catalogs[user_1['username']] = user_1['uuid']
195
        if user_2['username'] in names:
196
            catalogs[user_2['username']] = user_2['uuid']
197 307
        return_catalog = {"displayname_catalog": catalogs, "uuid_catalog": {}}
198 308
    else:
199 309
        return_catalog = {"displayname_catalog": {}, "uuid_catalog": {}}
......
247 357
        if 'body' not in kwargs:
248 358
            return _request_status_400(conn, method, url, **kwargs)
249 359
        body = simplejson.loads(unicode(kwargs['body']))
250
        if re.match('/?'+astakosclient.API_COMMISSIONS+'$', url) is not None:
360
        if re.match('/?'+api_commissions+'$', url) is not None:
251 361
            # Issue Commission
252 362
            # Check if we have enough resources to give
253 363
            if body['provisions'][1]['quantity'] > 420000000:
......
257 367
                    ("", simplejson.dumps(commission_successful_response), 200)
258 368
        else:
259 369
            # Issue commission action
260
            serial = url.split('/')[4]
370
            serial = url.split('/')[3]
261 371
            if serial == "action":
262 372
                # Resolve multiple actions
263 373
                if body == resolve_commissions_req:
......
275 385
                return ("", "", 200)
276 386

  
277 387
    elif method == "GET":
278
        if re.match('/?'+astakosclient.API_COMMISSIONS+'$', url) is not None:
388
        if re.match('/?'+api_commissions+'$', url) is not None:
279 389
            # Return pending commission
280 390
            return ("", simplejson.dumps(pending_commissions), 200)
281 391
        else:
282 392
            # Return commissions's description
283
            serial = re.sub('/?' + astakosclient.API_COMMISSIONS, '', url)[1:]
393
            serial = re.sub('/?' + api_commissions, '', url)[1:]
284 394
            if serial == str(57):
285 395
                return ("", simplejson.dumps(commission_description), 200)
286 396
            else:
......
289 399
        return _request_status_400(conn, method, url, **kwargs)
290 400

  
291 401

  
292
def _req_endpoints(conn, method, url, **kwargs):
293
    """Request endpoints"""
294
    global token_1, endpoints
295

  
296
    # Check input
297
    if conn.__class__.__name__ != "HTTPSConnection":
298
        return _request_status_302(conn, method, url, **kwargs)
299
    if method != "POST":
300
        return _request_status_400(conn, method, url, **kwargs)
301

  
302
    token_head = kwargs['headers'].get('X-Auth-Token')
303
    if method != "POST":
304
        return _request_status_400(conn, method, url, **kwargs)
305
    body = simplejson.loads(kwargs['body'])
306
    token_body = body['auth']['token']['id']
307
    if token_head != token_body:
308
        return _request_status_403(conn, method, url, **kwargs)
309
    if token_body != token_1:
310
        return _request_status_401(conn, method, url, **kwargs)
311
    # Return
312
    return ("", simplejson.dumps(user_info_endpoints), 200)
313

  
314

  
315 402
# ----------------------------
316 403
# Mock the actual _doRequest
317 404
def _mock_request(new_requests):
......
335 422
    astakosclient._do_request = _mock
336 423

  
337 424

  
338
# ----------------------------
339
# Local users
340
token_1 = "skzleaFlBl+fasFdaf24sx"
341
user_1 = \
342
    {"username": "user1@example.com",
343
     "auth_token_created": 1359386939000,
344
     "name": "Example User One",
345
     "email": ["user1@example.com"],
346
     "auth_token_expires": 1361978939000,
347
     "id": 108,
348
     "uuid": "73917abc-abcd-477e-a1f1-1763abcdefab",
349
     "usage": [
350
         {"currValue": 42949672960,
351
          "display_name": "System Disk",
352
          "name": "cyclades.disk"},
353
         {"currValue": 4,
354
          "display_name": "CPU",
355
          "name": "cyclades.cpu"},
356
         {"currValue": 4294967296,
357
          "display_name": "RAM",
358
          "name": "cyclades.ram"},
359
         {"currValue": 3,
360
          "display_name": "VM",
361
          "name": "cyclades.vm"},
362
         {"currValue": 0,
363
          "display_name": "private network",
364
          "name": "cyclades.network.private"},
365
         {"currValue": 152,
366
          "display_name": "Storage Space",
367
          "name": "pithos+.diskspace"}]}
368

  
369
token_2 = "fasdfDSFdf98923DF+sdfk"
370
user_2 = \
371
    {"username": "user2@example.com",
372
     "auth_token_created": 1358386938997,
373
     "name": "Example User Two",
374
     "email": ["user1@example.com"],
375
     "auth_token_expires": 1461998939000,
376
     "id": 109,
377
     "uuid": "73917bca-1234-5678-a1f1-1763abcdefab",
378
     "usage": [
379
         {"currValue": 68719476736,
380
          "display_name": "System Disk",
381
          "name": "cyclades.disk"},
382
         {"currValue": 1,
383
          "display_name": "CPU",
384
          "name": "cyclades.cpu"},
385
         {"currValue": 1073741824,
386
          "display_name": "RAM",
387
          "name": "cyclades.ram"},
388
         {"currValue": 2,
389
          "display_name": "VM",
390
          "name": "cyclades.vm"},
391
         {"currValue": 1,
392
          "display_name": "private network",
393
          "name": "cyclades.network.private"},
394
         {"currValue": 2341634510,
395
          "display_name": "Storage Space",
396
          "name": "pithos+.diskspace"}]}
397

  
398
resources = {
399
    "cyclades.vm": {
400
        "unit": None,
401
        "description": "Number of virtual machines",
402
        "service": "cyclades"},
403
    "cyclades.ram": {
404
        "unit": "bytes",
405
        "description": "Virtual machine memory",
406
        "service": "cyclades"}}
407

  
408
user_info_endpoints = \
409
    {'serviceCatalog': [
410
        {'endpoints': [{
411
            'SNF:uiURL': 'https://node1.example.com/ui/',
412
            'adminURL': 'https://node1.example.com/v1',
413
            'internalUrl': 'https://node1.example.com/v1',
414
            'publicURL': 'https://node1.example.com/v1',
415
            'region': 'cyclades'}],
416
         'name': 'cyclades',
417
         'type': 'compute'},
418
        {'endpoints': [{
419
            'SNF:uiURL': 'https://node2.example.com/ui/',
420
            'adminURL': 'https://node2.example.com/v1',
421
            'internalUrl': 'https://node2.example.com/v1',
422
            'publicURL': 'https://node2.example.com/v1',
423
            'region': 'pithos'}],
424
         'name': 'pithos',
425
         'type': 'storage'}],
426
     'token': {
427
         'expires': '2013-06-19T15:23:59.975572+00:00',
428
         'id': token_1,
429
         'tenant': {
430
             'id': user_1,
431
             'name': 'Firstname Lastname'}},
432
     'user': {
433
         'id': user_1,
434
         'name': 'Firstname Lastname',
435
         'roles': [{'id': 1, 'name': 'default'}],
436
         'roles_links': []}}
437

  
438
quotas = {
439
    "system": {
440
        "cyclades.ram": {
441
            "pending": 0,
442
            "limit": 1073741824,
443
            "usage": 536870912},
444
        "cyclades.vm": {
445
            "pending": 0,
446
            "limit": 2,
447
            "usage": 2}},
448
    "project:1": {
449
        "cyclades.ram": {
450
            "pending": 0,
451
            "limit": 2147483648,
452
            "usage": 2147483648},
453
        "cyclades.vm": {
454
            "pending": 1,
455
            "limit": 5,
456
            "usage": 2}}}
457

  
458
commission_request = {
459
    "force": False,
460
    "auto_accept": False,
461
    "name": "my commission",
462
    "provisions": [
463
        {
464
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
465
            "source": "system",
466
            "resource": "cyclades.vm",
467
            "quantity": 1
468
        },
469
        {
470
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
471
            "source": "system",
472
            "resource": "cyclades.ram",
473
            "quantity": 30000
474
        }]}
475

  
476
commission_successful_response = {"serial": 57}
477

  
478
commission_failure_response = {
479
    "overLimit": {
480
        "message": "a human-readable error message",
481
        "code": 413,
482
        "data": {
483
            "provision": {
484
                "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
485
                "source": "system",
486
                "resource": "cyclades.ram",
487
                "quantity": 520000000},
488
            "name": "NoCapacityError",
489
            "limit": 600000000,
490
            "usage": 180000000}}}
491

  
492
pending_commissions = [100, 200]
493

  
494
commission_description = {
495
    "serial": 57,
496
    "issue_time": "2013-04-08T10:19:15.0373+00:00",
497
    "name": "a commission",
498
    "provisions": [
499
        {
500
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
501
            "source": "system",
502
            "resource": "cyclades.vm",
503
            "quantity": 1
504
        },
505
        {
506
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
507
            "source": "system",
508
            "resource": "cyclades.ram",
509
            "quantity": 536870912
510
        }]}
511

  
512
resolve_commissions_req = {
513
    "accept": [56, 57],
514
    "reject": [56, 58, 59]}
515

  
516
resolve_commissions_rep = {
517
    "accepted": [57],
518
    "rejected": [59],
519
    "failed": [
520
        [56, {
521
            "badRequest": {
522
                "message": "cannot both accept and reject serial 56",
523
                "code": 400}}],
524
        [58, {
525
            "itemNotFound": {
526
                "message": "serial 58 does not exist",
527
                "code": 404}}]]}
425
# --------------------------------------
426
# Mock the get_endpoints method
427
@contextmanager
428
def patch_astakosclient(new_requests):
429
    _mock_request(new_requests)
430
    with patch('astakosclient.AstakosClient.get_endpoints') as patcher:
431
        patcher.return_value = endpoints
432
        yield
528 433

  
529 434

  
530 435
# --------------------------------------------------------------------
......
536 441
    # ----------------------------------
537 442
    # Test the response we get if we don't have internet access
538 443
    def _offline(self, pool):
539
        global token_1
444
        global token_1, auth_url
540 445
        _mock_request([_request_offline])
541 446
        try:
542
            client = AstakosClient("https://example.com", use_pool=pool)
543
            client._call_astakos(token_1, astakosclient.API_AUTHENTICATE)
447
            client = AstakosClient(token_1, auth_url, use_pool=pool)
448
            client._call_astakos("offline")
544 449
        except AstakosClientException:
545 450
            pass
546 451
        else:
......
557 462
    # ----------------------------------
558 463
    # Test the response we get if we send invalid token
559 464
    def _invalid_token(self, pool):
465
        global auth_url
560 466
        token = "skaksaFlBl+fasFdaf24sx"
561
        _mock_request([_request_ok])
562 467
        try:
563
            client = AstakosClient("https://example.com", use_pool=pool)
564
            client._call_astakos(token, astakosclient.API_AUTHENTICATE)
468
            with patch_astakosclient([_request_ok]):
469
                client = AstakosClient(token, auth_url, use_pool=pool)
470
                client.get_user_info()
565 471
        except Unauthorized:
566 472
            pass
567 473
        except Exception:
......
580 486
    # ----------------------------------
581 487
    # Test the response we get if we send invalid url
582 488
    def _invalid_url(self, pool):
583
        global token_1
584
        _mock_request([_request_ok])
489
        global token_1, auth_url
585 490
        try:
586
            client = AstakosClient("https://example.com", use_pool=pool)
587
            client._call_astakos(token_1, "/astakos/api/misspelled")
491
            with patch_astakosclient([_request_ok]):
492
                client = AstakosClient(token_1, auth_url, use_pool=pool)
493
                client._call_astakos("/astakos/api/misspelled")
588 494
        except NotFound:
589 495
            pass
590
        except Exception:
591
            self.fail("Should have returned 404 (Not Found)")
496
        except Exception, e:
497
            self.fail("Got \"%s\" instead of 404" % e)
592 498
        else:
593 499
            self.fail("Should have returned 404 (Not Found)")
594 500

  
......
603 509
    # ----------------------------------
604 510
    # Test the response we get if we use an unsupported scheme
605 511
    def _unsupported_scheme(self, pool):
606
        global token_1
607
        _mock_request([_request_ok])
512
        global token_1, auth_url
608 513
        try:
609
            client = AstakosClient("ftp://example.com", use_pool=pool)
610
            client._call_astakos(token_1, astakosclient.API_AUTHENTICATE)
514
            with patch_astakosclient([_request_ok]):
515
                client = AstakosClient(token_1, "ftp://example.com",
516
                                       use_pool=pool)
517
                client.get_user_info()
611 518
        except BadValue:
612 519
            pass
613 520
        except Exception:
......
627 534
    # Test the response we get if we use http instead of https
628 535
    def _http_scheme(self, pool):
629 536
        global token_1
630
        _mock_request([_request_ok])
537
        http_auth_url = "http://example.org/identity/v2.0"
631 538
        try:
632
            client = AstakosClient("http://example.com", use_pool=pool)
633
            client._call_astakos(token_1, astakosclient.API_AUTHENTICATE)
539
            with patch_astakosclient([_request_ok]):
540
                client = AstakosClient(token_1, http_auth_url, use_pool=pool)
541
                client.get_user_info()
634 542
        except AstakosClientException as err:
635 543
            if err.status != 302:
636 544
                self.fail("Should have returned 302 (Found)")
......
648 556
    # ----------------------------------
649 557
    # Test the response we get if we use authenticate with POST
650 558
    def _post_authenticate(self, pool):
651
        global token_1
652
        _mock_request([_request_ok])
559
        global token_1, auth_url
653 560
        try:
654
            client = AstakosClient("https://example.com", use_pool=pool)
655
            client._call_astakos(
656
                token_1, astakosclient.API_AUTHENTICATE, method="POST")
561
            with patch_astakosclient([_request_ok]):
562
                client = AstakosClient(token_1, auth_url, use_pool=pool)
563
                client._call_astakos(api_authenticate, method="POST")
657 564
        except BadRequest:
658 565
            pass
659 566
        except Exception:
......
672 579
    # ----------------------------------
673 580
    # Test the response if we request user_catalogs with GET
674 581
    def _get_user_catalogs(self, pool):
675
        global token_1
676
        _mock_request([_request_ok])
582
        global token_1, auth_url, api_usercatalogs
677 583
        try:
678
            client = AstakosClient("https://example.com", use_pool=pool)
679
            client._call_astakos(token_1, astakosclient.API_USERCATALOGS)
584
            with patch_astakosclient([_request_ok]):
585
                client = AstakosClient(token_1, auth_url, use_pool=pool)
586
                client._call_astakos(api_usercatalogs)
680 587
        except BadRequest:
681 588
            pass
682 589
        except Exception:
......
700 607
    # Test the response we get if we don't have internet access
701 608
    def test_offline(self):
702 609
        """Test offline after 3 retries"""
703
        global token_1
704
        _mock_request([_request_offline])
610
        global token_1, auth_url
705 611
        try:
706
            client = AstakosClient("https://example.com", retry=3)
707
            client.get_user_info(token_1)
612
            with patch_astakosclient([_request_offline]):
613
                client = AstakosClient(token_1, auth_url, retry=3)
614
                client.get_user_info()
708 615
        except AstakosClientException:
709 616
            pass
710 617
        else:
......
713 620
    # ----------------------------------
714 621
    # Test the response we get for invalid token
715 622
    def _invalid_token(self, pool):
623
        global auth_url
716 624
        token = "skaksaFlBl+fasFdaf24sx"
717
        _mock_request([_request_ok])
718 625
        try:
719
            client = AstakosClient("https://example.com", use_pool=pool)
720
            client.get_user_info(token)
626
            with patch_astakosclient([_request_ok]):
627
                client = AstakosClient(token, auth_url, use_pool=pool)
628
                client.get_user_info()
721 629
        except Unauthorized:
722 630
            pass
723 631
        except Exception:
......
734 642
        self._invalid_token(True)
735 643

  
736 644
    #- ---------------------------------
737
    # Test response for user 1
738
    def _auth_user(self, token, user_info, usage, pool):
739
        _mock_request([_request_ok])
645
    # Test response for user
646
    def _auth_user(self, token, user_info, pool):
647
        global auth_url
740 648
        try:
741
            client = AstakosClient("https://example.com", use_pool=pool)
742
            auth_info = client.get_user_info(token, usage=usage)
649
            with patch_astakosclient([_request_ok]):
650
                client = AstakosClient(token, auth_url, use_pool=pool)
651
                auth_info = client.get_user_info()
743 652
        except:
744 653
            self.fail("Shouldn't raise an Exception")
745 654
        self.assertEqual(user_info, auth_info)
746 655

  
747
    def test_auth_user_one(self):
748
        """Test _auth_user for User 1 without pool, without usage"""
656
    def test_auth_user(self):
657
        """Test _auth_user without pool"""
749 658
        global token_1, user_1
750 659
        user_info = dict(user_1)
751
        del user_info['usage']
752
        self._auth_user(token_1, user_info, False, False)
753

  
754
    def test_auth_user_one_usage(self):
755
        """Test _auth_user for User 1 without pool, with usage"""
756
        global token_1, user_1
757
        self._auth_user(token_1, user_1, True, False)
660
        self._auth_user(token_1, user_info, False)
758 661

  
759
    def test_auth_user_one_usage_pool(self):
662
    def test_auth_user_pool(self):
760 663
        """Test _auth_user for User 1 using pool, with usage"""
761 664
        global token_1, user_1
762
        self._auth_user(token_1, user_1, True, True)
763

  
764
    def test_auth_user_two(self):
765
        """Test _auth_user for User 2 without pool, without usage"""
766
        global token_2, user_2
767
        user_info = dict(user_2)
768
        del user_info['usage']
769
        self._auth_user(token_2, user_info, False, False)
770

  
771
    def test_auth_user_two_usage(self):
772
        """Test _auth_user for User 2 without pool, with usage"""
773
        global token_2, user_2
774
        self._auth_user(token_2, user_2, True, False)
775

  
776
    def test_auth_user_two_usage_pool(self):
777
        """Test _auth_user for User 2 using pool, with usage"""
778
        global token_2, user_2
779
        self._auth_user(token_2, user_2, True, True)
665
        self._auth_user(token_1, user_1, True)
780 666

  
781 667
    # ----------------------------------
782 668
    # Test retry functionality
783 669
    def test_offline_retry(self):
784 670
        """Test retry functionality for getUserInfo"""
785
        global token_1, user_1
671
        global token_1, user_1, auth_url
786 672
        _mock_request([_request_offline, _request_offline, _request_ok])
787 673
        try:
788
            client = AstakosClient("https://example.com", retry=2)
789
            auth_info = client.get_user_info(token_1, usage=True)
790
        except:
791
            self.fail("Shouldn't raise an Exception")
674
            with patch_astakosclient([_request_offline, _request_offline,
675
                                      _request_ok]):
676
                client = AstakosClient(token_1, auth_url, retry=2)
677
                auth_info = client.get_user_info()
678
        except Exception, e:
679
            self.fail("Shouldn't raise an Exception \"%s\"" % e)
792 680
        self.assertEqual(user_1, auth_info)
793 681

  
794 682

  
......
799 687
    # Test the response we get for invalid token
800 688
    def test_invalid_token(self):
801 689
        """Test the response we get for invalid token (without pool)"""
802
        global user_1
690
        global user_1, auth_url
803 691
        token = "skaksaFlBl+fasFdaf24sx"
804
        _mock_request([_request_ok])
805 692
        try:
806
            client = AstakosClient("https://example.com")
807
            client.get_usernames(token, [user_1['uuid']])
693
            with patch_astakosclient([_request_ok]):
694
                client = AstakosClient(token, auth_url)
695
                client.get_usernames([user_1['uuid']])
808 696
        except Unauthorized:
809 697
            pass
810 698
        except Exception:
......
813 701
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
814 702

  
815 703
    # ----------------------------------
816
    # Get Info for both users
817
    def test_usernames(self):
818
        """Test get_usernames with both users"""
819
        global token_1, user_1, user_2
820
        _mock_request([_request_ok])
821
        try:
822
            client = AstakosClient("https://example.com")
823
            catalog = client.get_usernames(
824
                token_1, [user_1['uuid'], user_2['uuid']])
825
        except:
826
            self.fail("Shouldn't raise an Exception")
827
        self.assertEqual(catalog[user_1['uuid']], user_1['username'])
828
        self.assertEqual(catalog[user_2['uuid']], user_2['username'])
829

  
830
    # ----------------------------------
831 704
    # Get info for user 1
832 705
    def test_username_user_one(self):
833 706
        """Test get_username for User One"""
834
        global token_2, user_1
835
        _mock_request([_request_offline, _request_ok])
707
        global token_1, user_1, auth_url
836 708
        try:
837
            client = AstakosClient(
838
                "https://example.com", use_pool=True, retry=2)
839
            info = client.get_username(token_2, user_1['uuid'])
709
            with patch_astakosclient([_request_offline, _request_ok]):
710
                client = AstakosClient(token_1, auth_url,
711
                                       use_pool=True, retry=2)
712
                info = client.get_username(user_1['uuid'])
840 713
        except:
841 714
            self.fail("Shouldn't raise an Exception")
842 715
        self.assertEqual(info, user_1['username'])
......
844 717
    # ----------------------------------
845 718
    # Get info with wrong uuid
846 719
    def test_no_username(self):
847
        global token_1
848
        _mock_request([_request_ok])
720
        global token_1, auth_url
849 721
        try:
850
            client = AstakosClient("https://example.com")
851
            client.get_username(token_1, "1234")
722
            with patch_astakosclient([_request_ok]):
723
                client = AstakosClient(token_1, auth_url)
724
                client.get_username("1234")
852 725
        except NoUserName:
853 726
            pass
854 727
        except:
......
864 737
    # Test the response we get for invalid token
865 738
    def test_invalid_token(self):
866 739
        """Test the response we get for invalid token (using pool)"""
867
        global user_1
740
        global user_1, auth_url
868 741
        token = "skaksaFlBl+fasFdaf24sx"
869
        _mock_request([_request_ok])
870 742
        try:
871
            client = AstakosClient("https://example.com")
872
            client.get_uuids(token, [user_1['username']])
743
            with patch_astakosclient([_request_ok]):
744
                client = AstakosClient(token, auth_url)
745
                client.get_uuids([user_1['username']])
873 746
        except Unauthorized:
874 747
            pass
875 748
        except Exception:
......
878 751
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
879 752

  
880 753
    # ----------------------------------
881
    # Get info for both users
882
    def test_uuids(self):
883
        """Test get_uuids with both users"""
884
        global token_1, user_1, user_2
885
        _mock_request([_request_ok])
886
        try:
887
            client = AstakosClient("https://example.com")
888
            catalog = client.get_uuids(
889
                token_1, [user_1['username'], user_2['username']])
890
        except:
891
            self.fail("Shouldn't raise an Exception")
892
        self.assertEqual(catalog[user_1['username']], user_1['uuid'])
893
        self.assertEqual(catalog[user_2['username']], user_2['uuid'])
894

  
895
    # ----------------------------------
896
    # Get uuid for user 2
754
    # Get uuid for user 1
897 755
    def test_get_uuid_user_two(self):
898 756
        """Test get_uuid for User Two"""
899
        global token_1, user_2
900
        _mock_request([_request_offline, _request_ok])
757
        global token_1, user_1, auth_url
901 758
        try:
902
            client = AstakosClient("https://example.com", retry=1)
903
            info = client.get_uuid(token_2, user_1['username'])
759
            with patch_astakosclient([_request_ok]):
760
                client = AstakosClient(token_1, auth_url, retry=1)
761
                catalog = client.get_uuids([user_1['username']])
904 762
        except:
905 763
            self.fail("Shouldn't raise an Exception")
906
        self.assertEqual(info, user_1['uuid'])
764
        self.assertEqual(catalog[user_1['username']], user_1['uuid'])
907 765

  
908 766
    # ----------------------------------
909 767
    # Get uuid with wrong username
910 768
    def test_no_uuid(self):
911
        global token_1
912
        _mock_request([_request_ok])
769
        global token_1, auth_url
913 770
        try:
914
            client = AstakosClient("https://example.com")
915
            client.get_uuid(token_1, "1234")
771
            with patch_astakosclient([_request_ok]):
772
                client = AstakosClient(token_1, auth_url)
773
                client.get_uuid("1234")
916 774
        except NoUUID:
917 775
            pass
918 776
        except:
......
927 785
    # ----------------------------------
928 786
    def test_get_resources(self):
929 787
        """Test function call of get_resources"""
930
        global resources
931
        _mock_request([_request_offline, _request_ok])
788
        global resources, auth_url, token_1
932 789
        try:
933
            client = AstakosClient("https://example.com", retry=1)
934
            result = client.get_resources()
790
            with patch_astakosclient([_request_offline, _request_ok]):
791
                client = AstakosClient(token_1, auth_url, retry=1)
792
                result = client.get_resources()
935 793
        except Exception as err:
936 794
            self.fail("Shouldn't raise Exception %s" % err)
937 795
        self.assertEqual(resources, result)
......
943 801
    # ----------------------------------
944 802
    def test_get_quotas(self):
945 803
        """Test function call of get_quotas"""
946
        global quotas, token_1
947
        _mock_request([_request_ok])
804
        global quotas, token_1, auth_url
948 805
        try:
949
            client = AstakosClient("https://example.com")
950
            result = client.get_quotas(token_1)
806
            with patch_astakosclient([_request_ok]):
807
                client = AstakosClient(token_1, auth_url)
808
                result = client.get_quotas()
951 809
        except Exception as err:
952 810
            self.fail("Shouldn't raise Exception %s" % err)
953 811
        self.assertEqual(quotas, result)
......
955 813
    # -----------------------------------
956 814
    def test_get_quotas_unauthorized(self):
957 815
        """Test function call of get_quotas with wrong token"""
958
        global token_2
959
        _mock_request([_request_ok])
816
        global auth_url
817
        token = "buahfhsda"
960 818
        try:
961
            client = AstakosClient("https://example.com")
962
            client.get_quotas(token_2)
963
        except Unauthorized:
964
            pass
965
        except Exception as err:
966
            self.fail("Shouldn't raise Exception %s" % err)
967
        else:
968
            self.fail("Should have raised Unauthorized Exception")
969

  
970
    # ----------------------------------
971
    def test_get_quotas_without_token(self):
972
        """Test function call of get_quotas without token"""
973
        _mock_request([_request_ok])
974
        try:
975
            client = AstakosClient("https://example.com")
976
            client.get_quotas(None)
819
            with patch_astakosclient([_request_ok]):
820
                client = AstakosClient(token, auth_url)
821
                client.get_quotas()
977 822
        except Unauthorized:
978 823
            pass
979 824
        except Exception as err:
......
989 834
    def test_issue_commission(self):
990 835
        """Test function call of issue_commission"""
991 836
        global token_1, commission_request, commission_successful_reqsponse
992
        _mock_request([_request_ok])
837
        global auth_url
993 838
        try:
994
            client = AstakosClient("https://example.com")
995
            response = client.issue_commission(token_1, commission_request)
839
            with patch_astakosclient([_request_ok]):
840
                client = AstakosClient(token_1, auth_url)
841
                response = client.issue_commission(commission_request)
996 842
        except Exception as err:
997 843
            self.fail("Shouldn't raise Exception %s" % err)
998 844
        self.assertEqual(response, commission_successful_response['serial'])
......
1001 847
    def test_issue_commission_quota_limit(self):
1002 848
        """Test function call of issue_commission with limit exceeded"""
1003 849
        global token_1, commission_request, commission_failure_response
1004
        _mock_request([_request_ok])
850
        global auth_url
1005 851
        new_request = dict(commission_request)
1006 852
        new_request['provisions'][1]['quantity'] = 520000000
1007 853
        try:
1008
            client = AstakosClient("https://example.com")
1009
            client.issue_commission(token_1, new_request)
854
            with patch_astakosclient([_request_ok]):
855
                client = AstakosClient(token_1, auth_url)
856
                client.issue_commission(new_request)
1010 857
        except QuotaLimit:
1011 858
            pass
1012 859
        except Exception as err:
......
1017 864
    # ----------------------------------
1018 865
    def test_issue_one_commission(self):
1019 866
        """Test function call of issue_one_commission"""
1020
        global token_1, commission_successful_response
1021
        _mock_request([_request_ok])
867
        global token_1, commission_successful_response, auth_url
1022 868
        try:
1023
            client = AstakosClient("https://example.com")
1024
            response = client.issue_one_commission(
1025
                token_1, "c02f315b-7d84-45bc-a383-552a3f97d2ad",
1026
                "system", {"cyclades.vm": 1, "cyclades.ram": 30000})
869
            with patch_astakosclient([_request_ok]):
870
                client = AstakosClient(token_1, auth_url)
871
                response = client.issue_one_commission(
872
                    "c02f315b-7d84-45bc-a383-552a3f97d2ad",
873
                    "system", {"cyclades.vm": 1, "cyclades.ram": 30000})
1027 874
        except Exception as err:
1028 875
            self.fail("Shouldn't have raised Exception %s" % err)
1029 876
        self.assertEqual(response, commission_successful_response['serial'])
......
1031 878
    # ----------------------------------
1032 879
    def test_get_pending_commissions(self):
1033 880
        """Test function call of get_pending_commissions"""
1034
        global token_1, pending_commissions
1035
        _mock_request([_request_ok])
881
        global token_1, pending_commissions, auth_url
1036 882
        try:
1037
            client = AstakosClient("https://example.com")
1038
            response = client.get_pending_commissions(token_1)
883
            with patch_astakosclient([_request_ok]):
884
                client = AstakosClient(token_1, auth_url)
885
                response = client.get_pending_commissions()
1039 886
        except Exception as err:
1040 887
            self.fail("Shouldn't raise Exception %s" % err)
1041 888
        self.assertEqual(response, pending_commissions)
......
1043 890
    # ----------------------------------
1044 891
    def test_get_commission_info(self):
1045 892
        """Test function call of get_commission_info"""
1046
        global token_1, commission_description
1047
        _mock_request([_request_ok])
893
        global token_1, commission_description, auth_url
1048 894
        try:
1049
            client = AstakosClient("https://example.com", use_pool=True,
1050
                                   pool_size=2)
1051
            response = client.get_commission_info(token_1, 57)
895
            with patch_astakosclient([_request_ok]):
896
                client = AstakosClient(token_1, auth_url,
897
                                       use_pool=True, pool_size=2)
898
                response = client.get_commission_info(57)
1052 899
        except Exception as err:
1053 900
            self.fail("Shouldn't raise Exception %s" % err)
1054 901
        self.assertEqual(response, commission_description)
......
1056 903
    # ----------------------------------
1057 904
    def test_get_commission_info_not_found(self):
1058 905
        """Test function call of get_commission_info with invalid serial"""
1059
        global token_1
906
        global token_1, auth_url
1060 907
        _mock_request([_request_ok])
1061 908
        try:
1062
            client = AstakosClient("https://example.com")
1063
            client.get_commission_info(token_1, "57lala")
909
            with patch_astakosclient([_request_ok]):
910
                client = AstakosClient(token_1, auth_url)
911
                client.get_commission_info("57lala")
1064 912
        except NotFound:
1065 913
            pass
1066 914
        except Exception as err:
......
1071 919
    # ----------------------------------
1072 920
    def test_get_commission_info_without_serial(self):
1073 921
        """Test function call of get_commission_info without serial"""
1074
        global token_1
1075
        _mock_request([_request_ok])
922
        global token_1, auth_url
1076 923
        try:
1077
            client = AstakosClient("https://example.com")
1078
            client.get_commission_info(token_1, None)
924
            with patch_astakosclient([_request_ok]):
925
                client = AstakosClient(token_1, auth_url)
926
                client.get_commission_info(None)
1079 927
        except BadValue:
1080 928
            pass
1081 929
        except Exception as err:
......
1086 934
    # ----------------------------------
1087 935
    def test_commision_action(self):
1088 936
        """Test function call of commision_action with wrong action"""
1089
        global token_1
1090
        _mock_request([_request_ok])
937
        global token_1, auth_url
1091 938
        try:
1092
            client = AstakosClient("https://example.com")
1093
            client.commission_action(token_1, 57, "lala")
939
            with patch_astakosclient([_request_ok]):
940
                client = AstakosClient(token_1, auth_url)
941
                client.commission_action(57, "lala")
1094 942
        except BadRequest:
1095 943
            pass
1096 944
        except Exception as err:
......
1101 949
    # ----------------------------------
1102 950
    def test_accept_commission(self):
1103 951
        """Test function call of accept_commission"""
1104
        global token_1
1105
        _mock_request([_request_ok])
952
        global token_1, auth_url
1106 953
        try:
1107
            client = AstakosClient("https://example.com")
1108
            client.accept_commission(token_1, 57)
954
            with patch_astakosclient([_request_ok]):
955
                client = AstakosClient(token_1, auth_url)
956
                client.accept_commission(57)
1109 957
        except Exception as err:
1110 958
            self.fail("Shouldn't raise Exception %s" % err)
1111 959

  
1112 960
    # ----------------------------------
1113 961
    def test_reject_commission(self):
1114 962
        """Test function call of reject_commission"""
1115
        global token_1
1116
        _mock_request([_request_ok])
963
        global token_1, auth_url
1117 964
        try:
1118
            client = AstakosClient("https://example.com")
1119
            client.reject_commission(token_1, 57)
965
            with patch_astakosclient([_request_ok]):
966
                client = AstakosClient(token_1, auth_url)
967
                client.reject_commission(57)
1120 968
        except Exception as err:
1121 969
            self.fail("Shouldn't raise Exception %s" % err)
1122 970

  
1123 971
    # ----------------------------------
1124 972
    def test_accept_commission_not_found(self):
1125 973
        """Test function call of accept_commission with wrong serial"""
1126
        global token_1
1127
        _mock_request([_request_ok])
974
        global token_1, auth_url
1128 975
        try:
1129
            client = AstakosClient("https://example.com")
1130
            client.reject_commission(token_1, 20)
976
            with patch_astakosclient([_request_ok]):
977
                client = AstakosClient(token_1, auth_url)
978
                client.reject_commission(20)
1131 979
        except NotFound:
1132 980
            pass
1133 981
        except Exception as err:
......
1138 986
    # ----------------------------------
1139 987
    def test_resolve_commissions(self):
1140 988
        """Test function call of resolve_commissions"""
1141
        global token_1
1142
        _mock_request([_request_ok])
989
        global token_1, auth_url
1143 990
        try:
1144
            client = AstakosClient("https://example.com")
1145
            result = client.resolve_commissions(token_1, [56, 57],
1146
                                                [56, 58, 59])
991
            with patch_astakosclient([_request_ok]):
992
                client = AstakosClient(token_1, auth_url)
993
                result = client.resolve_commissions([56, 57], [56, 58, 59])
1147 994
        except Exception as err:
1148 995
            self.fail("Shouldn't raise Exception %s" % err)
1149 996
        self.assertEqual(result, resolve_commissions_rep)
1150 997

  
1151 998

  
1152
class TestEndPoints(unittest.TestCase):
1153
    """Test cases for endpoints requests"""
1154

  
1155
    # ----------------------------------
1156
    def test_get_endpoints(self):
1157
        """Test function call of get_endpoints"""
1158
        global token_1, user_info_endpoints
1159
        _mock_request([_request_ok])
1160
        try:
1161
            client = AstakosClient("https://example.com")
1162
            response = client.get_endpoints(token_1)
1163
        except Exception as err:
1164
            self.fail("Shouldn't raise Exception %s" % err)
1165
        self.assertEqual(response, user_info_endpoints)
1166

  
1167

  
1168 999
# ----------------------------
1169 1000
# Run tests
1170 1001
if __name__ == "__main__":
1171
    unittest.main()
1002
        unittest.main()

Also available in: Unified diff