tests.py 30.9 KB
Newer Older
1 2
#!/usr/bin/env python
#
Vangelis Koukis's avatar
Vangelis Koukis committed
3
# Copyright (C) 2010-2014 GRNET S.A.
4
#
Vangelis Koukis's avatar
Vangelis Koukis committed
5 6 7 8
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
9
#
Vangelis Koukis's avatar
Vangelis Koukis committed
10 11 12 13
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
14
#
Vangelis Koukis's avatar
Vangelis Koukis committed
15 16
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
17 18 19 20 21 22 23 24

"""Unit Tests for the astakos-client module

Provides unit tests for the code implementing
the astakos client library

"""

25
import re
26
import sys
27 28 29 30 31

try:
    import simplejson as json
except ImportError:
    import json
32 33

import astakosclient
34
from astakosclient import AstakosClient
35
from astakosclient.utils import join_urls
36
from astakosclient.errors import \
37
    AstakosClientException, Unauthorized, BadRequest, NotFound, \
38
    NoUserName, NoUUID, BadValue, QuotaLimit
39 40

# Use backported unittest functionality if Python < 2.7
41 42 43 44 45 46
try:
    import unittest2 as unittest
except ImportError:
    if sys.version_info < (2, 7):
        raise Exception("The unittest2 package is required for Python < 2.7")
    import unittest
47 48 49 50


# --------------------------------------------------------------------
# Helper functions
51 52 53
auth_url = "https://example.org/identity/v2.0"
account_prefix = "/account_prefix"
ui_prefix = "/ui_prefix"
54
oauth2_prefix = "/oauth2"
55
api_tokens = "/identity/v2.0/tokens"
56 57 58 59 60 61 62
api_usercatalogs = join_urls(account_prefix, "user_catalogs")
api_resources = join_urls(account_prefix, "resources")
api_quotas = join_urls(account_prefix, "quotas")
api_commissions = join_urls(account_prefix, "commissions")

# --------------------------------------
# Local users
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
token = {
    'id': "skzleaFlBl+fasFdaf24sx",
    'tenant': {
        'id': "73917abc-abcd-477e-a1f1-1763abcdefab",
        'name': "Example User One",
        },
    }

user = {
    'id': "73917abc-abcd-477e-a1f1-1763abcdefab",
    'name': "Example User One",
    'roles': [{u'id': 1, u'name': u'default'},
              {u'id': 5, u'name': u'academic-login-users'}],
    'roles_links': []
    }
78 79 80 81 82 83 84 85 86

resources = {
    "cyclades.ram": {
        "unit": "bytes",
        "description": "Virtual machine memory",
        "service": "cyclades"}}

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

109 110 111 112
endpoints_with_info = dict(endpoints)
endpoints_with_info['access']['token'] = dict(token)
endpoints_with_info['access']['user'] = dict(user)

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203
quotas = {
    "system": {
        "cyclades.ram": {
            "pending": 0,
            "limit": 1073741824,
            "usage": 536870912},
        "cyclades.vm": {
            "pending": 0,
            "limit": 2,
            "usage": 2}},
    "project:1": {
        "cyclades.ram": {
            "pending": 0,
            "limit": 2147483648,
            "usage": 2147483648},
        "cyclades.vm": {
            "pending": 1,
            "limit": 5,
            "usage": 2}}}

commission_request = {
    "force": False,
    "auto_accept": False,
    "name": "my commission",
    "provisions": [
        {
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
            "source": "system",
            "resource": "cyclades.vm",
            "quantity": 1
        },
        {
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
            "source": "system",
            "resource": "cyclades.ram",
            "quantity": 30000
        }]}

commission_successful_response = {"serial": 57}

commission_failure_response = {
    "overLimit": {
        "message": "a human-readable error message",
        "code": 413,
        "data": {
            "provision": {
                "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
                "source": "system",
                "resource": "cyclades.ram",
                "quantity": 520000000},
            "name": "NoCapacityError",
            "limit": 600000000,
            "usage": 180000000}}}

pending_commissions = [100, 200]

commission_description = {
    "serial": 57,
    "issue_time": "2013-04-08T10:19:15.0373+00:00",
    "name": "a commission",
    "provisions": [
        {
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
            "source": "system",
            "resource": "cyclades.vm",
            "quantity": 1
        },
        {
            "holder": "c02f315b-7d84-45bc-a383-552a3f97d2ad",
            "source": "system",
            "resource": "cyclades.ram",
            "quantity": 536870912
        }]}

resolve_commissions_req = {
    "accept": [56, 57],
    "reject": [56, 58, 59]}

resolve_commissions_rep = {
    "accepted": [57],
    "rejected": [59],
    "failed": [
        [56, {
            "badRequest": {
                "message": "cannot both accept and reject serial 56",
                "code": 400}}],
        [58, {
            "itemNotFound": {
                "message": "serial 58 does not exist",
                "code": 404}}]]}

204 205

# ----------------------------
206
# These functions will be used as mocked requests
207
def _request_status_302(conn, method, url, **kwargs):
208
    """This request returns 302"""
209
    message = "FOUND"
210
    status = 302
211
    data = "302 Found"
212
    return (message, data, status)
213 214


215
def _request_status_404(conn, method, url, **kwargs):
216
    """This request returns 404"""
217
    message = "Not Found"
218
    status = 404
219
    data = "404 Not Found"
220
    return (message, data, status)
221 222


223 224 225 226 227 228 229 230
def _request_status_403(conn, method, url, **kwargs):
    """This request returns 403"""
    message = "UNAUTHORIZED"
    status = 403
    data = "Forbidden"
    return (message, data, status)


231
def _request_status_401(conn, method, url, **kwargs):
232
    """This request returns 401"""
233
    message = "UNAUTHORIZED"
234 235
    status = 401
    data = "Invalid X-Auth-Token\n"
236
    return (message, data, status)
237 238


239
def _request_status_400(conn, method, url, **kwargs):
240
    """This request returns 400"""
241
    message = "BAD REQUEST"
242 243
    status = 400
    data = "Method not allowed.\n"
244
    return (message, data, status)
245 246


247
def _mock_request(conn, method, url, **kwargs):
248
    """This request behaves like original Astakos does"""
249 250
    if api_tokens == url:
        return _req_tokens(conn, method, url, **kwargs)
251
    elif api_usercatalogs == url:
252
        return _req_catalogs(conn, method, url, **kwargs)
253
    elif api_resources == url:
254
        return _req_resources(conn, method, url, **kwargs)
255
    elif api_quotas == url:
256
        return _req_quotas(conn, method, url, **kwargs)
257
    elif url.startswith(api_commissions):
258
        return _req_commission(conn, method, url, **kwargs)
259
    else:
260
        return _request_status_404(conn, method, url, **kwargs)
261 262


263 264 265
def _req_tokens(conn, method, url, **kwargs):
    """Return endpoints"""
    global token, user, endpoints
266

267
    # Check input
268
    if conn.__class__.__name__ != "HTTPSConnection":
269
        return _request_status_302(conn, method, url, **kwargs)
270
    if method != "POST":
271
        return _request_status_400(conn, method, url, **kwargs)
272 273
    req_token = kwargs['headers'].get('X-Auth-Token')
    if req_token != token['id']:
274
        return _request_status_401(conn, method, url, **kwargs)
275

276 277
    if 'body' in kwargs:
        # Return endpoints with authenticate info
278
        return ("", json.dumps(endpoints_with_info), 200)
279 280
    else:
        # Return endpoints without authenticate info
281
        return ("", json.dumps(endpoints), 200)
282

283

284
def _req_catalogs(conn, method, url, **kwargs):
285
    """Return user catalogs"""
286
    global token, user
287

288
    # Check input
289
    if conn.__class__.__name__ != "HTTPSConnection":
290
        return _request_status_302(conn, method, url, **kwargs)
291
    if method != "POST":
292
        return _request_status_400(conn, method, url, **kwargs)
293 294
    req_token = kwargs['headers'].get('X-Auth-Token')
    if req_token != token['id']:
295
        return _request_status_401(conn, method, url, **kwargs)
296 297

    # Return
298
    body = json.loads(kwargs['body'])
299 300 301 302
    if 'uuids' in body:
        # Return uuid_catalog
        uuids = body['uuids']
        catalogs = {}
303 304
        if user['id'] in uuids:
            catalogs[user['id']] = user['name']
305 306 307 308 309
        return_catalog = {"displayname_catalog": {}, "uuid_catalog": catalogs}
    elif 'displaynames' in body:
        # Return displayname_catalog
        names = body['displaynames']
        catalogs = {}
310 311
        if user['name'] in names:
            catalogs[user['name']] = user['id']
312 313 314
        return_catalog = {"displayname_catalog": catalogs, "uuid_catalog": {}}
    else:
        return_catalog = {"displayname_catalog": {}, "uuid_catalog": {}}
315
    return ("", json.dumps(return_catalog), 200)
316 317


318 319 320 321 322 323 324 325 326 327 328
def _req_resources(conn, method, url, **kwargs):
    """Return quota resources"""
    global resources

    # Check input
    if conn.__class__.__name__ != "HTTPSConnection":
        return _request_status_302(conn, method, url, **kwargs)
    if method != "GET":
        return _request_status_400(conn, method, url, **kwargs)

    # Return
329
    return ("", json.dumps(resources), 200)
330 331


332 333
def _req_quotas(conn, method, url, **kwargs):
    """Return quotas for user_1"""
334
    global token, quotas
335 336 337 338 339 340

    # Check input
    if conn.__class__.__name__ != "HTTPSConnection":
        return _request_status_302(conn, method, url, **kwargs)
    if method != "GET":
        return _request_status_400(conn, method, url, **kwargs)
341 342
    req_token = kwargs['headers'].get('X-Auth-Token')
    if req_token != token['id']:
343 344 345
        return _request_status_401(conn, method, url, **kwargs)

    # Return
346
    return ("", json.dumps(quotas), 200)
347 348


349 350
def _req_commission(conn, method, url, **kwargs):
    """Perform a commission for user_1"""
351
    global token, pending_commissions, \
352
        commission_successful_response, commission_failure_response
353 354 355 356

    # Check input
    if conn.__class__.__name__ != "HTTPSConnection":
        return _request_status_302(conn, method, url, **kwargs)
357 358
    req_token = kwargs['headers'].get('X-Auth-Token')
    if req_token != token['id']:
359 360
        return _request_status_401(conn, method, url, **kwargs)

361 362 363
    if method == "POST":
        if 'body' not in kwargs:
            return _request_status_400(conn, method, url, **kwargs)
364
        body = json.loads(unicode(kwargs['body']))
365
        if re.match('/?'+api_commissions+'$', url) is not None:
366 367 368
            # Issue Commission
            # Check if we have enough resources to give
            if body['provisions'][1]['quantity'] > 420000000:
369
                return ("", json.dumps(commission_failure_response), 413)
370 371
            else:
                return \
372
                    ("", json.dumps(commission_successful_response), 200)
373
        else:
374
            # Issue commission action
375
            serial = url.split('/')[3]
376 377 378
            if serial == "action":
                # Resolve multiple actions
                if body == resolve_commissions_req:
379
                    return ("", json.dumps(resolve_commissions_rep), 200)
380 381 382 383 384 385 386 387 388 389 390
                else:
                    return _request_status_400(conn, method, url, **kwargs)
            else:
                # Issue action for one commission
                if serial != str(57):
                    return _request_status_404(conn, method, url, **kwargs)
                if len(body) != 1:
                    return _request_status_400(conn, method, url, **kwargs)
                if "accept" not in body.keys() and "reject" not in body.keys():
                    return _request_status_400(conn, method, url, **kwargs)
                return ("", "", 200)
391

392
    elif method == "GET":
393
        if re.match('/?'+api_commissions+'$', url) is not None:
394
            # Return pending commission
395
            return ("", json.dumps(pending_commissions), 200)
396 397
        else:
            # Return commissions's description
398
            serial = re.sub('/?' + api_commissions, '', url)[1:]
399
            if serial == str(57):
400
                return ("", json.dumps(commission_description), 200)
401 402
            else:
                return _request_status_404(conn, method, url, **kwargs)
403
    else:
404
        return _request_status_400(conn, method, url, **kwargs)
405 406


407 408 409 410 411 412
# --------------------------------------------------------------------
# The actual tests

class TestCallAstakos(unittest.TestCase):
    """Test cases for function _callAstakos"""

413
    # Patch astakosclient's _do_request function
414
    def setUp(self):  # noqa
415
        astakosclient._do_request = _mock_request
416 417 418

    # ----------------------------------
    # Test the response we get if we send invalid token
419
    def _invalid_token(self, pool):
420
        global auth_url
421
        token = "skaksaFlBl+fasFdaf24sx"
422
        try:
423 424
            client = AstakosClient(token, auth_url, use_pool=pool)
            client.authenticate()
425
        except Unauthorized:
426 427 428
            pass
        except Exception:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
429 430 431
        else:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")

432 433 434
    def test_invalid_token(self):
        """Test _invalid_token without pool"""
        self._invalid_token(False)
435

436 437 438
    def test_invalid_token_pool(self):
        """Test _invalid_token using pool"""
        self._invalid_token(True)
439 440 441

    # ----------------------------------
    # Test the response we get if we send invalid url
442
    def _invalid_url(self, pool):
443
        global token, auth_url
444
        try:
445 446
            client = AstakosClient(token['id'], auth_url, use_pool=pool)
            client._call_astakos("/astakos/api/misspelled")
447
        except NotFound:
448
            pass
449 450
        except Exception, e:
            self.fail("Got \"%s\" instead of 404" % e)
451 452 453
        else:
            self.fail("Should have returned 404 (Not Found)")

454 455 456
    def test_invalid_url(self):
        """Test _invalid_url without pool"""
        self._invalid_url(False)
457

458 459 460
    def test_invalid_url_pool(self):
        """Test _invalid_url using pool"""
        self._invalid_url(True)
461 462 463

    # ----------------------------------
    # Test the response we get if we use an unsupported scheme
464
    def _unsupported_scheme(self, pool):
465
        global token, auth_url
466
        try:
467 468 469
            client = AstakosClient(
                token['id'], "ftp://example.com", use_pool=pool)
            client.authenticate()
470
        except BadValue:
471 472
            pass
        except Exception:
473
            self.fail("Should have raise BadValue Exception")
474
        else:
475
            self.fail("Should have raise BadValue Exception")
476

477 478 479
    def test_unsupported_scheme(self):
        """Test _unsupported_scheme without pool"""
        self._unsupported_scheme(False)
480

481 482 483
    def test_unsupported_scheme_pool(self):
        """Test _unsupported_scheme using pool"""
        self._unsupported_scheme(True)
484 485 486

    # ----------------------------------
    # Test the response we get if we use http instead of https
487
    def _http_scheme(self, pool):
488
        global token
489
        http_auth_url = "http://example.org/identity/v2.0"
490
        try:
491 492
            client = AstakosClient(token['id'], http_auth_url, use_pool=pool)
            client.authenticate()
493 494
        except AstakosClientException as err:
            if err.status != 302:
495 496 497 498
                self.fail("Should have returned 302 (Found)")
        else:
            self.fail("Should have returned 302 (Found)")

499 500 501
    def test_http_scheme(self):
        """Test _http_scheme without pool"""
        self._http_scheme(False)
502

503 504 505
    def test_http_scheme_pool(self):
        """Test _http_scheme using pool"""
        self._http_scheme(True)
506 507

    # ----------------------------------
508 509 510
    # Test the response we get if we use authenticate with GET
    def _get_authenticate(self, pool):
        global token, auth_url
511
        try:
512 513
            client = AstakosClient(token['id'], auth_url, use_pool=pool)
            client._call_astakos(api_tokens, method="GET")
514
        except BadRequest:
515 516 517
            pass
        except Exception:
            self.fail("Should have returned 400 (Method not allowed)")
518 519 520
        else:
            self.fail("Should have returned 400 (Method not allowed)")

521 522 523
    def test_get_authenticate(self):
        """Test _get_authenticate without pool"""
        self._get_authenticate(False)
524

525 526 527
    def test_get_authenticate_pool(self):
        """Test _get_authenticate using pool"""
        self._get_authenticate(True)
528

529 530
    # ----------------------------------
    # Test the response if we request user_catalogs with GET
531
    def _get_user_catalogs(self, pool):
532
        global token, auth_url, api_usercatalogs
533
        try:
534 535
            client = AstakosClient(token['id'], auth_url, use_pool=pool)
            client._call_astakos(api_usercatalogs)
536
        except BadRequest:
537 538 539
            pass
        except Exception:
            self.fail("Should have returned 400 (Method not allowed)")
540 541 542
        else:
            self.fail("Should have returned 400 (Method not allowed)")

543 544 545
    def test_get_user_catalogs(self):
        """Test _get_user_catalogs without pool"""
        self._get_user_catalogs(False)
546

547 548 549
    def test_get_user_catalogs_pool(self):
        """Test _get_user_catalogs using pool"""
        self._get_user_catalogs(True)
550

551

552
class TestAuthenticate(unittest.TestCase):
553
    """Test cases for function getUserInfo"""
554

555
    # Patch astakosclient's _do_request function
556
    def setUp(self):  # noqa
557
        astakosclient._do_request = _mock_request
558 559 560

    # ----------------------------------
    # Test the response we get for invalid token
561
    def _invalid_token(self, pool):
562
        global auth_url
563
        token = "skaksaFlBl+fasFdaf24sx"
564
        try:
565 566
            client = AstakosClient(token, auth_url, use_pool=pool)
            client.authenticate()
567
        except Unauthorized:
568 569 570
            pass
        except Exception:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
571
        else:
572
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
573

574 575 576
    def test_invalid_token(self):
        """Test _invalid_token without pool"""
        self._invalid_token(False)
577

578 579 580
    def test_invalid_token_pool(self):
        """Test _invalid_token using pool"""
        self._invalid_token(True)
581

582
    # ----------------------------------
583
    # Test response for user
584 585
    def _auth_user(self, pool):
        global token, endpoints_with_info, auth_url
586
        try:
587 588
            client = AstakosClient(token['id'], auth_url, use_pool=pool)
            auth_info = client.authenticate()
589 590
        except Exception as err:
            self.fail("Shouldn't raise an Exception: %s" % err)
591
        self.assertEqual(endpoints_with_info, auth_info)
592

593 594
    def test_auth_user(self):
        """Test _auth_user without pool"""
595
        self._auth_user(False)
596

597
    def test_auth_user_pool(self):
598
        """Test _auth_user for User 1 using pool, with usage"""
599
        self._auth_user(True)
600 601


602 603 604
class TestDisplayNames(unittest.TestCase):
    """Test cases for functions getDisplayNames/getDisplayName"""

605
    # Patch astakosclient's _do_request function
606
    def setUp(self):  # noqa
607 608
        astakosclient._do_request = _mock_request

609 610
    # ----------------------------------
    # Test the response we get for invalid token
611
    def test_invalid_token(self):
612
        """Test the response we get for invalid token (without pool)"""
613
        global auth_url
614
        token = "skaksaFlBl+fasFdaf24sx"
615
        try:
616 617
            client = AstakosClient(token, auth_url)
            client.get_usernames(["12412351"])
618
        except Unauthorized:
619 620 621
            pass
        except Exception:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
622 623 624 625
        else:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")

    # ----------------------------------
626 627 628 629 630 631 632 633 634 635 636
    # Get username
    def test_username(self):
        """Test get_username"""
        global token, user, auth_url
        try:
            client = AstakosClient(token['id'], auth_url,
                                   use_pool=False, retry=2)
            info = client.get_username(user['id'])
        except Exception, e:
            self.fail("Shouldn't raise an Exception: %s" % e)
        self.assertEqual(info, user['name'])
637

638 639
    # ----------------------------------
    # Get info with wrong uuid
640
    def test_no_username(self):
641
        global token, auth_url
642
        try:
643 644
            client = AstakosClient(token['id'], auth_url)
            client.get_username("1234")
645
        except NoUserName:
646 647 648 649 650 651
            pass
        except:
            self.fail("Should have raised NoDisplayName exception")
        else:
            self.fail("Should have raised NoDisplayName exception")

652

653 654 655
class TestGetUUIDs(unittest.TestCase):
    """Test cases for functions getUUIDs/getUUID"""

656
    # Patch astakosclient's _do_request function
657
    def setUp(self):  # noqa
658 659
        astakosclient._do_request = _mock_request

660 661
    # ----------------------------------
    # Test the response we get for invalid token
662
    def test_invalid_token(self):
663
        """Test the response we get for invalid token (using pool)"""
664
        global user, auth_url
665
        token = "skaksaFlBl+fasFdaf24sx"
666
        try:
667 668
            client = AstakosClient(token, auth_url)
            client.get_uuids([user['name']])
669
        except Unauthorized:
670 671 672
            pass
        except Exception:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
673 674 675 676
        else:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")

    # ----------------------------------
677 678 679 680
    # Get uuid
    def test_get_uuid(self):
        """Test get_uuid"""
        global token, user, auth_url
681
        try:
682 683
            client = AstakosClient(token['id'], auth_url, retry=1)
            catalog = client.get_uuids([user['name']])
684 685
        except:
            self.fail("Shouldn't raise an Exception")
686
        self.assertEqual(catalog[user['name']], user['id'])
687

688 689
    # ----------------------------------
    # Get uuid with wrong username
690
    def test_no_uuid(self):
691
        global token, auth_url
692
        try:
693 694
            client = AstakosClient(token['id'], auth_url)
            client.get_uuid("1234")
695 696 697 698 699 700 701
        except NoUUID:
            pass
        except:
            self.fail("Should have raised NoUUID exception")
        else:
            self.fail("Should have raised NoUUID exception")

702

703 704 705
class TestResources(unittest.TestCase):
    """Test cases for function get_resources"""

706
    # Patch astakosclient's _do_request function
707
    def setUp(self):  # noqa
708 709
        astakosclient._do_request = _mock_request

710 711
    # ----------------------------------
    def test_get_resources(self):
712
        """Test function call of get_resources"""
713
        global resources, auth_url, token
714
        try:
715 716
            client = AstakosClient(token['id'], auth_url, retry=1)
            result = client.get_resources()
717 718 719 720 721
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        self.assertEqual(resources, result)


722 723 724
class TestQuotas(unittest.TestCase):
    """Test cases for function get_quotas"""

725
    # Patch astakosclient's _do_request function
726
    def setUp(self):  # noqa
727 728
        astakosclient._do_request = _mock_request

729 730 731
    # ----------------------------------
    def test_get_quotas(self):
        """Test function call of get_quotas"""
732
        global quotas, token, auth_url
733
        try:
734 735
            client = AstakosClient(token['id'], auth_url)
            result = client.get_quotas()
736 737 738 739 740 741 742
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        self.assertEqual(quotas, result)

    # -----------------------------------
    def test_get_quotas_unauthorized(self):
        """Test function call of get_quotas with wrong token"""
743 744
        global auth_url
        token = "buahfhsda"
745
        try:
746 747
            client = AstakosClient(token, auth_url)
            client.get_quotas()
748 749 750 751 752 753 754 755
        except Unauthorized:
            pass
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        else:
            self.fail("Should have raised Unauthorized Exception")


756
class TestCommissions(unittest.TestCase):
757
    """Test cases for quota commissions"""
758

759
    # Patch astakosclient's _do_request function
760
    def setUp(self):  # noqa
761 762
        astakosclient._do_request = _mock_request

763
    # ----------------------------------
764
    def test_issue_commission(self):
765
        """Test function call of issue_commission"""
766
        global token, commission_request, commission_successful_reqsponse
767
        global auth_url
768
        try:
769
            client = AstakosClient(token['id'], auth_url)
770
            response = client._issue_commission(commission_request)
771 772 773 774 775
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        self.assertEqual(response, commission_successful_response['serial'])

    # ----------------------------------
776
    def test_issue_commission_quota_limit(self):
777
        """Test function call of issue_commission with limit exceeded"""
778
        global token, commission_request, commission_failure_response
779
        global auth_url
780 781 782
        new_request = dict(commission_request)
        new_request['provisions'][1]['quantity'] = 520000000
        try:
783
            client = AstakosClient(token['id'], auth_url)
784
            client._issue_commission(new_request)
785 786 787 788 789 790 791
        except QuotaLimit:
            pass
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        else:
            self.fail("Should have raised QuotaLimit Exception")

792 793 794
    # ----------------------------------
    def test_issue_one_commission(self):
        """Test function call of issue_one_commission"""
795
        global token, commission_successful_response, auth_url
796
        try:
797 798 799
            client = AstakosClient(token['id'], auth_url)
            response = client.issue_one_commission(
                "c02f315b-7d84-45bc-a383-552a3f97d2ad",
800 801
                {("system", "cyclades.vm"): 1,
                 ("system", "cyclades.ram"): 30000})
802 803 804 805
        except Exception as err:
            self.fail("Shouldn't have raised Exception %s" % err)
        self.assertEqual(response, commission_successful_response['serial'])

806 807 808
    # ----------------------------------
    def test_get_pending_commissions(self):
        """Test function call of get_pending_commissions"""
809
        global token, pending_commissions, auth_url
810
        try:
811 812
            client = AstakosClient(token['id'], auth_url)
            response = client.get_pending_commissions()
813 814 815 816
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        self.assertEqual(response, pending_commissions)

817 818 819
    # ----------------------------------
    def test_get_commission_info(self):
        """Test function call of get_commission_info"""
820
        global token, commission_description, auth_url
821
        try:
822 823 824
            client = AstakosClient(token['id'], auth_url,
                                   use_pool=True, pool_size=2)
            response = client.get_commission_info(57)
825 826 827 828 829 830 831
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        self.assertEqual(response, commission_description)

    # ----------------------------------
    def test_get_commission_info_not_found(self):
        """Test function call of get_commission_info with invalid serial"""
832
        global token, auth_url
833
        try:
834 835
            client = AstakosClient(token['id'], auth_url)
            client.get_commission_info("57lala")
836 837 838 839 840 841 842 843 844 845
        except NotFound:
            pass
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        else:
            self.fail("Should have raised NotFound")

    # ----------------------------------
    def test_get_commission_info_without_serial(self):
        """Test function call of get_commission_info without serial"""
846
        global token, auth_url
847
        try:
848 849
            client = AstakosClient(token['id'], auth_url)
            client.get_commission_info(None)