Created RESTCONF for base edition with of13 plugin
[integration/test.git] / test / csit / libraries / RequestsLibrary.py
1 import requests
2 import json
3
4 from urllib import urlencode
5
6
7 import robot
8
9 from robot.libraries.BuiltIn import BuiltIn
10
11
12 class RequestsLibrary(object):
13     ROBOT_LIBRARY_SCOPE = 'Global'
14
15     def __init__(self):
16         self._cache = robot.utils.ConnectionCache('No sessions created')
17         self.builtin = BuiltIn()
18
19     def _utf8_urlencode(self, data):
20         if not type(data) is dict:
21             return data
22
23         utf8_data = {}
24         for k,v in data.iteritems():
25             utf8_data[k] = unicode(v).encode('utf-8')
26         return urlencode(utf8_data)
27
28     def create_session(self, alias, url, headers={}, cookies=None,
29                        auth=None, timeout=None, proxies=None,
30                        verify=False):
31
32         """ Create Session: create a HTTP session to a server
33
34         `url` Base url of the server
35
36         `alias` Robot Framework alias to identify the session
37
38         `headers` Dictionary of default headers
39
40         `auth` Dictionary of username & password for HTTP Basic Auth
41
42         `timeout` connection timeout
43
44         `proxies` proxy server url
45
46         `verify` set to True if Requests should verify the certificate
47         """
48
49         self.builtin.log('Creating session: %s' % alias, 'DEBUG')
50         auth = requests.auth.HTTPBasicAuth(*auth) if auth else None
51         s = session = requests.Session()
52         s.headers.update(headers)
53         s.auth = auth if auth else s.auth
54         s.proxies = proxies if proxies else  s.proxies
55
56         s.verify = self.builtin.convert_to_boolean(verify)
57
58         # cant pass these into the Session anymore
59         self.timeout = timeout
60         self.cookies = cookies
61         self.verify = verify
62
63         # cant use hooks :(
64         s.url = url
65
66         self._cache.register(session, alias=alias)
67         return session
68
69     def delete_all_sessions(self):
70         """ Removes all the session objects """
71
72         self._cache.empty_cache()
73
74     def to_json(self, content):
75         """ Convert a string to a JSON object
76
77         `content` String content to convert into JSON
78         """
79         return json.loads(content)
80
81     
82     def _get_url(self, session, uri):
83         ''' Helpere method to get the full url
84         '''
85         url = session.url
86         if uri:
87             slash = '' if uri.startswith('/') else '/'
88             url = "%s%s%s" %(session.url, slash, uri)
89         return url
90
91     def get(self, alias, uri, headers=None):
92         """ Send a GET request on the session object found using the
93             given `alias`
94
95         `alias` that will be used to identify the Session object in the cache
96
97         `uri` to send the GET request to
98
99         `headers` a dictionary of headers to use with the request
100         """
101
102         session = self._cache.switch(alias)
103         resp = session.get(self._get_url(session, uri),
104                            headers=headers,
105                            cookies=self.cookies, timeout=self.timeout)
106
107         # store the last response object
108         session.last_resp = resp
109         return resp
110
111     def post(self, alias, uri, data={}, headers=None, files={}):
112         """ Send a POST request on the session object found using the
113         given `alias`
114
115         `alias` that will be used to identify the Session object in the cache
116
117         `uri` to send the GET request to
118
119         `data` a dictionary of key-value pairs that will be urlencoded
120                and sent as POST data
121                or binary data that is sent as the raw body content
122
123         `headers` a dictionary of headers to use with the request
124
125         `files` a dictionary of file names containing file data to POST to the server
126         """
127
128         session = self._cache.switch(alias)
129         data = self._utf8_urlencode(data)
130
131         resp = session.post(self._get_url(session, uri),
132                        data=data, headers=headers,
133                        files=files,
134                        cookies=self.cookies, timeout=self.timeout)
135
136         # store the last response object
137         session.last_resp = resp
138         self.builtin.log("Post response: " + resp.content, 'DEBUG')
139         return resp
140
141     def put(self, alias, uri, data=None, headers=None):
142         """ Send a PUT request on the session object found using the
143         given `alias`
144
145         `alias` that will be used to identify the Session object in the cache
146
147         `uri` to send the PUT request to
148
149         `headers` a dictionary of headers to use with the request
150
151         """
152
153         session = self._cache.switch(alias)
154         #data = self._utf8_urlencode(data)
155         data = json.dumps(data)
156
157         resp = session.put(self._get_url(session, uri),
158                     data=data, headers=headers,
159                     cookies=self.cookies, timeout=self.timeout)
160
161         self.builtin.log("PUT response: %s DEBUG" % resp.content)
162
163         # store the last response object
164         session.last_resp = resp
165         return resp
166
167     def put_xml(self, alias, uri, data=None, headers=None):
168         """ Send a PUT_xml request on the session object found using the
169         given `alias`
170
171         `alias` that will be used to identify the Session object in the cache
172
173         `uri` to send the PUT_xml request to
174
175         `headers` a dictionary of headers to use with the request
176
177         """
178
179         session = self._cache.switch(alias)
180         data = self._utf8_urlencode(data)
181         #data = json.dumps(data)
182
183         resp = session.put(self._get_url(session, uri),
184                     data=data, headers=headers,
185                     cookies=self.cookies, timeout=self.timeout)
186
187         self.builtin.log("PUT response: %s DEBUG" % resp.content)
188
189         # store the last response object
190         session.last_resp = resp
191         return resp
192
193     def delete(self, alias, uri, data=(), headers=None):
194         """ Send a DELETE request on the session object found using the
195         given `alias`
196
197         `alias` that will be used to identify the Session object in the cache
198
199         `uri` to send the DELETE request to
200
201         `headers` a dictionary of headers to use with the request
202
203         """
204
205         session = self._cache.switch(alias)
206         args = "?%s" % urlencode(data) if data else ''
207         resp = session.delete("%s%s" % (self._get_url(session, uri), args),
208                             headers=headers, cookies=self.cookies,
209                             timeout=self.timeout)
210
211         # store the last response object
212         session.last_resp = resp
213         return resp
214
215         
216     def head(self, alias, uri, headers=None):
217         """ Send a HEAD request on the session object found using the
218         given `alias`
219
220         `alias` that will be used to identify the Session object in the cache
221
222         `uri` to send the HEAD request to
223
224         `headers` a dictionary of headers to use with the request
225
226         """
227
228         session = self._cache.switch(alias)
229         resp = session.head(self._get_url(session, uri), headers=headers,
230                            cookies=self.cookies, timeout=self.timeout)
231
232         # store the last response object
233         session.last_resp = resp
234         return resp