Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / tests / api.py @ 381a548c

History | View | Annotate | Download (26.5 kB)

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

    
34
from astakos.im.tests.common import *
35
from astakos.im.settings import astakos_services, BASE_HOST
36
from synnefo.lib.services import get_service_path
37
from synnefo.lib import join_urls
38

    
39
from django.test import TestCase
40
from django.core.urlresolvers import reverse
41

    
42
from datetime import date
43

    
44
#from xml.dom import minidom
45

    
46
import json
47

    
48
ROOT = "/%s/%s/%s/" % (
49
    astakos_settings.BASE_PATH, astakos_settings.ACCOUNTS_PREFIX, 'v1.0')
50
u = lambda url: ROOT + url
51

    
52

    
53
class QuotaAPITest(TestCase):
54
    def test_0(self):
55
        client = Client()
56

    
57
        component1 = Component.objects.create(name="comp1")
58
        register.add_service(component1, "service1", "type1", [])
59
        # custom service resources
60
        resource11 = {"name": "service1.resource11",
61
                      "desc": "resource11 desc",
62
                      "service_type": "type1",
63
                      "service_origin": "service1",
64
                      "allow_in_projects": True}
65
        r, _ = register.add_resource(resource11)
66
        register.update_resource(r, 100)
67
        resource12 = {"name": "service1.resource12",
68
                      "desc": "resource11 desc",
69
                      "service_type": "type1",
70
                      "service_origin": "service1",
71
                      "unit": "bytes"}
72
        r, _ = register.add_resource(resource12)
73
        register.update_resource(r, 1024)
74

    
75
        # create user
76
        user = get_local_user('test@grnet.gr')
77
        quotas.qh_sync_user(user)
78

    
79
        component2 = Component.objects.create(name="comp2")
80
        register.add_service(component2, "service2", "type2", [])
81
        # create another service
82
        resource21 = {"name": "service2.resource21",
83
                      "desc": "resource11 desc",
84
                      "service_type": "type2",
85
                      "service_origin": "service2",
86
                      "allow_in_projects": False}
87
        r, _ = register.add_resource(resource21)
88
        register.update_resource(r, 3)
89

    
90
        resource_names = [r['name'] for r in
91
                          [resource11, resource12, resource21]]
92

    
93
        # get resources
94
        r = client.get(u('resources'))
95
        self.assertEqual(r.status_code, 200)
96
        body = json.loads(r.content)
97
        for name in resource_names:
98
            assertIn(name, body)
99

    
100
        # get quota
101
        r = client.get(u('quotas'))
102
        self.assertEqual(r.status_code, 401)
103

    
104
        headers = {'HTTP_X_AUTH_TOKEN': user.auth_token}
105
        r = client.get(u('quotas/'), **headers)
106
        self.assertEqual(r.status_code, 200)
107
        body = json.loads(r.content)
108
        system_quota = body['system']
109
        assertIn('system', body)
110
        for name in resource_names:
111
            assertIn(name, system_quota)
112

    
113
        r = client.get(u('service_quotas'))
114
        self.assertEqual(r.status_code, 401)
115

    
116
        s1_headers = {'HTTP_X_AUTH_TOKEN': component1.auth_token}
117
        r = client.get(u('service_quotas'), **s1_headers)
118
        self.assertEqual(r.status_code, 200)
119
        body = json.loads(r.content)
120
        assertIn(user.uuid, body)
121

    
122
        r = client.get(u('commissions'), **s1_headers)
123
        self.assertEqual(r.status_code, 200)
124
        body = json.loads(r.content)
125
        self.assertEqual(body, [])
126

    
127
        # issue some commissions
128
        commission_request = {
129
            "force": False,
130
            "auto_accept": False,
131
            "name": "my commission",
132
            "provisions": [
133
                {
134
                    "holder": user.uuid,
135
                    "source": "system",
136
                    "resource": resource11['name'],
137
                    "quantity": 1
138
                },
139
                {
140
                    "holder": user.uuid,
141
                    "source": "system",
142
                    "resource": resource12['name'],
143
                    "quantity": 30000
144
                }]}
145

    
146
        post_data = json.dumps(commission_request)
147
        r = client.post(u('commissions'), post_data,
148
                        content_type='application/json', **s1_headers)
149
        self.assertEqual(r.status_code, 413)
150

    
151
        commission_request = {
152
            "force": False,
153
            "auto_accept": False,
154
            "name": "my commission",
155
            "provisions": [
156
                {
157
                    "holder": user.uuid,
158
                    "source": "system",
159
                    "resource": resource11['name'],
160
                    "quantity": 1
161
                },
162
                {
163
                    "holder": user.uuid,
164
                    "source": "system",
165
                    "resource": resource12['name'],
166
                    "quantity": 100
167
                }]}
168

    
169
        post_data = json.dumps(commission_request)
170
        r = client.post(u('commissions'), post_data,
171
                        content_type='application/json', **s1_headers)
172
        self.assertEqual(r.status_code, 201)
173
        body = json.loads(r.content)
174
        serial = body['serial']
175
        self.assertEqual(serial, 1)
176

    
177
        post_data = json.dumps(commission_request)
178
        r = client.post(u('commissions'), post_data,
179
                        content_type='application/json', **s1_headers)
180
        self.assertEqual(r.status_code, 201)
181
        body = json.loads(r.content)
182
        self.assertEqual(body['serial'], 2)
183

    
184
        post_data = json.dumps(commission_request)
185
        r = client.post(u('commissions'), post_data,
186
                        content_type='application/json', **s1_headers)
187
        self.assertEqual(r.status_code, 201)
188
        body = json.loads(r.content)
189
        self.assertEqual(body['serial'], 3)
190

    
191
        r = client.get(u('commissions'), **s1_headers)
192
        self.assertEqual(r.status_code, 200)
193
        body = json.loads(r.content)
194
        self.assertEqual(body, [1, 2, 3])
195

    
196
        r = client.get(u('commissions/' + str(serial)), **s1_headers)
197
        self.assertEqual(r.status_code, 200)
198
        body = json.loads(r.content)
199
        self.assertEqual(body['serial'], serial)
200
        assertIn('issue_time', body)
201
        provisions = sorted(body['provisions'], key=lambda p: p['resource'])
202
        self.assertEqual(provisions, commission_request['provisions'])
203
        self.assertEqual(body['name'], commission_request['name'])
204

    
205
        r = client.get(u('service_quotas?user=' + user.uuid), **s1_headers)
206
        self.assertEqual(r.status_code, 200)
207
        body = json.loads(r.content)
208
        user_quota = body[user.uuid]
209
        system_quota = user_quota['system']
210
        r11 = system_quota[resource11['name']]
211
        self.assertEqual(r11['usage'], 3)
212
        self.assertEqual(r11['pending'], 3)
213

    
214
        # resolve pending commissions
215
        resolve_data = {
216
            "accept": [1, 3],
217
            "reject": [2, 3, 4],
218
        }
219
        post_data = json.dumps(resolve_data)
220

    
221
        r = client.post(u('commissions/action'), post_data,
222
                        content_type='application/json', **s1_headers)
223
        self.assertEqual(r.status_code, 200)
224
        body = json.loads(r.content)
225
        self.assertEqual(body['accepted'], [1])
226
        self.assertEqual(body['rejected'], [2])
227
        failed = body['failed']
228
        self.assertEqual(len(failed), 2)
229

    
230
        r = client.get(u('commissions/' + str(serial)), **s1_headers)
231
        self.assertEqual(r.status_code, 404)
232

    
233
        # auto accept
234
        commission_request = {
235
            "auto_accept": True,
236
            "name": "my commission",
237
            "provisions": [
238
                {
239
                    "holder": user.uuid,
240
                    "source": "system",
241
                    "resource": resource11['name'],
242
                    "quantity": 1
243
                },
244
                {
245
                    "holder": user.uuid,
246
                    "source": "system",
247
                    "resource": resource12['name'],
248
                    "quantity": 100
249
                }]}
250

    
251
        post_data = json.dumps(commission_request)
252
        r = client.post(u('commissions'), post_data,
253
                        content_type='application/json', **s1_headers)
254
        self.assertEqual(r.status_code, 201)
255
        body = json.loads(r.content)
256
        serial = body['serial']
257
        self.assertEqual(serial, 4)
258

    
259
        r = client.get(u('commissions/' + str(serial)), **s1_headers)
260
        self.assertEqual(r.status_code, 404)
261

    
262
        # malformed
263
        commission_request = {
264
            "auto_accept": True,
265
            "name": "my commission",
266
            "provisions": [
267
                {
268
                    "holder": user.uuid,
269
                    "source": "system",
270
                    "resource": resource11['name'],
271
                }
272
            ]}
273

    
274
        post_data = json.dumps(commission_request)
275
        r = client.post(u('commissions'), post_data,
276
                        content_type='application/json', **s1_headers)
277
        self.assertEqual(r.status_code, 400)
278

    
279
        commission_request = {
280
            "auto_accept": True,
281
            "name": "my commission",
282
            "provisions": "dummy"}
283

    
284
        post_data = json.dumps(commission_request)
285
        r = client.post(u('commissions'), post_data,
286
                        content_type='application/json', **s1_headers)
287
        self.assertEqual(r.status_code, 400)
288

    
289
        r = client.post(u('commissions'), commission_request,
290
                        content_type='application/json', **s1_headers)
291
        self.assertEqual(r.status_code, 400)
292

    
293
        # no holding
294
        commission_request = {
295
            "auto_accept": True,
296
            "name": "my commission",
297
            "provisions": [
298
                {
299
                    "holder": user.uuid,
300
                    "source": "system",
301
                    "resource": "non existent",
302
                    "quantity": 1
303
                },
304
                {
305
                    "holder": user.uuid,
306
                    "source": "system",
307
                    "resource": resource12['name'],
308
                    "quantity": 100
309
                }]}
310

    
311
        post_data = json.dumps(commission_request)
312
        r = client.post(u('commissions'), post_data,
313
                        content_type='application/json', **s1_headers)
314
        self.assertEqual(r.status_code, 404)
315

    
316
        # release
317
        commission_request = {
318
            "provisions": [
319
                {
320
                    "holder": user.uuid,
321
                    "source": "system",
322
                    "resource": resource11['name'],
323
                    "quantity": -1
324
                }
325
            ]}
326

    
327
        post_data = json.dumps(commission_request)
328
        r = client.post(u('commissions'), post_data,
329
                        content_type='application/json', **s1_headers)
330
        self.assertEqual(r.status_code, 201)
331
        body = json.loads(r.content)
332
        serial = body['serial']
333

    
334
        accept_data = {'accept': ""}
335
        post_data = json.dumps(accept_data)
336
        r = client.post(u('commissions/' + str(serial) + '/action'), post_data,
337
                        content_type='application/json', **s1_headers)
338
        self.assertEqual(r.status_code, 200)
339

    
340
        reject_data = {'reject': ""}
341
        post_data = json.dumps(accept_data)
342
        r = client.post(u('commissions/' + str(serial) + '/action'), post_data,
343
                        content_type='application/json', **s1_headers)
344
        self.assertEqual(r.status_code, 404)
345

    
346
        # force
347
        commission_request = {
348
            "force": True,
349
            "provisions": [
350
                {
351
                    "holder": user.uuid,
352
                    "source": "system",
353
                    "resource": resource11['name'],
354
                    "quantity": 100
355
                }]}
356

    
357
        post_data = json.dumps(commission_request)
358
        r = client.post(u('commissions'), post_data,
359
                        content_type='application/json', **s1_headers)
360
        self.assertEqual(r.status_code, 201)
361

    
362
        commission_request = {
363
            "force": True,
364
            "provisions": [
365
                {
366
                    "holder": user.uuid,
367
                    "source": "system",
368
                    "resource": resource11['name'],
369
                    "quantity": -200
370
                }]}
371

    
372
        post_data = json.dumps(commission_request)
373
        r = client.post(u('commissions'), post_data,
374
                        content_type='application/json', **s1_headers)
375
        self.assertEqual(r.status_code, 413)
376

    
377
        r = client.get(u('quotas'), **headers)
378
        self.assertEqual(r.status_code, 200)
379
        body = json.loads(r.content)
380
        system_quota = body['system']
381
        r11 = system_quota[resource11['name']]
382
        self.assertEqual(r11['usage'], 102)
383
        self.assertEqual(r11['pending'], 101)
384

    
385
        # Bad Request
386
        r = client.head(u('commissions'))
387
        self.assertEqual(r.status_code, 405)
388
        self.assertTrue('Allow' in r)
389

    
390

    
391
class TokensApiTest(TestCase):
392
    def setUp(self):
393
        backend = activation_backends.get_backend()
394

    
395
        self.user1 = AstakosUser.objects.create(
396
            email='test1', email_verified=True, moderated=True,
397
            is_rejected=False)
398
        backend.activate_user(self.user1)
399
        assert self.user1.is_active is True
400

    
401
        self.user2 = AstakosUser.objects.create(
402
            email='test2', email_verified=True, moderated=True,
403
            is_rejected=False)
404
        backend.activate_user(self.user2)
405
        assert self.user2.is_active is True
406

    
407
        c1 = Component(name='component1', url='http://localhost/component1')
408
        c1.save()
409
        s1 = Service(component=c1, type='type1', name='service1')
410
        s1.save()
411
        e1 = Endpoint(service=s1)
412
        e1.save()
413
        e1.data.create(key='versionId', value='v1.0')
414
        e1.data.create(key='publicURL', value='http://localhost:8000/s1/v1.0')
415

    
416
        s2 = Service(component=c1, type='type2', name='service2')
417
        s2.save()
418
        e2 = Endpoint(service=s2)
419
        e2.save()
420
        e2.data.create(key='versionId', value='v1.0')
421
        e2.data.create(key='publicURL', value='http://localhost:8000/s2/v1.0')
422

    
423
        c2 = Component(name='component2', url='http://localhost/component2')
424
        c2.save()
425
        s3 = Service(component=c2, type='type3', name='service3')
426
        s3.save()
427
        e3 = Endpoint(service=s3)
428
        e3.save()
429
        e3.data.create(key='versionId', value='v2.0')
430
        e3.data.create(key='publicURL', value='http://localhost:8000/s3/v2.0')
431

    
432
    def test_authenticate(self):
433
        client = Client()
434
        url = reverse('astakos.api.tokens.authenticate')
435

    
436
        # Check not allowed method
437
        r = client.get(url, post_data={})
438
        self.assertEqual(r.status_code, 405)
439
        self.assertTrue('Allow' in r)
440
        self.assertEqual(r['Allow'], 'POST')
441

    
442
        # check public mode
443
        r = client.post(url, CONTENT_LENGTH=0)
444
        self.assertEqual(r.status_code, 200)
445
        self.assertTrue(r['Content-Type'].startswith('application/json'))
446
        try:
447
            body = json.loads(r.content)
448
        except Exception, e:
449
            self.fail(e)
450
        self.assertTrue('token' not in body.get('access'))
451
        self.assertTrue('user' not in body.get('access'))
452
        self.assertTrue('serviceCatalog' in body.get('access'))
453

    
454
        # Check unsupported xml input
455
        post_data = """
456
            <?xml version="1.0" encoding="UTF-8"?>
457
                <auth xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
458
                 xmlns="http://docs.openstack.org/identity/api/v2.0"
459
                 tenantName="%s">
460
                  <passwordCredentials username="%s" password="%s"/>
461
                </auth>""" % (self.user1.uuid, self.user1.uuid,
462
                              self.user1.auth_token)
463
        r = client.post(url, post_data, content_type='application/xml')
464
        self.assertEqual(r.status_code, 400)
465
        body = json.loads(r.content)
466
        self.assertEqual(body['badRequest']['message'],
467
                         "Unsupported Content-type: 'application/xml'")
468

    
469
        # Check malformed request: missing password
470
        post_data = """{"auth":{"passwordCredentials":{"username":"%s"},
471
                                "tenantName":"%s"}}""" % (
472
            self.user1.uuid, self.user1.uuid)
473
        r = client.post(url, post_data, content_type='application/json')
474
        self.assertEqual(r.status_code, 400)
475
        body = json.loads(r.content)
476
        self.assertTrue(body['badRequest']['message'].
477
                        startswith('Malformed request'))
478

    
479
        # Check malformed request: missing username
480
        post_data = """{"auth":{"passwordCredentials":{"password":"%s"},
481
                                "tenantName":"%s"}}""" % (
482
            self.user1.auth_token, self.user1.uuid)
483
        r = client.post(url, post_data, content_type='application/json')
484
        self.assertEqual(r.status_code, 400)
485
        body = json.loads(r.content)
486
        self.assertTrue(body['badRequest']['message'].
487
                        startswith('Malformed request'))
488

    
489
        # Check invalid pass
490
        post_data = """{"auth":{"passwordCredentials":{"username":"%s",
491
                                                       "password":"%s"},
492
                                "tenantName":"%s"}}""" % (
493
            self.user1.uuid, '', self.user1.uuid)
494
        r = client.post(url, post_data, content_type='application/json')
495
        self.assertEqual(r.status_code, 401)
496
        body = json.loads(r.content)
497
        self.assertEqual(body['unauthorized']['message'],
498
                         'Invalid token')
499

    
500
        # Check inconsistent pass
501
        post_data = """{"auth":{"passwordCredentials":{"username":"%s",
502
                                                       "password":"%s"},
503
                                "tenantName":"%s"}}""" % (
504
            self.user1.uuid, self.user2.auth_token, self.user2.uuid)
505
        r = client.post(url, post_data, content_type='application/json')
506
        self.assertEqual(r.status_code, 401)
507
        body = json.loads(r.content)
508
        self.assertEqual(body['unauthorized']['message'],
509
                         'Invalid credentials')
510

    
511
        # Check invalid json data
512
        r = client.post(url, "not json", content_type='application/json')
513
        self.assertEqual(r.status_code, 400)
514
        body = json.loads(r.content)
515
        self.assertEqual(body['badRequest']['message'], 'Invalid JSON data')
516

    
517
        # Check auth with token
518
        post_data = """{"auth":{"token": {"id":"%s"},
519
                        "tenantName":"%s"}}""" % (
520
            self.user1.auth_token, self.user1.uuid)
521
        r = client.post(url, post_data, content_type='application/json')
522
        self.assertEqual(r.status_code, 200)
523
        self.assertTrue(r['Content-Type'].startswith('application/json'))
524
        try:
525
            body = json.loads(r.content)
526
        except Exception, e:
527
            self.fail(e)
528

    
529
        # Check malformed request: missing token
530
        post_data = """{"auth":{"auth_token":{"id":"%s"},
531
                                "tenantName":"%s"}}""" % (
532
            self.user1.auth_token, self.user1.uuid)
533
        r = client.post(url, post_data, content_type='application/json')
534
        self.assertEqual(r.status_code, 400)
535
        body = json.loads(r.content)
536
        self.assertTrue(body['badRequest']['message'].
537
                        startswith('Malformed request'))
538

    
539
        # Check bad request: inconsistent tenant
540
        post_data = """{"auth":{"token":{"id":"%s"},
541
                                "tenantName":"%s"}}""" % (
542
            self.user1.auth_token, self.user2.uuid)
543
        r = client.post(url, post_data, content_type='application/json')
544
        self.assertEqual(r.status_code, 400)
545
        body = json.loads(r.content)
546
        self.assertEqual(body['badRequest']['message'],
547
                         'Not conforming tenantName')
548

    
549
        # Check bad request: inconsistent tenant
550
        post_data = """{"auth":{"token":{"id":"%s"},
551
                                "tenantName":""}}""" % (
552
            self.user1.auth_token)
553
        r = client.post(url, post_data, content_type='application/json')
554
        self.assertEqual(r.status_code, 200)
555

    
556
        # Check successful json response
557
        post_data = """{"auth":{"passwordCredentials":{"username":"%s",
558
                                                       "password":"%s"},
559
                                "tenantName":"%s"}}""" % (
560
            self.user1.uuid, self.user1.auth_token, self.user1.uuid)
561
        r = client.post(url, post_data, content_type='application/json')
562
        self.assertEqual(r.status_code, 200)
563
        self.assertTrue(r['Content-Type'].startswith('application/json'))
564
        try:
565
            body = json.loads(r.content)
566
        except Exception, e:
567
            self.fail(e)
568

    
569
        try:
570
            token = body['access']['token']['id']
571
            user = body['access']['user']['id']
572
            service_catalog = body['access']['serviceCatalog']
573
        except KeyError:
574
            self.fail('Invalid response')
575

    
576
        self.assertEqual(token, self.user1.auth_token)
577
        self.assertEqual(user, self.user1.uuid)
578
        self.assertEqual(len(service_catalog), 3)
579

    
580
        # Check successful xml response
581
        headers = {'HTTP_ACCEPT': 'application/xml'}
582
        post_data = """{"auth":{"passwordCredentials":{"username":"%s",
583
                                                       "password":"%s"},
584
                                "tenantName":"%s"}}""" % (
585
            self.user1.uuid, self.user1.auth_token, self.user1.uuid)
586
        r = client.post(url, post_data, content_type='application/json',
587
                        **headers)
588
        self.assertEqual(r.status_code, 200)
589
        self.assertTrue(r['Content-Type'].startswith('application/xml'))
590
#        try:
591
#            body = minidom.parseString(r.content)
592
#        except Exception, e:
593
#            self.fail(e)
594

    
595

    
596
class UserCatalogsTest(TestCase):
597
    def test_get_uuid_displayname_catalogs(self):
598
        self.user = AstakosUser.objects.create(
599
            email='test1', email_verified=True, moderated=True,
600
            is_rejected=False)
601

    
602
        client = Client()
603
        url = reverse('astakos.api.user.get_uuid_displayname_catalogs')
604
        d = dict(uuids=[self.user.uuid], displaynames=[self.user.username])
605

    
606
        # assert Unauthorized: missing authentication token
607
        r = client.post(url,
608
                        data=json.dumps(d),
609
                        content_type='application/json')
610
        self.assertEqual(r.status_code, 401)
611

    
612
        # assert Unauthorized: invalid authentication token
613
        r = client.post(url,
614
                        data=json.dumps(d),
615
                        content_type='application/json',
616
                        HTTP_X_AUTH_TOKEN='1234')
617
        self.assertEqual(r.status_code, 401)
618

    
619
        # assert Unauthorized: inactive token holder
620
        r = client.post(url,
621
                        data=json.dumps(d),
622
                        content_type='application/json',
623
                        HTTP_X_AUTH_TOKEN=self.user.auth_token)
624
        self.assertEqual(r.status_code, 401)
625

    
626
        backend = activation_backends.get_backend()
627
        backend.activate_user(self.user)
628
        assert self.user.is_active is True
629

    
630
        r = client.post(url,
631
                        data=json.dumps(d),
632
                        content_type='application/json',
633
                        HTTP_X_AUTH_TOKEN=self.user.auth_token)
634
        self.assertEqual(r.status_code, 200)
635
        try:
636
            data = json.loads(r.content)
637
        except:
638
            self.fail('Response body should be json formatted')
639
        else:
640
            if not isinstance(data, dict):
641
                self.fail('Response body should be json formatted dictionary')
642

    
643
            self.assertTrue('uuid_catalog' in data)
644
            self.assertEqual(data['uuid_catalog'],
645
                             {self.user.uuid: self.user.username})
646

    
647
            self.assertTrue('displayname_catalog' in data)
648
            self.assertEqual(data['displayname_catalog'],
649
                             {self.user.username: self.user.uuid})
650

    
651
        # assert Unauthorized: expired token
652
        self.user.auth_token_expires = date.today() - timedelta(1)
653
        self.user.save()
654

    
655
        r = client.post(url,
656
                        data=json.dumps(d),
657
                        content_type='application/json',
658
                        HTTP_X_AUTH_TOKEN=self.user.auth_token)
659
        self.assertEqual(r.status_code, 401)
660

    
661
        # assert Unauthorized: expired token
662
        self.user.auth_token_expires = date.today() + timedelta(1)
663
        self.user.save()
664

    
665
        # assert badRequest
666
        r = client.post(url,
667
                        data=json.dumps(str(d)),
668
                        content_type='application/json',
669
                        HTTP_X_AUTH_TOKEN=self.user.auth_token)
670
        self.assertEqual(r.status_code, 400)
671

    
672

    
673
class WrongPathAPITest(TestCase):
674
    def test_catch_wrong_account_paths(self, *args):
675
        path = get_service_path(astakos_services, 'account', 'v1.0')
676
        path = join_urls(BASE_HOST, path, 'nonexistent')
677
        response = self.client.get(path)
678
        self.assertEqual(response.status_code, 400)
679
        try:
680
            error = json.loads(response.content)
681
        except ValueError:
682
            self.assertTrue(False)
683

    
684
    def test_catch_wrong_identity_paths(self, *args):
685
        path = get_service_path(astakos_services, 'identity', 'v2.0')
686
        path = join_urls(BASE_HOST, path, 'nonexistent')
687
        response = self.client.get(path)
688
        self.assertEqual(response.status_code, 400)
689
        try:
690
            json.loads(response.content)
691
        except ValueError:
692
            self.assertTrue(False)