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