Revision c4644612

b/astakosclient/astakosclient/__init__.py
68 68
    # ----------------------------------
69 69
    def __init__(self, astakos_url, retry=0,
70 70
                 use_pool=False, pool_size=8, logger=None):
71
        """Intialize AstakosClient Class
71
        """Initialize AstakosClient Class
72 72

  
73 73
        Keyword arguments:
74 74
        astakos_url -- i.e https://accounts.example.com (string)
......
111 111
    def _call_astakos(self, token, request_path,
112 112
                      headers=None, body=None, method="GET"):
113 113
        """Make the actual call to Astakos Service"""
114
        hashed_token = hashlib.sha1()
115
        hashed_token.update(token)
114
        if token is not None:
115
            hashed_token = hashlib.sha1()
116
            hashed_token.update(token)
117
            using_token = "using token %s" % (hashed_token.hexdigest())
118
        else:
119
            using_token = "without using token"
116 120
        self.logger.debug(
117
            "Make a %s request to %s using token %s "
118
            "with headers %s and body %s"
119
            % (method, request_path, hashed_token.hexdigest(), headers, body))
121
            "Make a %s request to %s %s with headers %s and body %s"
122
            % (method, request_path, using_token, headers, body))
120 123

  
121 124
        # Check Input
122
        if not token:
123
            m = "Token not given"
124
            self.logger.error(m)
125
            raise ValueError(m)
126 125
        if headers is None:
127 126
            headers = {}
128 127
        if body is None:
......
133 132
        # Build request's header and body
134 133
        kwargs = {}
135 134
        kwargs['headers'] = copy(headers)
136
        kwargs['headers']['X-Auth-Token'] = token
135
        if token is not None:
136
            kwargs['headers']['X-Auth-Token'] = token
137 137
        if body:
138 138
            kwargs['body'] = copy(body)
139 139
            kwargs['headers'].setdefault(
......
166 166
        return simplejson.loads(unicode(data))
167 167

  
168 168
    # ------------------------
169
    # GET /im/authenticate
169 170
    def get_user_info(self, token, usage=False):
170 171
        """Authenticate user and get user's info as a dictionary
171 172

  
......
184 185
        return self._call_astakos(token, auth_path)
185 186

  
186 187
    # ----------------------------------
188
    # POST /user_catalogs (or /service/api/user_catalogs)
189
    #   with {'uuids': uuids}
187 190
    def _uuid_catalog(self, token, uuids, req_path):
188 191
        req_headers = {'content-type': 'application/json'}
189 192
        req_body = simplejson.dumps({'uuids': uuids})
......
241 244
            raise NoUserName(uuid)
242 245

  
243 246
    # ----------------------------------
247
    # POST /user_catalogs (or /service/api/user_catalogs)
248
    #   with {'displaynames': display_names}
244 249
    def _displayname_catalog(self, token, display_names, req_path):
245 250
        req_headers = {'content-type': 'application/json'}
246 251
        req_body = simplejson.dumps({'displaynames': display_names})
......
298 303
            raise NoUUID(display_name)
299 304

  
300 305
    # ----------------------------------
306
    # GET "/im/get_services"
301 307
    def get_services(self):
302 308
        """Return a list of dicts with the registered services"""
303
        return self._call_astakos("dummy token", "/im/get_services")
309
        return self._call_astakos(None, "/im/get_services")
310

  
311
    # ----------------------------------
312
    # GET "/astakos/api/resources"
313
    def get_resources(self):
314
        """Return a dict of dicts with the available resources"""
315
        return self._call_astakos(None, "/astakos/api/resources")
304 316

  
305 317

  
306 318
# --------------------------------------------------------------------
b/astakosclient/astakosclient/tests.py
108 108

  
109 109
def _request_ok(conn, method, url, **kwargs):
110 110
    """This request behaves like original Astakos does"""
111
    if url[0:16] == "/im/authenticate":
111
    if url.startswith("/im/authenticate"):
112 112
        return _req_authenticate(conn, method, url, **kwargs)
113
    elif url[0:14] == "/user_catalogs":
113
    elif url.startswith("/user_catalogs"):
114 114
        return _req_catalogs(conn, method, url, **kwargs)
115
    elif url.startswith("/astakos/api/resources"):
116
        return _req_resources(conn, method, url, **kwargs)
115 117
    else:
116 118
        return _request_status_404(conn, method, url, **kwargs)
117 119

  
118 120

  
119 121
def _req_authenticate(conn, method, url, **kwargs):
120 122
    """Check if user exists and return his profile"""
121
    global user_1, user_2
123
    global user_1, user_2, token_1, token_2
122 124

  
123 125
    # Check input
124 126
    if conn.__class__.__name__ != "HTTPSConnection":
125 127
        return _request_status_302(conn, method, url, **kwargs)
126

  
127 128
    if method != "GET":
128 129
        return _request_status_400(conn, method, url, **kwargs)
129

  
130 130
    token = kwargs['headers']['X-Auth-Token']
131 131
    if token == token_1:
132 132
        user = dict(user_1)
......
150 150
    # Check input
151 151
    if conn.__class__.__name__ != "HTTPSConnection":
152 152
        return _request_status_302(conn, method, url, **kwargs)
153

  
154 153
    if method != "POST":
155 154
        return _request_status_400(conn, method, url, **kwargs)
156

  
157 155
    token = kwargs['headers']['X-Auth-Token']
158 156
    if token != token_1 and token != token_2:
159 157
        return _request_status_401(conn, method, url, **kwargs)
......
183 181
    return ("", simplejson.dumps(return_catalog), 200)
184 182

  
185 183

  
184
def _req_resources(conn, method, url, **kwargs):
185
    """Return quota resources"""
186
    global resources
187

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

  
194
    # Return
195
    return ("", simplejson.dumps(resources), 200)
196

  
197

  
186 198
# ----------------------------
187 199
# Mock the actual _doRequest
188 200
def _mock_request(new_requests):
......
266 278
          "display_name": "Storage Space",
267 279
          "name": "pithos+.diskspace"}]}
268 280

  
281
resources = {
282
    "cyclades.vm": {
283
        "unit": None,
284
        "description": "Number of virtual machines",
285
        "service": "cyclades"},
286
    "cyclades.ram": {
287
        "unit": "bytes",
288
        "description": "Virtual machine memory",
289
        "service": "cyclades"}}
290

  
269 291

  
270 292
# --------------------------------------------------------------------
271 293
# The actual tests
......
660 682
            self.fail("Should have raised NoUUID exception")
661 683

  
662 684

  
685
class TestResources(unittest.TestCase):
686
    """Test cases for function get_resources"""
687

  
688
    # ----------------------------------
689
    # Test function call of get_resources
690
    def test_get_resources(self):
691
        global resources
692
        _mock_request([_request_offline, _request_ok])
693
        try:
694
            client = AstakosClient("https://example.com", retry=1)
695
            result = client.get_resources()
696
        except Exception as err:
697
            self.fail("Shouldn't raise Exception %s" % err)
698
        self.assertEqual(resources, result)
699

  
700

  
663 701
# ----------------------------
664 702
# Run tests
665 703
if __name__ == "__main__":

Also available in: Unified diff