Merge "leverage token_check only when posting results"
[releng.git] / utils / test / testapi / opnfv_testapi / tests / unit / resources / test_base.py
1 ##############################################################################
2 # Copyright (c) 2016 ZTE Corporation
3 # feng.xiaowei@zte.com.cn
4 # All rights reserved. This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 # http://www.apache.org/licenses/LICENSE-2.0
8 ##############################################################################
9 import json
10 from os import path
11
12 import mock
13 from tornado import testing
14
15 from opnfv_testapi.resources import models
16 from opnfv_testapi.tests.unit import fake_pymongo
17
18
19 class TestBase(testing.AsyncHTTPTestCase):
20     headers = {'Content-Type': 'application/json; charset=UTF-8'}
21
22     def setUp(self):
23         self._patch_server()
24         self.basePath = ''
25         self.create_res = models.CreateResponse
26         self.get_res = None
27         self.list_res = None
28         self.update_res = None
29         self.req_d = None
30         self.req_e = None
31         self.addCleanup(self._clear)
32         super(TestBase, self).setUp()
33
34     def tearDown(self):
35         self.db_patcher.stop()
36         self.config_patcher.stop()
37
38     def _patch_server(self):
39         import argparse
40         config = path.join(path.dirname(__file__),
41                            '../../../../etc/config.ini')
42         self.config_patcher = mock.patch(
43             'argparse.ArgumentParser.parse_known_args',
44             return_value=(argparse.Namespace(config_file=config), None))
45         self.db_patcher = mock.patch('opnfv_testapi.db.api.DB',
46                                      fake_pymongo)
47         self.config_patcher.start()
48         self.db_patcher.start()
49
50     def get_app(self):
51         from opnfv_testapi.cmd import server
52         return server.make_app()
53
54     def create_d(self, *args):
55         return self.create(self.req_d, *args)
56
57     def create_e(self, *args):
58         return self.create(self.req_e, *args)
59
60     def create(self, req=None, *args):
61         return self.create_help(self.basePath, req, *args)
62
63     def create_help(self, uri, req, *args):
64         return self.post_direct_url(self._update_uri(uri, *args), req)
65
66     def post_direct_url(self, url, req):
67         if req and not isinstance(req, str) and hasattr(req, 'format'):
68             req = req.format()
69         res = self.fetch(url,
70                          method='POST',
71                          body=json.dumps(req),
72                          headers=self.headers)
73
74         return self._get_return(res, self.create_res)
75
76     def get(self, *args):
77         res = self.fetch(self._get_uri(*args),
78                          method='GET',
79                          headers=self.headers)
80
81         def inner():
82             new_args, num = self._get_valid_args(*args)
83             return self.get_res \
84                 if num != self._need_arg_num(self.basePath) else self.list_res
85         return self._get_return(res, inner())
86
87     def query(self, query):
88         res = self.fetch(self._get_query_uri(query),
89                          method='GET',
90                          headers=self.headers)
91         return self._get_return(res, self.list_res)
92
93     def update_direct_url(self, url, new=None):
94         if new and hasattr(new, 'format'):
95             new = new.format()
96         res = self.fetch(url,
97                          method='PUT',
98                          body=json.dumps(new),
99                          headers=self.headers)
100         return self._get_return(res, self.update_res)
101
102     def update(self, new=None, *args):
103         return self.update_direct_url(self._get_uri(*args), new)
104
105     def delete_direct_url(self, url, body):
106         if body:
107             res = self.fetch(url,
108                              method='DELETE',
109                              body=json.dumps(body),
110                              headers=self.headers,
111                              allow_nonstandard_methods=True)
112         else:
113             res = self.fetch(url,
114                              method='DELETE',
115                              headers=self.headers)
116
117         return res.code, res.body
118
119     def delete(self, *args):
120         return self.delete_direct_url(self._get_uri(*args), None)
121
122     @staticmethod
123     def _get_valid_args(*args):
124         new_args = tuple(['%s' % arg for arg in args if arg is not None])
125         return new_args, len(new_args)
126
127     def _need_arg_num(self, uri):
128         return uri.count('%s')
129
130     def _get_query_uri(self, query):
131         return self.basePath + '?' + query if query else self.basePath
132
133     def _get_uri(self, *args):
134         return self._update_uri(self.basePath, *args)
135
136     def _update_uri(self, uri, *args):
137         r_uri = uri
138         new_args, num = self._get_valid_args(*args)
139         if num != self._need_arg_num(uri):
140             r_uri += '/%s'
141
142         return r_uri % tuple(['%s' % arg for arg in new_args])
143
144     def _get_return(self, res, cls):
145         code = res.code
146         body = res.body
147         if body:
148             return code, self._get_return_body(code, body, cls)
149         else:
150             return code, None
151
152     @staticmethod
153     def _get_return_body(code, body, cls):
154         return cls.from_dict(json.loads(body)) if code < 300 and cls else body
155
156     def assert_href(self, body):
157         self.assertIn(self.basePath, body.href)
158
159     def assert_create_body(self, body, req=None, *args):
160         import inspect
161         if not req:
162             req = self.req_d
163         resource_name = ''
164         if inspect.isclass(req):
165             resource_name = req.name
166         elif isinstance(req, dict):
167             resource_name = req['name']
168         elif isinstance(req, str):
169             resource_name = json.loads(req)['name']
170         new_args = args + tuple([resource_name])
171         self.assertIn(self._get_uri(*new_args), body.href)
172
173     @staticmethod
174     def _clear():
175         fake_pymongo.pods.clear()
176         fake_pymongo.projects.clear()
177         fake_pymongo.testcases.clear()
178         fake_pymongo.results.clear()
179         fake_pymongo.scenarios.clear()