Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / tests / api.py @ 8aaf4f0d

History | View | Annotate | Download (23.9 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 xml.dom import minidom
43

    
44
import json
45

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

    
50

    
51
class QuotaAPITest(TestCase):
52
    def test_0(self):
53
        client = Client()
54

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

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

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

    
88
        resource_names = [r['name'] for r in
89
                          [resource11, resource12, resource21]]
90

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

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

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

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

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

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

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

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

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

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

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

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

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

    
194
        r = client.get(u('commissions/' + str(serial)), **s1_headers)
195
        self.assertEqual(r.status_code, 200)
196
        body = json.loads(r.content)
197
        self.assertEqual(body['serial'], serial)
198
        assertIn('issue_time', body)
199
        self.assertEqual(body['provisions'], commission_request['provisions'])
200
        self.assertEqual(body['name'], commission_request['name'])
201

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

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

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

    
227
        r = client.get(u('commissions/' + str(serial)), **s1_headers)
228
        self.assertEqual(r.status_code, 404)
229

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

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

    
256
        r = client.get(u('commissions/' + str(serial)), **s1_headers)
257
        self.assertEqual(r.status_code, 404)
258

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

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

    
276
        commission_request = {
277
            "auto_accept": True,
278
            "name": "my commission",
279
            "provisions": "dummy"}
280

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

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

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

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

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

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

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

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

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

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

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

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

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

    
382

    
383
class TokensApiTest(TestCase):
384
    def setUp(self):
385
        backend = activation_backends.get_backend()
386

    
387
        self.user1 = AstakosUser.objects.create(
388
            email='test1', email_verified=True, moderated=True,
389
            is_rejected=False)
390
        backend.activate_user(self.user1)
391
        assert self.user1.is_active is True
392

    
393
        self.user2 = AstakosUser.objects.create(
394
            email='test2', email_verified=True, moderated=True,
395
            is_rejected=False)
396
        backend.activate_user(self.user2)
397
        assert self.user2.is_active is True
398

    
399
        c1 = Component(name='component1', url='http://localhost/component1')
400
        c1.save()
401
        s1 = Service(component=c1, type='type1', name='service1')
402
        s1.save()
403
        e1 = Endpoint(service=s1)
404
        e1.save()
405
        e1.data.create(key='versionId', value='v1.0')
406
        e1.data.create(key='publicURL', value='http://localhost:8000/s1/v1.0')
407

    
408
        s2 = Service(component=c1, type='type2', name='service2')
409
        s2.save()
410
        e2 = Endpoint(service=s2)
411
        e2.save()
412
        e2.data.create(key='versionId', value='v1.0')
413
        e2.data.create(key='publicURL', value='http://localhost:8000/s2/v1.0')
414

    
415
        c2 = Component(name='component2', url='http://localhost/component2')
416
        c2.save()
417
        s3 = Service(component=c2, type='type3', name='service3')
418
        s3.save()
419
        e3 = Endpoint(service=s3)
420
        e3.save()
421
        e3.data.create(key='versionId', value='v2.0')
422
        e3.data.create(key='publicURL', value='http://localhost:8000/s3/v2.0')
423

    
424
    def test_authenticate(self):
425
        client = Client()
426

    
427
        # Check not allowed method
428
        url = reverse('astakos.api.tokens.authenticate')
429
        r = client.get(url, post_data={})
430
        self.assertEqual(r.status_code, 400)
431

    
432
        # check public mode
433
        r = client.post(url, CONTENT_LENGTH=0)
434
        self.assertEqual(r.status_code, 200)
435
        self.assertTrue(r['Content-Type'].startswith('application/json'))
436
        try:
437
            body = json.loads(r.content)
438
        except Exception, e:
439
            self.fail(e)
440
        self.assertTrue('token' not in body.get('access'))
441
        self.assertTrue('user' not in body.get('access'))
442
        self.assertTrue('serviceCatalog' in body.get('access'))
443

    
444
        # Check unsupported xml input
445
        url = reverse('astakos.api.tokens.authenticate')
446
        post_data = """
447
            <?xml version="1.0" encoding="UTF-8"?>
448
                <auth xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
449
                 xmlns="http://docs.openstack.org/identity/api/v2.0"
450
                 tenantName="%s">
451
                  <passwordCredentials username="%s" password="%s"/>
452
                </auth>""" % (self.user1.uuid, self.user1.uuid,
453
                              self.user1.auth_token)
454
        r = client.post(url, post_data, content_type='application/xml')
455
        self.assertEqual(r.status_code, 400)
456
        body = json.loads(r.content)
457
        self.assertEqual(body['badRequest']['message'],
458
                         "Unsupported Content-type: 'application/xml'")
459

    
460
        # Check malformed request: missing password
461
        url = reverse('astakos.api.tokens.authenticate')
462
        post_data = """{"auth":{"passwordCredentials":{"username":"%s"},
463
                                "tenantName":"%s"}}""" % (
464
            self.user1.uuid, self.user1.uuid)
465
        r = client.post(url, post_data, content_type='application/json')
466
        self.assertEqual(r.status_code, 400)
467
        body = json.loads(r.content)
468
        self.assertTrue(body['badRequest']['message'].
469
                        startswith('Malformed request'))
470

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

    
482
        # Check invalid pass
483
        url = reverse('astakos.api.tokens.authenticate')
484
        post_data = """{"auth":{"passwordCredentials":{"username":"%s",
485
                                                       "password":"%s"},
486
                                "tenantName":"%s"}}""" % (
487
            self.user1.uuid, '', self.user1.uuid)
488
        r = client.post(url, post_data, content_type='application/json')
489
        self.assertEqual(r.status_code, 401)
490
        body = json.loads(r.content)
491
        self.assertEqual(body['unauthorized']['message'],
492
                         'Invalid token')
493

    
494
        # Check inconsistent pass
495
        url = reverse('astakos.api.tokens.authenticate')
496
        post_data = """{"auth":{"passwordCredentials":{"username":"%s",
497
                                                       "password":"%s"},
498
                                "tenantName":"%s"}}""" % (
499
            self.user1.uuid, self.user2.auth_token, self.user2.uuid)
500
        r = client.post(url, post_data, content_type='application/json')
501
        self.assertEqual(r.status_code, 401)
502
        body = json.loads(r.content)
503
        self.assertEqual(body['unauthorized']['message'],
504
                         'Invalid credentials')
505

    
506
        # Check invalid json data
507
        url = reverse('astakos.api.tokens.authenticate')
508
        r = client.post(url, "not json", content_type='application/json')
509
        self.assertEqual(r.status_code, 400)
510
        body = json.loads(r.content)
511
        self.assertEqual(body['badRequest']['message'], 'Invalid JSON data')
512

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

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

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

    
548
        # Check bad request: inconsistent tenant
549
        url = reverse('astakos.api.tokens.authenticate')
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
        url = reverse('astakos.api.tokens.authenticate')
558
        post_data = """{"auth":{"passwordCredentials":{"username":"%s",
559
                                                       "password":"%s"},
560
                                "tenantName":"%s"}}""" % (
561
            self.user1.uuid, self.user1.auth_token, self.user1.uuid)
562
        r = client.post(url, post_data, content_type='application/json')
563
        self.assertEqual(r.status_code, 200)
564
        self.assertTrue(r['Content-Type'].startswith('application/json'))
565
        try:
566
            body = json.loads(r.content)
567
        except Exception, e:
568
            self.fail(e)
569

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

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

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

    
597

    
598
class WrongPathAPITest(TestCase):
599
    def test_catch_wrong_api_paths(self, *args):
600
        path = get_service_path(astakos_services, 'account', 'v1.0')
601
        path = join_urls(BASE_HOST, path, 'nonexistent')
602
        response = self.client.get(path)
603
        self.assertEqual(response.status_code, 400)
604
        try:
605
            error = json.loads(response.content)
606
        except ValueError:
607
            self.assertTrue(False)
608

    
609
    def test_catch_wrong_api_paths(self, *args):
610
        path = get_service_path(astakos_services, 'identity', 'v2.0')
611
        path = join_urls(BASE_HOST, path, 'nonexistent')
612
        response = self.client.get(path)
613
        self.assertEqual(response.status_code, 400)
614
        try:
615
            error = json.loads(response.content)
616
        except ValueError:
617
            self.assertTrue(False)