Merge "Update Functest documentation for Euphrates"
[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             1. appends a / to base if not present.
80             2. casts end to a str as a convenience
81         """
82
83         if base and not base.endswith('/'):
84             base = base + '/'
85         return urljoin(base, str(end))
86
87     def httpRequest(self, method, url='', data='', params={}, headers={}):
88         """
89         Method for making a HTTP request.
90         The method type (GET, POST, PATCH, DELETE) will be sent as a parameter.
91         Along with the url and request data. The HTTP response is returned
92         """
93
94         headers[Connection.kHeaderContentType] = Connection.kContentJson
95
96         absUrl = Connection.urljoin(self.url, url)
97         result = self._getHttpSession().request(method,
98                                                 absUrl,
99                                                 data=str(data),
100                                                 params=params,
101                                                 headers=headers)
102         return result
103
104     def httpGet(self, url='', data='', params={}, headers={}):
105         """
106         Method for calling HTTP GET.
107         This will return a WebObject that has the fields returned
108         in JSON format by the GET operation.
109         """
110
111         reply = self.httpRequest('GET', url, data, params, headers)
112         return _WebObject(reply.json())
113
114     def httpPost(self, url='', data='', params={}, headers={}):
115         """
116         Method for calling HTTP POST. Will return the HTTP reply.
117         """
118
119         return self.httpRequest('POST', url, data, params, headers)
120
121     def httpPatch(self, url='', data='', params={}, headers={}):
122         """
123         Method for calling HTTP PATCH. Will return the HTTP reply.
124         """
125
126         return self.httpRequest('PATCH', url, data, params, headers)
127
128     def httpDelete(self, url='', data='', params={}, headers={}):
129         """
130         Method for calling HTTP DELETE. Will return the HTTP reply.
131         """
132
133         return self.httpRequest('DELETE', url, data, params, headers)
134
135
136 def _WebObject(value):
137     """
138     Method used for creating a wrapper object corresponding to the JSON string
139     received on a GET request.
140     """
141
142     if isinstance(value, dict):
143         result = WebObject(**value)
144     elif isinstance(value, list):
145         result = WebList(entries=value)
146     else:
147         result = value
148     return result
149
150
151 class WebList(list):
152
153     """
154     Using this class a JSON list will be transformed
155     in a list of WebObject instances.
156     """
157
158     def __init__(self, entries=[]):
159         """
160         Create a WebList from a list of items that
161         are processed by the _WebObject function
162         """
163
164         for item in entries:
165             self.append(_WebObject(item))
166
167
168 class WebObject(object):
169
170     """
171     A WebObject instance will have its fields set to correspond to
172     the JSON format received on a GET request.
173     """
174
175     def __init__(self, **entries):
176         """
177         Create a WebObject instance by providing a dict having a
178         property - value structure.
179         """
180
181         self.jsonOptions = {}
182         for (key, value) in entries.iteritems():
183             webObj = _WebObject(value)
184             self.jsonOptions[key] = webObj
185             self.__dict__[key] = webObj
186
187     def getOptions(self):
188         '''
189             Get the JSON dictionary which represents the WebObject Instance
190         '''
191
192         return self.jsonOptions