summaryrefslogtreecommitdiffstats
path: root/utils/test/testapi/opnfv_testapi/resources/scenario_handlers.py
blob: bd06400b4f083958c13b271bc9e53975eb22fdb1 (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
import functools

from opnfv_testapi.common import message
from opnfv_testapi.common import raises
from opnfv_testapi.resources import handlers
import opnfv_testapi.resources.scenario_models as models
from opnfv_testapi.tornado_swagger import swagger


class GenericScenarioHandler(handlers.GenericApiHandler):
    def __init__(self, application, request, **kwargs):
        super(GenericScenarioHandler, self).__init__(application,
                                                     request,
                                                     **kwargs)
        self.table = self.db_scenarios
        self.table_cls = models.Scenario

    def set_query(self, locators):
        query = dict()
        elem_query = dict()
        for k, v in locators.iteritems():
            if k == 'scenario':
                query['name'] = v
            elif k == 'installer':
                elem_query["installer"] = v
            elif k == 'version':
                elem_query["versions.version"] = v
            elif k == 'project':
                elem_query["versions.projects.project"] = v
            else:
                query[k] = v
        if elem_query:
            query['installers'] = {'$elemMatch': elem_query}
        return query


class ScenariosCLHandler(GenericScenarioHandler):
    @swagger.operation(nickname="queryScenarios")
    def get(self):
        """
            @description: Retrieve scenario(s).
            @notes: Retrieve scenario(s)
                Available filters for this request are :
                 - name : scenario name

                GET /scenarios?name=scenario_1
            @param name: scenario name
            @type name: L{string}
            @in name: query
            @required name: False
            @param installer: installer type
            @type installer: L{string}
            @in installer: query
            @required installer: False
            @param version: version
            @type version: L{string}
            @in version: query
            @required version: False
            @param project: project name
            @type project: L{string}
            @in project: query
            @required project: False
            @return 200: all scenarios satisfy queries,
                         empty list if no scenario is found
            @rtype: L{Scenarios}
        """

        def _set_query():
            query = dict()
            elem_query = dict()
            for k in self.request.query_arguments.keys():
                v = self.get_query_argument(k)
                if k == 'installer':
                    elem_query["installer"] = v
                elif k == 'version':
                    elem_query["versions.version"] = v
                elif k == 'project':
                    elem_query["versions.projects.project"] = v
                else:
                    query[k] = v
            if elem_query:
                query['installers'] = {'$elemMatch': elem_query}
            return query

        self._list(query=_set_query())

    @swagger.operation(nickname="createScenario")
    def post(self):
        """
            @description: create a new scenario by name
            @param body: scenario to be created
            @type body: L{ScenarioCreateRequest}
            @in body: body
            @rtype: L{CreateResponse}
            @return 200: scenario is created.
            @raise 403: scenario already exists
            @raise 400:  body or name not provided
        """
        def query():
            return {'name': self.json_args.get('name')}
        miss_fields = ['name']
        self._create(miss_fields=miss_fields, query=query)


class ScenarioGURHandler(GenericScenarioHandler):
    @swagger.operation(nickname='getScenarioByName')
    def get(self, name):
        """
            @description: get a single scenario by name
            @rtype: L{Scenario}
            @return 200: scenario exist
            @raise 404: scenario not exist
        """
        self._get_one(query={'name': name})
        pass

    def put(self, name):
        pass

    @swagger.operation(nickname="deleteScenarioByName")
    def delete(self, name):
        """
        @description: delete a scenario by name
        @return 200: delete success
        @raise 404: scenario not exist:
        """
        self._delete(query={'name': name})


class ScenarioUpdater(object):
    def __init__(self, data, body=None,
                 installer=None, version=None, project=None):
        self.data = data
        self.body = body
        self.installer = installer
        self.version = version
        self.project = project

    def update(self, item, action):
        updates = {
            ('scores', 'post'): self._update_requests_add_score,
            ('trust_indicators', 'post'): self._update_requests_add_ti,
            ('customs', 'post'): self._update_requests_add_customs,
            ('customs', 'put'): self._update_requests_update_customs,
            ('customs', 'delete'): self._update_requests_delete_customs,
            ('projects', 'post'): self._update_requests_add_projects,
            ('projects', 'put'): self._update_requests_update_projects,
            ('projects', 'delete'): self._update_requests_delete_projects,
            ('owner', 'put'): self._update_requests_change_owner,
        }
        updates[(item, action)](self.data)

        return self.data.format()

    def iter_installers(xstep):
        @functools.wraps(xstep)
        def magic(self, data):
            [xstep(self, installer)
             for installer in self._filter_installers(data.installers)]
        return magic

    def iter_versions(xstep):
        @functools.wraps(xstep)
        def magic(self, installer):
            [xstep(self, version)
             for version in (self._filter_versions(installer.versions))]
        return magic

    def iter_projects(xstep):
        @functools.wraps(xstep)
        def magic(self, version):
            [xstep(self, project)
             for project in (self._filter_projects(version.projects))]
        return magic

    @iter_installers
    @iter_versions
    @iter_projects
    def _update_requests_add_score(self, project):
        project.scores.append(
            models.ScenarioScore.from_dict(self.body))

    @iter_installers
    @iter_versions
    @iter_projects
    def _update_requests_add_ti(self, project):
        project.trust_indicators.append(
            models.ScenarioTI.from_dict(self.body))

    @iter_installers
    @iter_versions
    @iter_projects
    def _update_requests_add_customs(self, project):
        project.customs = list(set(project.customs + self.body))

    @iter_installers
    @iter_versions
    @iter_projects
    def _update_requests_update_customs(self, project):
        project.customs = list(set(self.body))

    @iter_installers
    @iter_versions
    @iter_projects
    def _update_requests_delete_customs(self, project):
        project.customs = filter(
            lambda f: f not in self.body,
            project.customs)

    @iter_installers
    @iter_versions
    def _update_requests_add_projects(self, version):
        exists = list()
        malformat = list()
        for n in self.body:
            try:
                f_n = models.ScenarioProject.from_dict_with_raise(n)
                if not any(o.project == f_n.project for o in version.projects):
                    version.projects.append(f_n)
                else:
                    exists.append(n['project'])
            except Exception as e:
                malformat.append(e.message)
        if malformat:
            raises.BadRequest(message.bad_format(malformat))
        elif exists:
            raises.Conflict(message.exist('projects', exists))

    @iter_installers
    @iter_versions
    def _update_requests_update_projects(self, version):
        exists = list()
        malformat = list()
        projects = list()
        for n in self.body:
            try:
                f_n = models.ScenarioProject.from_dict_with_raise(n)
                if not any(o.project == f_n.project for o in projects):
                    projects.append(models.ScenarioProject.from_dict(n))
                else:
                    exists.append(n['project'])
            except:
                malformat.append(n)
        if malformat:
            raises.BadRequest(message.bad_format(malformat))
        elif exists:
            raises.Forbidden(message.exist('projects', exists))
        version.projects = projects

    @iter_installers
    @iter_versions
    def _update_requests_delete_projects(self, version):
        version.projects = self._remove_projects(version.projects)

    @iter_installers
    @iter_versions
    def _update_requests_change_owner(self, version):
        version.owner = self.body

    def _filter_installers(self, installers):
        return self._filter('installer', installers)

    def _filter_versions(self, versions):
        return self._filter('version', versions)

    def _filter_projects(self, projects):
        return self._filter('project', projects)

    def _remove_projects(self, projects):
        return self._remove('project', projects)

    def _filter(self, item, items):
        return filter(
            lambda f: getattr(f, item) == getattr(self, item),
            items)

    def _remove(self, field, fields):
        return filter(
            lambda f: getattr(f, field) not in self.body,
            fields)


class GenericScenarioUpdateHandler(GenericScenarioHandler):
    def __init__(self, application, request, **kwargs):
        super(GenericScenarioUpdateHandler, self).__init__(application,
                                                           request,
                                                           **kwargs)
        self.installer = None
        self.version = None
        self.project = None
        self.item = None
        self.action = None

    def do_update(self, item, action, locators):
        self.item = item
        self.action = action
        for k, v in locators.iteritems():
            if not v:
                v = self.get_query_argument(k)
                setattr(self, k, v)
                locators[k] = v
        self.pure_update(query=self.set_query(locators=locators))

    def _update_requests(self, data):
        return ScenarioUpdater(data,
                               self.json_args,
                               self.installer,
                               self.version,
                               self.project).update(self.item, self.action)


class ScenarioScoresHandler(GenericScenarioUpdateHandler):
    @swagger.operation(nickname="addScoreRecord")
    def post(self, scenario):
        """
        @description: add a new score record
        @notes: add a new score record to a project
            POST /api/v1/scenarios/<scenario_name>/scores? \
                installer=<installer_name>& \
                version=<version_name>& \
                project=<project_name>
        @param body: score to be added
        @type body: L{ScenarioScore}
        @in body: body
        @param installer: installer type
        @type installer: L{string}
        @in installer: query
        @required installer: True
        @param version: version
        @type version: L{string}
        @in version: query
        @required version: True
        @param project: project name
        @type project: L{string}
        @in project: query
        @required project: True
        @return 200: score is created.
        @raise 404:  scenario/installer/version/project not existed
        """
        self.do_update('scores',
                       'post',
                       locators={'scenario': scenario,
                                 'installer': None,
                                 'version': None,
                                 'project': None})


class ScenarioTIsHandler(GenericScenarioUpdateHandler):
    @swagger.operation(nickname="addTrustIndicatorRecord")
    def post(self, scenario):
        """
        @description: add a new trust indicator record
        @notes: add a new trust indicator record to a project
            POST /api/v1/scenarios/<scenario_name>/trust_indicators? \
                installer=<installer_name>& \
                version=<version_name>& \
                project=<project_name>
        @param body: trust indicator to be added
        @type body: L{ScenarioTI}
        @in body: body
        @param installer: installer type
        @type installer: L{string}
        @in installer: query
        @required installer: True
        @param version: version
        @type version: L{string}
        @in version: query
        @required version: True
        @param project: project name
        @type project: L{string}
        @in project: query
        @required project: True
        @return 200: trust indicator is added.
        @raise 404:  scenario/installer/version/project not existed
        """
        self.do_update('trust_indicators',
                       'post',
                       locators={'scenario': scenario,
                                 'installer': None,
                                 'version': None,
                                 'project': None})


class ScenarioCustomsHandler(GenericScenarioUpdateHandler):
    @swagger.operation(nickname="addCustomizedTestCases")
    def post(self, scenario):
        """
        @description: add customized test cases
        @notes: add several test cases to a project
            POST /api/v1/scenarios/<scenario_name>/customs? \
                installer=<installer_name>& \
                version=<version_name>& \
                project=<project_name>
        @param body: test cases to be added
        @type body: C{list} of L{string}
        @in body: body
        @param installer: installer type
        @type installer: L{string}
        @in installer: query
        @required installer: True
        @param version: version
        @type version: L{string}
        @in version: query
        @required version: True
        @param project: project name
        @type project: L{string}
        @in project: query
        @required project: True
        @return 200: test cases are added.
        @raise 404:  scenario/installer/version/project not existed
        """
        self.do_update('customs',
                       'post',
                       locators={'scenario': scenario,
                                 'installer': None,
                                 'version': None,
                                 'project': None})

    @swagger.operation(nickname="updateCustomizedTestCases")
    def put(self, scenario):
        """
        @description: update customized test cases
        @notes: substitute all the customized test cases
            PUT /api/v1/scenarios/<scenario_name>/customs? \
                installer=<installer_name>& \
                version=<version_name>& \
                project=<project_name>
        @param body: new supported test cases
        @type body: C{list} of L{string}
        @in body: body
        @param installer: installer type
        @type installer: L{string}
        @in installer: query
        @required installer: True
        @param version: version
        @type version: L{string}
        @in version: query
        @required version: True
        @param project: project name
        @type project: L{string}
        @in project: query
        @required project: True
        @return 200: substitute test cases success.
        @raise 404:  scenario/installer/version/project not existed
        """
        self.do_update('customs',
                       'put',
                       locators={'scenario': scenario,
                                 'installer': None,
                                 'version': None,
                                 'project': None})

    @swagger.operation(nickname="deleteCustomizedTestCases")
    def delete(self, scenario):
        """
        @description: delete one or several customized test cases
        @notes: delete one or some customized test cases
            DELETE /api/v1/scenarios/<scenario_name>/customs? \
                installer=<installer_name>& \
                version=<version_name>& \
                project=<project_name>
        @param body: test case(s) to be deleted
        @type body: C{list} of L{string}
        @in body: body
        @param installer: installer type
        @type installer: L{string}
        @in installer: query
        @required installer: True
        @param version: version
        @type version: L{string}
        @in version: query
        @required version: True
        @param project: project name
        @type project: L{string}
        @in project: query
        @required project: True
        @return 200: delete test case(s) success.
        @raise 404:  scenario/installer/version/project not existed
        """
        self.do_update('customs',
                       'delete',
                       locators={'scenario': scenario,
                                 'installer': None,
                                 'version': None,
                                 'project': None})


class ScenarioProjectsHandler(GenericScenarioUpdateHandler):
    @swagger.operation(nickname="addProjectsUnderScenario")
    def post(self, scenario):
        """
        @description: add projects to scenario
        @notes: add one or multiple projects
            POST /api/v1/scenarios/<scenario_name>/projects? \
                installer=<installer_name>& \
                version=<version_name>
        @param body: projects to be added
        @type body: C{list} of L{ScenarioProject}
        @in body: body
        @param installer: installer type
        @type installer: L{string}
        @in installer: query
        @required installer: True
        @param version: version
        @type version: L{string}
        @in version: query
        @required version: True
        @return 200: projects are added.
        @raise 400: bad schema
        @raise 409: conflict, project already exists
        @raise 404:  scenario/installer/version not existed
        """
        self.do_update('projects',
                       'post',
                       locators={'scenario': scenario,
                                 'installer': None,
                                 'version': None})

    @swagger.operation(nickname="updateScenarioProjects")
    def put(self, scenario):
        """
        @description: replace all projects
        @notes: substitute all projects, delete existed ones with new provides
            PUT /api/v1/scenarios/<scenario_name>/projects? \
                installer=<installer_name>& \
                version=<version_name>
        @param body: new projects
        @type body: C{list} of L{ScenarioProject}
        @in body: body
        @param installer: installer type
        @type installer: L{string}
        @in installer: query
        @required installer: True
        @param version: version
        @type version: L{string}
        @in version: query
        @required version: True
        @return 200: replace projects success.
        @raise 400: bad schema
        @raise 404:  scenario/installer/version not existed
        """
        self.do_update('projects',
                       'put',
                       locators={'scenario': scenario,
                                 'installer': None,
                                 'version': None})

    @swagger.operation(nickname="deleteProjectsUnderScenario")
    def delete(self, scenario):
        """
        @description: delete one or multiple projects
        @notes: delete one or multiple projects
            DELETE /api/v1/scenarios/<scenario_name>/projects? \
                installer=<installer_name>& \
                version=<version_name>
        @param body: projects(names) to be deleted
        @type body: C{list} of L{string}
        @in body: body
        @param installer: installer type
        @type installer: L{string}
        @in installer: query
        @required installer: True
        @param version: version
        @type version: L{string}
        @in version: query
        @required version: True
        @return 200: delete project(s) success.
        @raise 404:  scenario/installer/version not existed
        """
        self.do_update('projects',
                       'delete',
                       locators={'scenario': scenario,
                                 'installer': None,
                                 'version': None})


class ScenarioOwnerHandler(GenericScenarioUpdateHandler):
    @swagger.operation(nickname="changeScenarioOwner")
    def put(self, scenario):
        """
        @description: change scenario owner
        @notes: substitute all projects, delete existed ones with new provides
            PUT /api/v1/scenarios/<scenario_name>/owner? \
                installer=<installer_name>& \
                version=<version_name>
        @param body: new owner
        @type body: L{string}
        @in body: body
        @param installer: installer type
        @type installer: L{string}
        @in installer: query
        @required installer: True
        @param version: version
        @type version: L{string}
        @in version: query
        @required version: True
        @return 200: change owner success.
        @raise 404:  scenario/installer/version not existed
        """
        self.do_update('owner',
                       'put',
                       locators={'scenario': scenario,
                                 'installer': None,
                                 'version': None})