fc780e44cb8517da52d2d7f33de8bd396549fb68
[releng.git] / utils / test / testapi / opnfv_testapi / tests / unit / 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
11 from tornado.web import Application
12 from tornado.testing import AsyncHTTPTestCase
13
14 from opnfv_testapi.router import url_mappings
15 from opnfv_testapi.resources.models import CreateResponse
16 import fake_pymongo
17
18
19 class TestBase(AsyncHTTPTestCase):
20     headers = {'Content-Type': 'application/json; charset=UTF-8'}
21
22     def setUp(self):
23         self.basePath = ''
24         self.create_res = CreateResponse
25         self.get_res = None
26         self.list_res = None
27         self.update_res = None
28         self.req_d = None
29         self.req_e = None
30         self.addCleanup(self._clear)
31         super(TestBase, self).setUp()
32
33     def get_app(self):
34         return Application(
35             url_mappings.mappings,
36             db=fake_pymongo,
37             debug=True,
38         )
39
40     def create_d(self, *args):
41         return self.create(self.req_d, *args)
42
43     def create_e(self, *args):
44         return self.create(self.req_e, *args)
45
46     def create(self, req=None, *args):
47         return self.create_help(self.basePath, req, *args)
48
49     def create_help(self, uri, req, *args):
50         if req and not isinstance(req, str) and hasattr(req, 'format'):
51             req = req.format()
52         res = self.fetch(self._update_uri(uri, *args),
53                          method='POST',
54                          body=json.dumps(req),
55                          headers=self.headers)
56
57         return self._get_return(res, self.create_res)
58
59     def get(self, *args):
60         res = self.fetch(self._get_uri(*args),
61                          method='GET',
62                          headers=self.headers)
63
64         def inner():
65             new_args, num = self._get_valid_args(*args)
66             return self.get_res \
67                 if num != self._need_arg_num(self.basePath) else self.list_res
68         return self._get_return(res, inner())
69
70     def query(self, query):
71         res = self.fetch(self._get_query_uri(query),
72                          method='GET',
73                          headers=self.headers)
74         return self._get_return(res, self.list_res)
75
76     def update(self, new=None, *args):
77         if new:
78             new = new.format()
79         res = self.fetch(self._get_uri(*args),
80                          method='PUT',
81                          body=json.dumps(new),
82                          headers=self.headers)
83         return self._get_return(res, self.update_res)
84
85     def delete(self, *args):
86         res = self.fetch(self._get_uri(*args),
87                          method='DELETE',
88                          headers=self.headers)
89         return res.code, res.body
90
91     @staticmethod
92     def _get_valid_args(*args):
93         new_args = tuple(['%s' % arg for arg in args if arg is not None])
94         return new_args, len(new_args)
95
96     def _need_arg_num(self, uri):
97         return uri.count('%s')
98
99     def _get_query_uri(self, query):
100         return self.basePath + '?' + query if query else self.basePath
101
102     def _get_uri(self, *args):
103         return self._update_uri(self.basePath, *args)
104
105     def _update_uri(self, uri, *args):
106         r_uri = uri
107         new_args, num = self._get_valid_args(*args)
108         if num != self._need_arg_num(uri):
109             r_uri += '/%s'
110
111         return r_uri % tuple(['%s' % arg for arg in new_args])
112
113     def _get_return(self, res, cls):
114         code = res.code
115         body = res.body
116         return code, self._get_return_body(code, body, cls)
117
118     @staticmethod
119     def _get_return_body(code, body, cls):
120         return cls.from_dict(json.loads(body)) if code < 300 and cls else body
121
122     def assert_href(self, body):
123         self.assertIn(self.basePath, body.href)
124
125     def assert_create_body(self, body, req=None, *args):
126         import inspect
127         if not req:
128             req = self.req_d
129         resource_name = ''
130         if inspect.isclass(req):
131             resource_name = req.name
132         elif isinstance(req, dict):
133             resource_name = req['name']
134         elif isinstance(req, str):
135             resource_name = json.loads(req)['name']
136         new_args = args + tuple([resource_name])
137         self.assertIn(self._get_uri(*new_args), body.href)
138
139     @staticmethod
140     def _clear():
141         fake_pymongo.pods.clear()
142         fake_pymongo.projects.clear()
143         fake_pymongo.testcases.clear()
144         fake_pymongo.results.clear()
145         fake_pymongo.scenarios.clear()