tests.py 40.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
#!/usr/bin/env python
#
# Copyright (C) 2012, 2013 GRNET S.A. All rights reserved.
#
# Redistribution and use in source and binary forms, with or
# without modification, are permitted provided that the following
# conditions are met:
#
#   1. Redistributions of source code must retain the above
#      copyright notice, this list of conditions and the following
#      disclaimer.
#
#   2. Redistributions in binary form must reproduce the above
#      copyright notice, this list of conditions and the following
#      disclaimer in the documentation and/or other materials
#      provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# The views and conclusions contained in the software and
# documentation are those of the authors and should not be
# interpreted as representing official policies, either expressed
# or implied, of GRNET S.A.

"""Unit Tests for the astakos-client module

Provides unit tests for the code implementing
the astakos client library

"""

43
import re
44
import sys
45
import socket
46
import simplejson
47 48

import astakosclient
49 50
from astakosclient import AstakosClient
from astakosclient.errors import \
51
    AstakosClientException, Unauthorized, BadRequest, NotFound, \
52
    NoUserName, NoUUID, BadValue, QuotaLimit
53 54

# Use backported unittest functionality if Python < 2.7
55 56 57 58 59 60
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
61 62 63 64 65 66 67


# --------------------------------------------------------------------
# Helper functions

# ----------------------------
# This functions will be used as mocked requests
68
def _request_offline(conn, method, url, **kwargs):
69 70 71 72
    """This request behaves as we were offline"""
    raise socket.gaierror


73
def _request_status_302(conn, method, url, **kwargs):
74
    """This request returns 302"""
75
    message = "FOUND"
76 77 78 79
    status = 302
    data = '<html>\r\n<head><title>302 Found</title></head>\r\n' \
        '<body bgcolor="white">\r\n<center><h1>302 Found</h1></center>\r\n' \
        '<hr><center>nginx/0.7.67</center>\r\n</body>\r\n</html>\r\n'
80
    return (message, data, status)
81 82


83
def _request_status_404(conn, method, url, **kwargs):
84
    """This request returns 404"""
85
    message = "Not Found"
86 87 88 89 90
    status = 404
    data = '<html><head><title>404 Not Found</title></head>' \
        '<body><h1>Not Found</h1><p>The requested URL /foo was ' \
        'not found on this server.</p><hr><address>Apache Server ' \
        'at example.com Port 80</address></body></html>'
91
    return (message, data, status)
92 93


94 95 96 97 98 99 100 101
def _request_status_403(conn, method, url, **kwargs):
    """This request returns 403"""
    message = "UNAUTHORIZED"
    status = 403
    data = "Forbidden"
    return (message, data, status)


102
def _request_status_401(conn, method, url, **kwargs):
103
    """This request returns 401"""
104
    message = "UNAUTHORIZED"
105 106
    status = 401
    data = "Invalid X-Auth-Token\n"
107
    return (message, data, status)
108 109


110
def _request_status_400(conn, method, url, **kwargs):
111
    """This request returns 400"""
112
    message = "BAD REQUEST"
113 114
    status = 400
    data = "Method not allowed.\n"
115
    return (message, data, status)
116 117


118
def _request_ok(conn, method, url, **kwargs):
119
    """This request behaves like original Astakos does"""
120 121
    if re.match('/?' + astakosclient.API_AUTHENTICATE, url) is not None:
        print "here 1"
122
        return _req_authenticate(conn, method, url, **kwargs)
123 124
    elif re.match('/?' + astakosclient.API_USERCATALOGS, url) is not None:
        print "here 2"
125
        return _req_catalogs(conn, method, url, **kwargs)
126 127
    elif re.match('/?' + astakosclient.API_RESOURCES, url) is not None:
        print "here 3"
128
        return _req_resources(conn, method, url, **kwargs)
129
    elif re.match('/?' + astakosclient.API_QUOTAS, url) is not None:
130
        return _req_quotas(conn, method, url, **kwargs)
131
    elif re.match('/?' + astakosclient.API_COMMISSIONS, url) is not None:
132
        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
    else:
136
        print "here 4"
137
        return _request_status_404(conn, method, url, **kwargs)
138 139


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

144
    # Check input
145
    if conn.__class__.__name__ != "HTTPSConnection":
146
        return _request_status_302(conn, method, url, **kwargs)
147
    if method != "GET":
148
        return _request_status_400(conn, method, url, **kwargs)
149
    token = kwargs['headers'].get('X-Auth-Token')
150
    if token == token_1:
151
        user = dict(user_1)
152
    elif token == token_2:
153
        user = dict(user_2)
154 155
    else:
        # No user found
156
        return _request_status_401(conn, method, url, **kwargs)
157

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


165
def _req_catalogs(conn, method, url, **kwargs):
166
    """Return user catalogs"""
167 168
    global token_1, token_2, user_1, user_2

169
    # Check input
170
    if conn.__class__.__name__ != "HTTPSConnection":
171
        return _request_status_302(conn, method, url, **kwargs)
172
    if method != "POST":
173
        return _request_status_400(conn, method, url, **kwargs)
174
    token = kwargs['headers'].get('X-Auth-Token')
175
    if token != token_1 and token != token_2:
176
        return _request_status_401(conn, method, url, **kwargs)
177 178 179

    # Return
    body = simplejson.loads(kwargs['body'])
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
    if 'uuids' in body:
        # Return uuid_catalog
        uuids = body['uuids']
        catalogs = {}
        if user_1['uuid'] in uuids:
            catalogs[user_1['uuid']] = user_1['username']
        if user_2['uuid'] in uuids:
            catalogs[user_2['uuid']] = user_2['username']
        return_catalog = {"displayname_catalog": {}, "uuid_catalog": catalogs}
    elif 'displaynames' in body:
        # Return displayname_catalog
        names = body['displaynames']
        catalogs = {}
        if user_1['username'] in names:
            catalogs[user_1['username']] = user_1['uuid']
        if user_2['username'] in names:
            catalogs[user_2['username']] = user_2['uuid']
        return_catalog = {"displayname_catalog": catalogs, "uuid_catalog": {}}
    else:
        return_catalog = {"displayname_catalog": {}, "uuid_catalog": {}}
200
    return ("", simplejson.dumps(return_catalog), 200)
201 202


203 204 205 206 207 208 209 210 211 212 213 214 215 216
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
    return ("", simplejson.dumps(resources), 200)


217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
def _req_quotas(conn, method, url, **kwargs):
    """Return quotas for user_1"""
    global token_1, quotas

    # 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)
    token = kwargs['headers'].get('X-Auth-Token')
    if token != token_1:
        return _request_status_401(conn, method, url, **kwargs)

    # Return
    return ("", simplejson.dumps(quotas), 200)


234 235
def _req_commission(conn, method, url, **kwargs):
    """Perform a commission for user_1"""
236 237
    global token_1, pending_commissions, \
        commission_successful_response, commission_failure_response
238 239 240 241 242 243 244 245

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

246 247 248 249
    if method == "POST":
        if 'body' not in kwargs:
            return _request_status_400(conn, method, url, **kwargs)
        body = simplejson.loads(unicode(kwargs['body']))
250
        if re.match('/?'+astakosclient.API_COMMISSIONS+'$', url) is not None:
251 252 253 254 255 256 257
            # Issue Commission
            # Check if we have enough resources to give
            if body['provisions'][1]['quantity'] > 420000000:
                return ("", simplejson.dumps(commission_failure_response), 413)
            else:
                return \
                    ("", simplejson.dumps(commission_successful_response), 200)
258
        else:
259 260
            # Issue commission action
            serial = url.split('/')[4]
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275
            if serial == "action":
                # Resolve multiple actions
                if body == resolve_commissions_req:
                    return ("", simplejson.dumps(resolve_commissions_rep), 200)
                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)
276

277
    elif method == "GET":
278
        if re.match('/?'+astakosclient.API_COMMISSIONS+'$', url) is not None:
279 280 281 282
            # Return pending commission
            return ("", simplejson.dumps(pending_commissions), 200)
        else:
            # Return commissions's description
283
            serial = re.sub('/?' + astakosclient.API_COMMISSIONS, '', url)[1:]
284 285 286 287
            if serial == str(57):
                return ("", simplejson.dumps(commission_description), 200)
            else:
                return _request_status_404(conn, method, url, **kwargs)
288
    else:
289
        return _request_status_400(conn, method, url, **kwargs)
290 291


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

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

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


315 316
# ----------------------------
# Mock the actual _doRequest
317
def _mock_request(new_requests):
318 319 320 321 322 323 324 325 326 327 328 329 330
    """Mock the actual request

    Given a list of requests to use (in rotation),
    replace the original _doRequest function with
    a new one

    """
    def _mock(conn, method, url, **kwargs):
        # Get first request
        request = _mock.requests[0]
        # Rotate requests
        _mock.requests = _mock.requests[1:] + _mock.requests[:1]
        # Use first request
331
        return request(conn, method, url, **kwargs)
332 333 334

    _mock.requests = new_requests
    # Replace `_doRequest' with our `_mock'
335
    astakosclient._do_request = _mock
336 337 338 339


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

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

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

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

438 439 440
quotas = {
    "system": {
        "cyclades.ram": {
441
            "pending": 0,
442
            "limit": 1073741824,
443
            "usage": 536870912},
444
        "cyclades.vm": {
445
            "pending": 0,
446
            "limit": 2,
447
            "usage": 2}},
448 449
    "project:1": {
        "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 459 460
commission_request = {
    "force": False,
    "auto_accept": False,
461
    "name": "my commission",
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488
    "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",
489 490
            "limit": 600000000,
            "usage": 180000000}}}
491

492 493
pending_commissions = [100, 200]

494 495
commission_description = {
    "serial": 57,
496
    "issue_time": "2013-04-08T10:19:15.0373+00:00",
497
    "name": "a commission",
498 499 500 501 502 503 504 505 506 507 508 509 510 511
    "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
        }]}

512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528
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}}]]}

529 530 531 532 533 534 535

# --------------------------------------------------------------------
# The actual tests

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

536 537 538
    # ----------------------------------
    # Test the response we get if we don't have internet access
    def _offline(self, pool):
539
        global token_1
540
        _mock_request([_request_offline])
541
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
542
            client = AstakosClient("https://example.com", use_pool=pool)
543
            client._call_astakos(token_1, astakosclient.API_AUTHENTICATE)
544
        except AstakosClientException:
545 546
            pass
        else:
547
            self.fail("Should have raised AstakosClientException")
548

549
    def test_offline(self):
550 551 552
        """Test _offline without pool"""
        self._offline(False)

553
    def test_offline_pool(self):
554 555 556 557 558
        """Test _offline using pool"""
        self._offline(True)

    # ----------------------------------
    # Test the response we get if we send invalid token
559
    def _invalid_token(self, pool):
560
        token = "skaksaFlBl+fasFdaf24sx"
561
        _mock_request([_request_ok])
562
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
563
            client = AstakosClient("https://example.com", use_pool=pool)
564
            client._call_astakos(token, astakosclient.API_AUTHENTICATE)
565
        except Unauthorized:
566 567 568
            pass
        except Exception:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
569 570 571
        else:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")

572 573 574
    def test_invalid_token(self):
        """Test _invalid_token without pool"""
        self._invalid_token(False)
575

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

    # ----------------------------------
    # Test the response we get if we send invalid url
582
    def _invalid_url(self, pool):
583
        global token_1
584
        _mock_request([_request_ok])
585
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
586
            client = AstakosClient("https://example.com", use_pool=pool)
587
            client._call_astakos(token_1, "/astakos/api/misspelled")
588
        except NotFound:
589 590 591
            pass
        except Exception:
            self.fail("Should have returned 404 (Not Found)")
592 593 594
        else:
            self.fail("Should have returned 404 (Not Found)")

595 596 597
    def test_invalid_url(self):
        """Test _invalid_url without pool"""
        self._invalid_url(False)
598

599 600 601
    def test_invalid_url_pool(self):
        """Test _invalid_url using pool"""
        self._invalid_url(True)
602 603 604

    # ----------------------------------
    # Test the response we get if we use an unsupported scheme
605
    def _unsupported_scheme(self, pool):
606
        global token_1
607
        _mock_request([_request_ok])
608
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
609
            client = AstakosClient("ftp://example.com", use_pool=pool)
610
            client._call_astakos(token_1, astakosclient.API_AUTHENTICATE)
611
        except BadValue:
612 613
            pass
        except Exception:
614
            self.fail("Should have raise BadValue Exception")
615
        else:
616
            self.fail("Should have raise BadValue Exception")
617

618 619 620
    def test_unsupported_scheme(self):
        """Test _unsupported_scheme without pool"""
        self._unsupported_scheme(False)
621

622 623 624
    def test_unsupported_scheme_pool(self):
        """Test _unsupported_scheme using pool"""
        self._unsupported_scheme(True)
625 626 627

    # ----------------------------------
    # Test the response we get if we use http instead of https
628
    def _http_scheme(self, pool):
629
        global token_1
630
        _mock_request([_request_ok])
631
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
632
            client = AstakosClient("http://example.com", use_pool=pool)
633
            client._call_astakos(token_1, astakosclient.API_AUTHENTICATE)
634 635
        except AstakosClientException as err:
            if err.status != 302:
636 637 638 639
                self.fail("Should have returned 302 (Found)")
        else:
            self.fail("Should have returned 302 (Found)")

640 641 642
    def test_http_scheme(self):
        """Test _http_scheme without pool"""
        self._http_scheme(False)
643

644 645 646
    def test_http_scheme_pool(self):
        """Test _http_scheme using pool"""
        self._http_scheme(True)
647 648 649

    # ----------------------------------
    # Test the response we get if we use authenticate with POST
650
    def _post_authenticate(self, pool):
651
        global token_1
652
        _mock_request([_request_ok])
653
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
654
            client = AstakosClient("https://example.com", use_pool=pool)
655 656
            client._call_astakos(
                token_1, astakosclient.API_AUTHENTICATE, method="POST")
657
        except BadRequest:
658 659 660
            pass
        except Exception:
            self.fail("Should have returned 400 (Method not allowed)")
661 662 663
        else:
            self.fail("Should have returned 400 (Method not allowed)")

664 665 666
    def test_post_authenticate(self):
        """Test _post_authenticate without pool"""
        self._post_authenticate(False)
667

668 669 670
    def test_post_authenticate_pool(self):
        """Test _post_authenticate using pool"""
        self._post_authenticate(True)
671

672 673
    # ----------------------------------
    # Test the response if we request user_catalogs with GET
674
    def _get_user_catalogs(self, pool):
675
        global token_1
676
        _mock_request([_request_ok])
677
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
678
            client = AstakosClient("https://example.com", use_pool=pool)
679
            client._call_astakos(token_1, astakosclient.API_USERCATALOGS)
680
        except BadRequest:
681 682 683
            pass
        except Exception:
            self.fail("Should have returned 400 (Method not allowed)")
684 685 686
        else:
            self.fail("Should have returned 400 (Method not allowed)")

687 688 689
    def test_get_user_catalogs(self):
        """Test _get_user_catalogs without pool"""
        self._get_user_catalogs(False)
690

691 692 693
    def test_get_user_catalogs_pool(self):
        """Test _get_user_catalogs using pool"""
        self._get_user_catalogs(True)
694

695

696
class TestAuthenticate(unittest.TestCase):
697
    """Test cases for function getUserInfo"""
698 699 700

    # ----------------------------------
    # Test the response we get if we don't have internet access
701
    def test_offline(self):
702 703
        """Test offline after 3 retries"""
        global token_1
704
        _mock_request([_request_offline])
705
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
706
            client = AstakosClient("https://example.com", retry=3)
707
            client.get_user_info(token_1)
708 709 710 711 712 713 714
        except AstakosClientException:
            pass
        else:
            self.fail("Should have raised AstakosClientException exception")

    # ----------------------------------
    # Test the response we get for invalid token
715
    def _invalid_token(self, pool):
716
        token = "skaksaFlBl+fasFdaf24sx"
717
        _mock_request([_request_ok])
718
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
719
            client = AstakosClient("https://example.com", use_pool=pool)
720
            client.get_user_info(token)
721
        except Unauthorized:
722 723 724
            pass
        except Exception:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
725
        else:
726
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
727

728 729 730
    def test_invalid_token(self):
        """Test _invalid_token without pool"""
        self._invalid_token(False)
731

732 733 734
    def test_invalid_token_pool(self):
        """Test _invalid_token using pool"""
        self._invalid_token(True)
735 736 737

    #- ---------------------------------
    # Test response for user 1
738 739
    def _auth_user(self, token, user_info, usage, pool):
        _mock_request([_request_ok])
740
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
741
            client = AstakosClient("https://example.com", use_pool=pool)
742
            auth_info = client.get_user_info(token, usage=usage)
743 744 745 746
        except:
            self.fail("Shouldn't raise an Exception")
        self.assertEqual(user_info, auth_info)

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

754 755
    def test_auth_user_one_usage(self):
        """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)
758

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

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

771 772
    def test_auth_user_two_usage(self):
        """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 777
    def test_auth_user_two_usage_pool(self):
        """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)
780 781 782

    # ----------------------------------
    # Test retry functionality
783
    def test_offline_retry(self):
784
        """Test retry functionality for getUserInfo"""
785
        global token_1, user_1
786
        _mock_request([_request_offline, _request_offline, _request_ok])
787
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
788
            client = AstakosClient("https://example.com", retry=2)
789
            auth_info = client.get_user_info(token_1, usage=True)
790 791 792
        except:
            self.fail("Shouldn't raise an Exception")
        self.assertEqual(user_1, auth_info)
793 794


795 796 797 798 799
class TestDisplayNames(unittest.TestCase):
    """Test cases for functions getDisplayNames/getDisplayName"""

    # ----------------------------------
    # Test the response we get for invalid token
800
    def test_invalid_token(self):
801 802
        """Test the response we get for invalid token (without pool)"""
        global user_1
803
        token = "skaksaFlBl+fasFdaf24sx"
804
        _mock_request([_request_ok])
805
        try:
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
806
            client = AstakosClient("https://example.com")
807
            client.get_usernames(token, [user_1['uuid']])
808
        except Unauthorized:
809 810 811
            pass
        except Exception:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
812 813 814 815 816
        else:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")

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

    # ----------------------------------
    # Get info for user 1
832 833
    def test_username_user_one(self):
        """Test get_username for User One"""
834
        global token_2, user_1
835
        _mock_request([_request_offline, _request_ok])
836 837
        try:
            client = AstakosClient(
Ilias Tsitsimpis's avatar
Ilias Tsitsimpis committed
838
                "https://example.com", use_pool=True, retry=2)
839
            info = client.get_username(token_2, user_1['uuid'])
840 841 842 843
        except:
            self.fail("Shouldn't raise an Exception")
        self.assertEqual(info, user_1['username'])

844 845
    # ----------------------------------
    # Get info with wrong uuid
846
    def test_no_username(self):
847
        global token_1
848
        _mock_request([_request_ok])
849 850
        try:
            client = AstakosClient("https://example.com")
851 852
            client.get_username(token_1, "1234")
        except NoUserName:
853 854 855 856 857 858
            pass
        except:
            self.fail("Should have raised NoDisplayName exception")
        else:
            self.fail("Should have raised NoDisplayName exception")

859

860 861 862 863 864
class TestGetUUIDs(unittest.TestCase):
    """Test cases for functions getUUIDs/getUUID"""

    # ----------------------------------
    # Test the response we get for invalid token
865
    def test_invalid_token(self):
866 867
        """Test the response we get for invalid token (using pool)"""
        global user_1
868
        token = "skaksaFlBl+fasFdaf24sx"
869
        _mock_request([_request_ok])
870 871
        try:
            client = AstakosClient("https://example.com")
872
            client.get_uuids(token, [user_1['username']])
873
        except Unauthorized:
874 875 876
            pass
        except Exception:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")
877 878 879 880 881
        else:
            self.fail("Should have returned 401 (Invalid X-Auth-Token)")

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

    # ----------------------------------
    # Get uuid for user 2
897 898
    def test_get_uuid_user_two(self):
        """Test get_uuid for User Two"""
899
        global token_1, user_2
900
        _mock_request([_request_offline, _request_ok])
901 902
        try:
            client = AstakosClient("https://example.com", retry=1)
903
            info = client.get_uuid(token_2, user_1['username'])
904 905 906 907
        except:
            self.fail("Shouldn't raise an Exception")
        self.assertEqual(info, user_1['uuid'])

908 909
    # ----------------------------------
    # Get uuid with wrong username
910
    def test_no_uuid(self):
911
        global token_1
912
        _mock_request([_request_ok])
913 914
        try:
            client = AstakosClient("https://example.com")
915
            client.get_uuid(token_1, "1234")
916 917 918 919 920 921 922
        except NoUUID:
            pass
        except:
            self.fail("Should have raised NoUUID exception")
        else:
            self.fail("Should have raised NoUUID exception")

923

924 925 926 927 928
class TestResources(unittest.TestCase):
    """Test cases for function get_resources"""

    # ----------------------------------
    def test_get_resources(self):
929
        """Test function call of get_resources"""
930 931 932 933 934 935 936 937 938 939
        global resources
        _mock_request([_request_offline, _request_ok])
        try:
            client = AstakosClient("https://example.com", retry=1)
            result = client.get_resources()
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        self.assertEqual(resources, result)


940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971
class TestQuotas(unittest.TestCase):
    """Test cases for function get_quotas"""

    # ----------------------------------
    def test_get_quotas(self):
        """Test function call of get_quotas"""
        global quotas, token_1
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            result = client.get_quotas(token_1)
        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"""
        global token_2
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            client.get_quotas(token_2)
        except Unauthorized:
            pass
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        else:
            self.fail("Should have raised Unauthorized Exception")

    # ----------------------------------
    def test_get_quotas_without_token(self):
972
        """Test function call of get_quotas without token"""
973 974 975 976 977 978 979 980 981 982 983 984
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            client.get_quotas(None)
        except Unauthorized:
            pass
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        else:
            self.fail("Should have raised Unauthorized Exception")


985
class TestCommissions(unittest.TestCase):
986
    """Test cases for quota commissions"""
987 988

    # ----------------------------------
989
    def test_issue_commission(self):
990
        """Test function call of issue_commission"""
991 992 993 994 995 996 997 998 999 1000
        global token_1, commission_request, commission_successful_reqsponse
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            response = client.issue_commission(token_1, commission_request)
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        self.assertEqual(response, commission_successful_response['serial'])

    # ----------------------------------
1001
    def test_issue_commission_quota_limit(self):
1002
        """Test function call of issue_commission with limit exceeded"""
1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
        global token_1, commission_request, commission_failure_response
        _mock_request([_request_ok])
        new_request = dict(commission_request)
        new_request['provisions'][1]['quantity'] = 520000000
        try:
            client = AstakosClient("https://example.com")
            client.issue_commission(token_1, new_request)
        except QuotaLimit:
            pass
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        else:
            self.fail("Should have raised QuotaLimit Exception")

1017 1018 1019 1020 1021 1022 1023 1024 1025
    # ----------------------------------
    def test_issue_one_commission(self):
        """Test function call of issue_one_commission"""
        global token_1, commission_successful_response
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            response = client.issue_one_commission(
                token_1, "c02f315b-7d84-45bc-a383-552a3f97d2ad",
1026
                "system", {"cyclades.vm": 1, "cyclades.ram": 30000})
1027 1028 1029 1030
        except Exception as err:
            self.fail("Shouldn't have raised Exception %s" % err)
        self.assertEqual(response, commission_successful_response['serial'])

1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
    # ----------------------------------
    def test_get_pending_commissions(self):
        """Test function call of get_pending_commissions"""
        global token_1, pending_commissions
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            response = client.get_pending_commissions(token_1)
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        self.assertEqual(response, pending_commissions)

1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085
    # ----------------------------------
    def test_get_commission_info(self):
        """Test function call of get_commission_info"""
        global token_1, commission_description
        _mock_request([_request_ok])
        try:
            client = \
                AstakosClient("https://example.com", use_pool=True, pool_size=2)
            response = client.get_commission_info(token_1, 57)
        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"""
        global token_1
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            client.get_commission_info(token_1, "57lala")
        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"""
        global token_1
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            client.get_commission_info(token_1, None)
        except BadValue:
            pass
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        else:
            self.fail("Should have raise BadValue")

1086
    # ----------------------------------
1087 1088
    def test_commision_action(self):
        """Test function call of commision_action with wrong action"""
1089 1090 1091 1092
        global token_1
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
1093
            client.commission_action(token_1, 57, "lala")
1094 1095 1096 1097 1098 1099 1100 1101
        except BadRequest:
            pass
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        else:
            self.fail("Should have raised BadRequest")

    # ----------------------------------
1102 1103
    def test_accept_commission(self):
        """Test function call of accept_commission"""
1104 1105 1106 1107
        global token_1
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
1108
            client.accept_commission(token_1, 57)
1109 1110 1111 1112
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)

    # ----------------------------------
1113 1114
    def test_reject_commission(self):
        """Test function call of reject_commission"""
1115 1116 1117 1118
        global token_1
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
1119
            client.reject_commission(token_1, 57)
1120 1121 1122
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)

1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    # ----------------------------------
    def test_accept_commission_not_found(self):
        """Test function call of accept_commission with wrong serial"""
        global token_1
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            client.reject_commission(token_1, 20)
        except NotFound:
            pass
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        else:
            self.fail("Should have raised NotFound")

1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149
    # ----------------------------------
    def test_resolve_commissions(self):
        """Test function call of resolve_commissions"""
        global token_1
        _mock_request([_request_ok])
        try:
            client = AstakosClient("https://example.com")
            result = client.resolve_commissions(token_1, [56, 57], [56, 58, 59])
        except Exception as err:
            self.fail("Shouldn't raise Exception %s" % err)
        self.assertEqual(result, resolve_commissions_rep)

1150

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

    # ----------------------------------
    def test_get_endpoints(self):
        """Test function call of get_endpoints"""
1157 1158 1159 1160