-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathSessionKeywords.py
659 lines (545 loc) · 25.2 KB
/
SessionKeywords.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
import logging
import sys
import requests
from requests.cookies import merge_cookies
from requests.models import Response
from requests.sessions import merge_setting
from robot.api import logger
from robot.api.deco import keyword
from robot.utils.asserts import assert_equal
from RequestsLibrary import utils
from RequestsLibrary.compat import RetryAdapter, httplib
from RequestsLibrary.exceptions import InvalidExpectedStatus, InvalidResponse
from RequestsLibrary.utils import is_string_type
from .RequestsKeywords import RequestsKeywords
try:
from requests_ntlm import HttpNtlmAuth
except ImportError:
pass
class SessionKeywords(RequestsKeywords):
DEFAULT_RETRY_METHOD_LIST = RetryAdapter.get_default_allowed_methods()
def _create_session(
self,
alias,
url,
headers,
cookies,
auth,
timeout,
proxies,
verify,
debug,
max_retries,
backoff_factor,
disable_warnings,
retry_status_list,
retry_method_list,
):
logger.debug("Creating session: %s" % alias)
s = session = requests.Session()
s.headers.update(headers)
s.auth = auth if auth else s.auth
s.proxies = proxies if proxies else s.proxies
try:
max_retries = int(max_retries)
retry_status_list = (
[int(x) for x in retry_status_list] if retry_status_list else None
)
except ValueError as err:
raise ValueError("Error converting session parameter: %s" % err)
if max_retries > 0:
retry = RetryAdapter(
total=max_retries,
backoff_factor=backoff_factor,
status_forcelist=retry_status_list,
allowed_methods=retry_method_list,
)
http = requests.adapters.HTTPAdapter(max_retries=retry)
https = requests.adapters.HTTPAdapter(max_retries=retry)
# Replace the session's original adapters
s.mount("http://", http)
s.mount("https://", https)
# Disable requests warnings, useful when you have large number of testcase
# you will observe drastical changes in Robot log.html and output.xml files size
if disable_warnings:
# you need to initialize logging, otherwise you will not see anything from requests
logging.basicConfig()
logging.getLogger().setLevel(logging.ERROR)
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.ERROR)
requests_log.propagate = True
if not verify:
requests.packages.urllib3.disable_warnings()
# verify can be a Boolean or a String
if isinstance(verify, bool):
s.verify = verify
elif utils.is_string_type(verify):
if verify.lower() == "true" or verify.lower() == "false":
s.verify = self.builtin.convert_to_boolean(verify)
else:
# String for CA_BUNDLE, not a Boolean String
s.verify = verify
else:
# not a Boolean nor a String
s.verify = verify
# cant pass these into the Session anymore
self.timeout = timeout
self.cookies = cookies
s.url = url
# Enable http verbosity
if int(debug) >= 1:
self.debug = int(debug)
httplib.HTTPConnection.debuglevel = self.debug
self._cache.register(session, alias=alias)
return session
@keyword("Create Session")
def create_session(
self,
alias,
url,
headers={},
cookies={},
auth=None,
timeout=None,
proxies=None,
verify=False,
debug=0,
max_retries=3,
backoff_factor=0.10,
disable_warnings=0,
retry_status_list=[],
retry_method_list=DEFAULT_RETRY_METHOD_LIST,
):
"""Create Session: create a HTTP session to a server
``alias`` Robot Framework alias to identify the session
``url`` Base url of the server
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``auth`` List of username & password for HTTP Basic Auth
``timeout`` Connection timeout
``proxies`` Dictionary mapping protocol or protocol and host to the URL of the proxy
(e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'})
``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided.
``debug`` Enable http verbosity option more information. Valid values are 0, 1, 2 ...
https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel
``max_retries`` Number of maximum retries each connection should attempt.
By default it will retry 3 times in case of connection errors only.
A 0 value will disable any kind of retries regardless of other retry settings.
In case the number of retries is reached a retry exception is raised.
``disable_warnings`` Disable requests warning useful when you have large number of testcases
``backoff_factor`` Introduces a delay time between retries that is longer after each retry.
eg. if backoff_factor is set to 0.1
the sleep between attemps will be: 0.0, 0.2, 0.4
More info here: https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html
``retry_method_list`` List of uppercased HTTP method verbs where retries are allowed.
By default retries are allowed only on HTTP requests methods that are considered to be
idempotent (multiple requests with the same parameters end with the same state).
eg. set to ['POST', 'GET'] to retry only those kind of requests.
``retry_status_list`` List of integer HTTP status codes that, if returned, a retry is attempted.
eg. set to [502, 503] to retry requests if those status are returned.
Note that max_retries must be greater than 0.
"""
auth = requests.auth.HTTPBasicAuth(*auth) if auth else None
logger.info(
"Creating Session using : alias=%s, url=%s, headers=%s, \
cookies=%s, auth=%s, timeout=%s, proxies=%s, verify=%s, \
debug=%s "
% (alias, url, headers, cookies, auth, timeout, proxies, verify, debug)
)
return self._create_session(
alias=alias,
url=url,
headers=headers,
cookies=cookies,
auth=auth,
timeout=timeout,
max_retries=max_retries,
backoff_factor=backoff_factor,
proxies=proxies,
verify=verify,
debug=debug,
disable_warnings=disable_warnings,
retry_status_list=retry_status_list,
retry_method_list=retry_method_list,
)
@keyword("Create Client Cert Session")
def create_client_cert_session(
self,
alias,
url,
headers={},
cookies={},
auth=None,
client_certs=None,
timeout=None,
proxies=None,
verify=False,
debug=0,
max_retries=3,
backoff_factor=0.10,
disable_warnings=0,
retry_status_list=[],
retry_method_list=DEFAULT_RETRY_METHOD_LIST,
):
"""Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``auth`` List of username & password for HTTP Basic Auth
``client_certs`` ['client certificate', 'client key'] PEM files containing the client key and certificate
``timeout`` Connection timeout
``proxies`` Dictionary mapping protocol or protocol and host to the URL of the proxy
(e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'})
``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided.
Defaults to False.
``debug`` Enable http verbosity option more information. Valid values are 0, 1, 2 ...
https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel
``max_retries`` Number of maximum retries each connection should attempt.
By default it will retry 3 times in case of connection errors only.
A 0 value will disable any kind of retries regardless of other retry settings.
In case the number of retries is reached a retry exception is raised.
``disable_warnings`` Disable requests warning useful when you have large number of testcases
``backoff_factor`` Introduces a delay time between retries that is longer after each retry.
eg. if backoff_factor is set to 0.1
the sleep between attemps will be: 0.0, 0.2, 0.4
More info here: https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html
``retry_method_list`` List of uppercased HTTP method verbs where retries are allowed.
By default retries are allowed only on HTTP requests methods that are considered to be
idempotent (multiple requests with the same parameters end with the same state).
eg. set to ['POST', 'GET'] to retry only those kind of requests.
``retry_status_list`` List of integer HTTP status codes that, if returned, a retry is attempted.
eg. set to [502, 503] to retry requests if those status are returned.
Note that max_retries must be greater than 0.
"""
auth = requests.auth.HTTPBasicAuth(*auth) if auth else None
logger.info(
"Creating Session using : alias=%s, url=%s, headers=%s, \
cookies=%s, auth=%s, client_certs=%s, timeout=%s, proxies=%s, verify=%s, \
debug=%s "
% (
alias,
url,
headers,
cookies,
auth,
client_certs,
timeout,
proxies,
verify,
debug,
)
)
session = self._create_session(
alias=alias,
url=url,
headers=headers,
cookies=cookies,
auth=auth,
timeout=timeout,
max_retries=max_retries,
backoff_factor=backoff_factor,
proxies=proxies,
verify=verify,
debug=debug,
disable_warnings=disable_warnings,
retry_status_list=retry_status_list,
retry_method_list=retry_method_list,
)
session.cert = tuple(client_certs)
return session
@keyword("Create Custom Session")
def create_custom_session(
self,
alias,
url,
auth,
headers={},
cookies={},
timeout=None,
proxies=None,
verify=False,
debug=0,
max_retries=3,
backoff_factor=0.10,
disable_warnings=0,
retry_status_list=[],
retry_method_list=DEFAULT_RETRY_METHOD_LIST,
):
"""Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``auth`` A Custom Authentication object to be passed on to the requests library.
http://docs.python-requests.org/en/master/user/advanced/#custom-authentication
``timeout`` Connection timeout
``proxies`` Dictionary mapping protocol or protocol and host to the URL of the proxy
(e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'})
``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided.
Defaults to False.
``debug`` Enable http verbosity option more information. Valid values are 0, 1, 2 ...
https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel
``max_retries`` Number of maximum retries each connection should attempt.
By default it will retry 3 times in case of connection errors only.
A 0 value will disable any kind of retries regardless of other retry settings.
In case the number of retries is reached a retry exception is raised.
``disable_warnings`` Disable requests warning useful when you have large number of testcases
``backoff_factor`` Introduces a delay time between retries that is longer after each retry.
eg. if backoff_factor is set to 0.1
the sleep between attemps will be: 0.0, 0.2, 0.4
More info here: https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html
``retry_method_list`` List of uppercased HTTP method verbs where retries are allowed.
By default retries are allowed only on HTTP requests methods that are considered to be
idempotent (multiple requests with the same parameters end with the same state).
eg. set to ['POST', 'GET'] to retry only those kind of requests.
``retry_status_list`` List of integer HTTP status codes that, if returned, a retry is attempted.
eg. set to [502, 503] to retry requests if those status are returned.
Note that max_retries must be greater than 0.
"""
logger.info(
"Creating Custom Authenticated Session using : alias=%s, url=%s, headers=%s, \
cookies=%s, auth=%s, timeout=%s, proxies=%s, verify=%s, \
debug=%s "
% (alias, url, headers, cookies, auth, timeout, proxies, verify, debug)
)
return self._create_session(
alias=alias,
url=url,
headers=headers,
cookies=cookies,
auth=auth,
timeout=timeout,
max_retries=max_retries,
backoff_factor=backoff_factor,
proxies=proxies,
verify=verify,
debug=debug,
disable_warnings=disable_warnings,
retry_status_list=retry_status_list,
retry_method_list=retry_method_list,
)
@keyword("Create Digest Session")
def create_digest_session(
self,
alias,
url,
auth,
headers={},
cookies={},
timeout=None,
proxies=None,
verify=False,
debug=0,
max_retries=3,
backoff_factor=0.10,
disable_warnings=0,
retry_status_list=[],
retry_method_list=DEFAULT_RETRY_METHOD_LIST,
):
"""Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``auth`` ['DOMAIN', 'username', 'password'] for NTLM Authentication
``timeout`` Connection timeout
``proxies`` Dictionary mapping protocol or protocol and host to the URL of the proxy
(e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'})
``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided.
Defaults to False.
``debug`` Enable http verbosity option more information. Valid values are 0, 1, 2 ...
https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel
``max_retries`` Number of maximum retries each connection should attempt.
By default it will retry 3 times in case of connection errors only.
A 0 value will disable any kind of retries regardless of other retry settings.
In case the number of retries is reached a retry exception is raised.
``disable_warnings`` Disable requests warning useful when you have large number of testcases
``backoff_factor`` Introduces a delay time between retries that is longer after each retry.
eg. if backoff_factor is set to 0.1
the sleep between attemps will be: 0.0, 0.2, 0.4
More info here: https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html
``retry_method_list`` List of uppercased HTTP method verbs where retries are allowed.
By default retries are allowed only on HTTP requests methods that are considered to be
idempotent (multiple requests with the same parameters end with the same state).
eg. set to ['POST', 'GET'] to retry only those kind of requests.
``retry_status_list`` List of integer HTTP status codes that, if returned, a retry is attempted.
eg. set to [502, 503] to retry requests if those status are returned.
Note that max_retries must be greater than 0.
"""
digest_auth = requests.auth.HTTPDigestAuth(*auth) if auth else None
return self._create_session(
alias=alias,
url=url,
headers=headers,
cookies=cookies,
auth=digest_auth,
timeout=timeout,
max_retries=max_retries,
backoff_factor=backoff_factor,
proxies=proxies,
verify=verify,
debug=debug,
disable_warnings=disable_warnings,
retry_status_list=retry_status_list,
retry_method_list=retry_method_list,
)
@keyword("Create Ntlm Session")
def create_ntlm_session(
self,
alias,
url,
auth,
headers={},
cookies={},
timeout=None,
proxies=None,
verify=False,
debug=0,
max_retries=3,
backoff_factor=0.10,
disable_warnings=0,
retry_status_list=[],
retry_method_list=DEFAULT_RETRY_METHOD_LIST,
):
"""Create Session: create a HTTP session to a server
``url`` Base url of the server
``alias`` Robot Framework alias to identify the session
``headers`` Dictionary of default headers
``cookies`` Dictionary of cookies
``auth`` ['DOMAIN', 'username', 'password'] for NTLM Authentication
``timeout`` Connection timeout
``proxies`` Dictionary mapping protocol or protocol and host to the URL of the proxy
(e.g. {'http': 'foo.bar:3128', 'http://host.name': 'foo.bar:4012'})
``verify`` Whether the SSL cert will be verified. A CA_BUNDLE path can also be provided.
Defaults to False.
``debug`` Enable http verbosity option more information. Valid values are 0, 1, 2 ...
https://docs.python.org/2/library/httplib.html#httplib.HTTPConnection.set_debuglevel
``max_retries`` Number of maximum retries each connection should attempt.
By default it will retry 3 times in case of connection errors only.
A 0 value will disable any kind of retries regardless of other retry settings.
In case the number of retries is reached a retry exception is raised.
``disable_warnings`` Disable requests warning useful when you have large number of testcases
``backoff_factor`` Introduces a delay time between retries that is longer after each retry.
eg. if backoff_factor is set to 0.1
the sleep between attemps will be: 0.0, 0.2, 0.4
More info here: https://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html
``retry_method_list`` List of uppercased HTTP method verbs where retries are allowed.
By default retries are allowed only on HTTP requests methods that are considered to be
idempotent (multiple requests with the same parameters end with the same state).
eg. set to ['POST', 'GET'] to retry only those kind of requests.
``retry_status_list`` List of integer HTTP status codes that, if returned, a retry is attempted.
eg. set to [502, 503] to retry requests if those status are returned.
Note that max_retries must be greater than 0.
"""
try:
HttpNtlmAuth
except NameError:
raise AssertionError("requests_ntlm module not installed")
if len(auth) != 3:
raise AssertionError(
"Incorrect number of authentication arguments"
" - expected 3, got {}".format(len(auth))
)
else:
ntlm_auth = HttpNtlmAuth("{}\\{}".format(auth[0], auth[1]), auth[2])
logger.info(
"Creating NTLM Session using : alias=%s, url=%s, \
headers=%s, cookies=%s, ntlm_auth=%s, timeout=%s, \
proxies=%s, verify=%s, debug=%s "
% (
alias,
url,
headers,
cookies,
ntlm_auth,
timeout,
proxies,
verify,
debug,
)
)
return self._create_session(
alias=alias,
url=url,
headers=headers,
cookies=cookies,
auth=ntlm_auth,
timeout=timeout,
max_retries=max_retries,
backoff_factor=backoff_factor,
proxies=proxies,
verify=verify,
debug=debug,
disable_warnings=disable_warnings,
retry_status_list=retry_status_list,
retry_method_list=retry_method_list,
)
@keyword("Session Exists")
def session_exists(self, alias):
"""Return True if the session has been already created
``alias`` that has been used to identify the Session object in the cache
"""
try:
self._cache[alias]
return True
except RuntimeError:
return False
@keyword("Delete All Sessions")
def delete_all_sessions(self):
"""Removes all the session objects"""
logger.info("Deleting All Sessions")
self._cache.close_all()
# TODO this is not covered by any tests
@keyword("Update Session")
def update_session(self, alias, headers=None, cookies=None):
"""Updates HTTP Session Headers and Cookies.
Session will be identified using the ``alias`` name.
Dictionary of ``headers`` and ``cookies`` to be updated and merged into session data.
"""
session = self._cache.switch(alias)
session.headers = merge_setting(headers, session.headers)
session.cookies = merge_cookies(session.cookies, cookies)
@staticmethod
def _check_status(expected_status, resp, msg=None):
"""
Helper method to check HTTP status
"""
if not isinstance(resp, Response):
raise InvalidResponse(resp)
if expected_status is None:
resp.raise_for_status()
else:
if not is_string_type(expected_status):
raise InvalidExpectedStatus(expected_status)
if expected_status.lower() in ["any", "anything"]:
return
try:
expected_status = int(expected_status)
except ValueError:
expected_status = utils.parse_named_status(expected_status)
msg = "" if msg is None else "{} ".format(msg)
msg = "{}Url: {} Expected status".format(msg, resp.url)
assert_equal(expected_status, resp.status_code, msg)
def _get_timeout(self, timeout):
result = timeout if timeout is not None else self.timeout
if result is None:
return None
if type(result) is tuple:
return (float(result[0]), float(result[1]))
return float(result)
def _capture_output(self):
if self.debug >= 1:
self.http_log = utils.WritableObject()
sys.stdout = self.http_log
def _print_debug(self):
if self.debug >= 1:
sys.stdout = sys.__stdout__ # Restore stdout
debug_info = (
"".join(self.http_log.content).replace("\\r", "").replace("'", "")
)
# Remove empty lines
debug_info = "\n".join(
[ll.rstrip() for ll in debug_info.splitlines() if ll.strip()]
)
logger.debug(debug_info)