Commit 20a8189b authored by Ilias Tsitsimpis's avatar Ilias Tsitsimpis

astakosclient: Add request for Commissions

Refs #3440
parent 6dee206f
......@@ -41,7 +41,7 @@ import simplejson
from astakosclient.utils import retry, scheme_to_class
from astakosclient.errors import \
AstakosClientException, Unauthorized, BadRequest, NotFound, Forbidden, \
NoUserName, NoUUID, BadValue
NoUserName, NoUUID, BadValue, QuotaLimit
# --------------------------------------------------------------------
......@@ -317,9 +317,49 @@ class AstakosClient():
# ----------------------------------
# GET "/astakos/api/quotas"
def get_quotas(self, token):
"""Return a dict of dicts with user's current quotas"""
"""Get user's quotas
Keyword arguments:
token -- user's token (string)
In case of success return a dict of dicts with user's current quotas.
Otherwise raise an AstakosClientException
"""
return self._call_astakos(token, "/astakos/api/quotas")
# ----------------------------------
# POST "/astakos/api/commisions"
def issue_commission(self, token, request):
"""Issue a commission
Keyword arguments:
token -- user's token (string)
request -- commision request (dict)
In case of success return commission's id (int).
Otherwise raise an AstakosClientException.
"""
req_headers = {'content-type': 'application/json'}
req_body = simplejson.dumps(request)
try:
response = self._call_astakos(token, "/astakos/api/commissions",
req_headers, req_body, "POST")
except AstakosClientException as err:
if err.status == 413:
raise QuotaLimit(err.message, err.details)
else:
raise
if "serial" in response:
return response['serial']
else:
m = "issue_commission_core request returned %s. No serial found" \
% response
self.logger.error(m)
raise AstakosClientException(m)
# --------------------------------------------------------------------
# Private functions
......
......@@ -65,6 +65,10 @@ class NotFound(AstakosClientException):
status = 404
class QuotaLimit(AstakosClientException):
status = 413
class NoUserName(AstakosClientException):
def __init__(self, uuid):
"""No display name for the given uuid"""
......
......@@ -48,7 +48,7 @@ import astakosclient
from astakosclient import AstakosClient
from astakosclient.errors import \
AstakosClientException, Unauthorized, BadRequest, NotFound, \
NoUserName, NoUUID, BadValue
NoUserName, NoUUID, BadValue, QuotaLimit
# Use backported unittest functionality if Python < 2.7
try:
......@@ -116,6 +116,8 @@ def _request_ok(conn, method, url, **kwargs):
return _req_resources(conn, method, url, **kwargs)
elif url.startswith("/astakos/api/quotas"):
return _req_quotas(conn, method, url, **kwargs)
elif url.startswith("/astakos/api/commissions"):
return _req_commission(conn, method, url, **kwargs)
else:
return _request_status_404(conn, method, url, **kwargs)
......@@ -214,6 +216,29 @@ def _req_quotas(conn, method, url, **kwargs):
return ("", simplejson.dumps(quotas), 200)
def _req_commission(conn, method, url, **kwargs):
"""Perform a commission for user_1"""
global token_1, commission_successful_response, commission_failure_response
# Check input
if conn.__class__.__name__ != "HTTPSConnection":
return _request_status_302(conn, method, url, **kwargs)
if method != "POST":
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)
if 'body' not in kwargs:
return _request_status_400(conn, method, url, **kwargs)
# Check if we have enough resources to give
body = simplejson.loads(unicode(kwargs['body']))
if body['provisions'][1]['quantity'] > 420000000:
return ("", simplejson.dumps(commission_failure_response), 413)
else:
return ("", simplejson.dumps(commission_successful_response), 200)
# ----------------------------
# Mock the actual _doRequest
def _mock_request(new_requests):
......@@ -327,6 +352,38 @@ quotas = {
"limit": 5,
"used": 2}}}
commission_request = {
"force": False,
"auto_accept": False,
"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",
"available": 420000000}}}
# --------------------------------------------------------------------
# The actual tests
......@@ -769,6 +826,7 @@ class TestQuotas(unittest.TestCase):
# ----------------------------------
def test_get_quotas_without_token(self):
"""Test function call of get_quotas without token"""
_mock_request([_request_ok])
try:
client = AstakosClient("https://example.com")
......@@ -781,6 +839,39 @@ class TestQuotas(unittest.TestCase):
self.fail("Should have raised Unauthorized Exception")
class TestCommissions(unittest.TestCase):
"""Test cases for function issue_commision"""
# ----------------------------------
def test_issue_commission_core(self):
"""Test function call of issue_commission_core"""
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'])
# ----------------------------------
def test_issue_commission_core_quota_limit(self):
"""Test function call of issue_commission_core with limit exceeded"""
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")
# ----------------------------
# Run tests
if __name__ == "__main__":
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment