Support py3 in uncovered packages
[functest.git] / functest / opnfv_tests / vnf / ims / ixia / utils / IxRestUtils.py
1 #!/usr/bin/env python
2
3 # Copyright (c) 2017 IXIA and others.
4 #
5 # All rights reserved. This program and the accompanying materials
6 # are made available under the terms of the Apache License, Version 2.0
7 # which accompanies this distribution, and is available at
8 # http://www.apache.org/licenses/LICENSE-2.0
9
10 import requests
11
12
13 import six
14 from six.moves.urllib.parse import urljoin
15
16
17 def getConnection(server, port):
18     """
19     Gets a Connection instance, that will be used to
20     make the HTTP requests to the application
21     """
22     connectionUrl = 'http://%s:%s/' % (server, port)
23
24     conn = Connection(connectionUrl, 'v0')
25     return conn
26
27
28 def formatDictToJSONPayload(dictionary):
29     """
30     Converts a given python dict instance to a string
31     JSON payload that can be sent to a REST API.
32     """
33     jsonPayload = '{'
34     optionsList = []
35     for (key, val) in dictionary.items():
36         valStr = str(val)
37         if type(val) is str:
38             valStr = '"%s"' % val
39         if type(val) is bool:
40             valStr = valStr.lower()
41         optionsList.append('"%s":%s' % (key, valStr))
42
43     jsonPayload += ','.join(optionsList)
44     jsonPayload += '}'
45
46     return jsonPayload
47
48
49 class Connection(object):
50
51     """
52     Class that executes the HTTP requests to the application instance.
53     It handles creating the HTTP session and executing HTTP methods.
54     """
55
56     kHeaderContentType = 'content-type'
57     kContentJson = 'application/json'
58
59     def __init__(self, siteUrl, apiVersion):
60         self.httpSession = None
61
62         self.url = Connection.urljoin(siteUrl, 'api')
63         self.url = Connection.urljoin(self.url, apiVersion)
64
65     def _getHttpSession(self):
66         """
67         This is a lazy initializer for the HTTP session.
68         It does not need to be active until it is required.
69         """
70
71         if self.httpSession is None:
72             self.httpSession = requests.Session()
73         return self.httpSession
74
75     @classmethod
76     def urljoin(cls, base, end):
77         """ Join two URLs. If the second URL is absolute, the base is ignored.
78
79         Use this instead of urlparse.urljoin directly so that we can customize
80         its behavior if necessary.
81         Currently differs in that it
82
83             1. appends a / to base if not present.
84             2. casts end to a str as a convenience
85         """
86
87         if base and not base.endswith('/'):
88             base = base + '/'
89         return urljoin(base, str(end))
90
91     def httpRequest(self, method, url='', data='', params={}, headers={}):
92         """
93         Method for making a HTTP request.
94         The method type (GET, POST, PATCH, DELETE) will be sent as a parameter.
95         Along with the url and request data. The HTTP response is returned
96         """
97
98         headers[Connection.kHeaderContentType] = Connection.kContentJson
99
100         absUrl = Connection.urljoin(self.url, url)
101         result = self._getHttpSession().request(method,
102                                                 absUrl,
103                                                 data=str(data),
104                                                 params=params,
105                                                 headers=headers)
106         return result
107
108     def httpGet(self, url='', data='', params={}, headers={}):
109         """
110         Method for calling HTTP GET.
111         This will return a WebObject that has the fields returned
112         in JSON format by the GET operation.
113         """
114
115         reply = self.httpRequest('GET', url, data, params, headers)
116         return _WebObject(reply.json())
117
118     def httpPost(self, url='', data='', params={}, headers={}):
119         """
120         Method for calling HTTP POST. Will return the HTTP reply.
121         """
122
123         return self.httpRequest('POST', url, data, params, headers)
124
125     def httpPatch(self, url='', data='', params={}, headers={}):
126         """
127         Method for calling HTTP PATCH. Will return the HTTP reply.
128         """
129
130         return self.httpRequest('PATCH', url, data, params, headers)
131
132     def httpDelete(self, url='', data='', params={}, headers={}):
133         """
134         Method for calling HTTP DELETE. Will return the HTTP reply.
135         """
136
137         return self.httpRequest('DELETE', url, data, params, headers)
138
139
140 def _WebObject(value):
141     """
142     Method used for creating a wrapper object corresponding to the JSON string
143     received on a GET request.
144     """
145
146     if isinstance(value, dict):
147         result = WebObject(**value)
148     elif isinstance(value, list):
149         result = WebList(entries=value)
150     else:
151         result = value
152     return result
153
154
155 class WebList(list):
156
157     """
158     Using this class a JSON list will be transformed
159     in a list of WebObject instances.
160     """
161
162     def __init__(self, entries=[]):
163         """
164         Create a WebList from a list of items that
165         are processed by the _WebObject function
166         """
167
168         for item in entries:
169             self.append(_WebObject(item))
170
171
172 class WebObject(object):
173
174     """
175     A WebObject instance will have its fields set to correspond to
176     the JSON format received on a GET request.
177     """
178
179     def __init__(self, **entries):
180         """
181         Create a WebObject instance by providing a dict having a
182         property - value structure.
183         """
184
185         self.jsonOptions = {}
186         for (key, value) in six.iteritems(entries):
187             webObj = _WebObject(value)
188             self.jsonOptions[key] = webObj
189             self.__dict__[key] = webObj
190
191     def getOptions(self):
192         '''
193         Get the JSON dictionary which represents the WebObject Instance
194         '''
195
196         return self.jsonOptions