-
Notifications
You must be signed in to change notification settings - Fork 461
/
utils.py
2426 lines (1957 loc) · 80.9 KB
/
utils.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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
"""
Every project needs its trash heap of miscellaneous functions and classes
Copyright 2015 BlazeMeter Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import codecs
import copy
import csv
import fnmatch
import ipaddress
import itertools
import json
import locale
import logging
import math
import mimetypes
import operator
import os
import platform
import random
import re
import shlex
import shutil
import signal
import subprocess
import sys
import tarfile
import tempfile
import time
import traceback
import webbrowser
import zipfile
from abc import abstractmethod
from collections import defaultdict, Counter
from contextlib import contextmanager
from distutils.version import LooseVersion
from io import IOBase
from ssl import SSLError
from subprocess import CalledProcessError, PIPE, check_output, STDOUT
from urllib import parse
from urllib.error import URLError
from urllib.parse import urlparse
from urllib.request import url2pathname
from webbrowser import GenericBrowser
import psutil
import requests
import requests.adapters
from lxml import etree
from progressbar import ProgressBar, Percentage, Bar, ETA
from requests.exceptions import ReadTimeout
from urwid import BaseScreen
from bzt import TaurusInternalException, TaurusNetworkError, ToolError, TaurusConfigError
LOG = logging.getLogger("")
CALL_PROBLEMS = (CalledProcessError, OSError)
NETWORK_PROBLEMS = (IOError, URLError, SSLError, ReadTimeout, TaurusNetworkError)
numeric_types = (int, float, complex)
viewvalues = operator.methodcaller("values")
def unicode_decode(string, errors="strict"):
if isinstance(string, bytes):
return string.decode("utf-8", errors)
else:
return string
def communicate(proc):
out, err = proc.communicate()
out = unicode_decode(out, errors="ignore")
err = unicode_decode(err, errors="ignore")
return out, err
def iteritems(dictionary, **kw):
return iter(dictionary.items(**kw))
def b(string):
return string.encode("latin-1")
def get_stacktrace(exc):
return ''.join(traceback.format_tb(exc.__traceback__)).rstrip()
def reraise(exc_info, exc=None):
_type, message, stacktrace = exc_info
if exc is None:
exc = _type(message)
exc.__traceback__ = stacktrace
raise exc
def stream_decode(string):
if not isinstance(string, str):
return string.decode()
else:
return string
def sync_run(args, env=None):
output = check_output(args, env=env, stderr=STDOUT)
return stream_decode(output).rstrip()
def temp_file(suffix="", prefix="tmp", dir=None):
""" Creates temporary file, returns name of it. User is responsible for deleting the file """
fd, fname = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir)
os.close(fd)
return fname
def simple_body_dict(dic):
""" body dict must have just one level for sending with form params"""
if isinstance(dic, dict):
for key in dic:
if not isinstance(dic[key], (str, numeric_types)):
return False
return True
return False
def get_full_path(path, default=None, step_up=0):
"""
Function expands '~' and adds cwd to path if it's not absolute (relative)
Target doesn't have to exist
:param path:
:param default:
:param step_up:
:return:
"""
if not path:
return default
res = os.path.abspath(os.path.expanduser(path))
for _ in range(step_up):
res = os.path.dirname(res)
return res
BZT_DIR = get_full_path(__file__, step_up=1)
RESOURCES_DIR = os.path.join(BZT_DIR, "resources")
def get_files_recursive(dir_name, exclude_mask=''):
for root, _, files in os.walk(dir_name):
for _file in files:
if not fnmatch.fnmatch(_file, exclude_mask):
yield os.path.join(root, _file)
def parse_java_version(versions):
if versions:
version = versions[0]
if LooseVersion(version) > LooseVersion("6"): # start of openjdk naming
major = re.findall("^([\d]*)", version)
else:
major = re.findall("\.([\d]*)", version)
if major:
return major[0]
def run_once(func):
"""
A decorator to run function only once
:type func: __builtin__.function
:return:
"""
def wrapper(*args, **kwargs):
"""
:param kwargs:
:param args:
"""
if not wrapper.has_run:
wrapper.has_run = True
return func(*args, **kwargs)
wrapper.has_run = False
return wrapper
def replace_in_config(config, samples, substitutes, log=None):
def file_replacer(value, key, container):
if value in samples:
container[key] = substitutes[samples.index(value)]
if container[key] != value and log:
log.debug("Replaced %s with %s", value, container[key])
BetterDict.traverse(config, file_replacer)
def dehumanize_time(str_time):
"""
Convert value like 1d4h33m12s103ms into seconds
Also, incidentally translates strings like "inf" into float("inf")
:param str_time: string to convert
:return: float value in seconds
:raise TaurusInternalException: in case of unsupported unit
"""
if not str_time:
return 0
parser = re.compile(r'([\d\.\-infa]+)([a-zA-Z]*)')
parts = parser.findall(str(str_time).replace(' ', ''))
if len(parts) == 0:
msg = "String format not supported: %s"
raise TaurusInternalException(msg % str_time)
result = 0.0
for value, unit in parts:
try:
value = float(value)
except ValueError:
raise TaurusInternalException("Unsupported float string: %r" % value)
unit = unit.lower()
if unit == 'ms':
result += value / 1000.0
continue
elif unit == 's' or unit == '':
result += value
continue
elif unit == 'm':
result += value * 60
continue
elif unit == 'h':
result += value * 60 * 60
continue
elif unit == 'd':
result += value * 60 * 60 * 24
continue
else:
msg = "String contains unsupported unit %s: %s"
raise TaurusInternalException(msg % (unit, str_time))
return result
def get_bytes_count(str_bytes):
if not str_bytes:
return 0
parser = re.compile(r'([\d\.]+)([a-zA-Z]*)')
parts = parser.findall(str(str_bytes).replace(' ', ''))
if len(parts) != 1:
msg = "String format not supported: %s"
raise TaurusConfigError(msg % str_bytes)
value, unit = parts[0]
try:
value = float(value)
except ValueError:
raise TaurusConfigError("Unsupported float string: %r" % value)
unit = unit.lower()
if unit in ('', 'b'):
result = value
elif unit in ('k', 'kb', 'kib'):
result = value * 1024
elif unit in ('m', 'mb', 'mib'):
result = value * 1024 * 1024
else:
msg = "String contains unsupported unit %s: %s"
raise TaurusConfigError(msg % (unit, str_bytes))
return result
class BetterDict(defaultdict):
"""
Wrapper for defaultdict that able to deep merge other dicts into itself
"""
@classmethod
def from_dict(cls, orig):
"""
# https://stackoverflow.com/questions/50013768/how-can-i-convert-nested-dictionary-to-defaultdict/50013806
"""
if isinstance(orig, dict):
return cls(lambda: None, {k: cls.from_dict(v) for k, v in orig.items()})
elif isinstance(orig, list):
return [cls.from_dict(e) for e in orig]
else:
return orig
def get(self, key, default=defaultdict, force_set=False):
"""
Change get with setdefault
:param force_set:
:type key: object
:type default: object
"""
if default == defaultdict:
default = BetterDict()
if isinstance(default, BaseException) and key not in self:
raise default
if force_set:
value = self.setdefault(key, default)
else:
value = defaultdict.get(self, key, default)
return value
def merge(self, src):
"""
Deep merge other dict into current
:type src: dict
"""
if not isinstance(src, dict):
raise TaurusInternalException("Loaded object is not dict [%s]: %s" % (src.__class__, src))
for key, val in iteritems(src):
prefix = ""
if key[0] in ("^", "~", "$"): # modificator found
prefix = key[0]
key = key[1:]
if prefix == "^": # eliminate flag
if key in self:
self.pop(key)
continue
elif prefix == "~": # overwrite flag
if key in self:
self.pop(key)
if isinstance(val, dict):
self.__add_dict(key, val)
elif isinstance(val, list):
self.__add_list(key, val, merge_list_items=(prefix == "$"))
else:
self[key] = val
return self
def __add_dict(self, key, val):
dst = self.get(key, force_set=True)
if isinstance(dst, BetterDict):
dst.merge(val)
elif isinstance(dst, Counter):
self[key] += val
elif isinstance(dst, dict):
raise TaurusInternalException("Mix of DictOfDict and dict is forbidden")
else:
self[key] = BetterDict.from_dict(val)
def __add_list(self, key, val, merge_list_items):
self.__ensure_list_type(val)
if key not in self:
self[key] = []
if not isinstance(self[key], list):
self[key] = val
return
if merge_list_items:
left = self[key]
right = val
for index, righty in enumerate(right):
if index < len(left):
lefty = left[index]
if isinstance(lefty, BetterDict) and isinstance(righty, BetterDict):
lefty.merge(righty)
else:
LOG.warning("Overwriting the value of %r when merging configs", key)
left[index] = righty
else:
left.insert(index, righty)
else:
self[key].extend(val)
def __ensure_list_type(self, values):
"""
Ensure that values is a list, convert if needed
:param values: dict or list
:return:
"""
for idx, obj in enumerate(values):
if isinstance(obj, dict):
values[idx] = BetterDict.from_dict(obj)
elif isinstance(obj, list):
self.__ensure_list_type(obj)
@classmethod
def traverse(cls, obj, visitor):
"""
Deep traverse dict with visitor. If visitor returns any value, don't traverse into
:type obj: list or dict or object
:type visitor: callable
"""
if isinstance(obj, dict):
for key, val in iteritems(obj):
if not visitor(val, key, obj):
cls.traverse(obj[key], visitor)
elif isinstance(obj, list):
for idx, val in enumerate(obj):
if not visitor(val, idx, obj):
cls.traverse(obj[idx], visitor)
def filter(self, rules, black_list=False):
keys = set(self.keys())
for key in keys:
ikey = "!" + key
if (key in rules) or (ikey in rules): # we have rule for this key
current_black_list = black_list if key in rules else not black_list
rkey = key if key in rules else ikey
if isinstance(rules.get(rkey), dict):
if isinstance(self.get(key), BetterDict): # need to go deeper
self.get(key).filter(rules[rkey], black_list=current_black_list)
elif not current_black_list:
del self[key]
elif current_black_list:
del self[key] # must be blacklisted
elif not black_list:
del self[key] # remove unknown key
current = self.get(key, None)
if isinstance(current, (dict, list)) and not current:
del self[key] # clean empty
def __repr__(self):
return dict(self).__repr__()
def get_uniq_name(directory, prefix, suffix="", forbidden_names=()):
base = os.path.join(directory, prefix)
diff = ""
num = 0
while os.path.exists(base + diff + suffix) or base + diff + suffix in forbidden_names:
num += 1
diff = "-%s" % num
return base + diff + suffix
class TaurusCalledProcessError(CalledProcessError):
def __init__(self, *args, **kwargs):
""" join output and stderr for compatibility """
output = ""
if "output" in kwargs:
output += u"\n>>> {out_start} >>>\n{out}\n<<< {out_end} <<<\n".format(
out_start="START OF STDOUT", out=kwargs["output"], out_end="END OF STDOUT")
if "stderr" in kwargs:
output += u"\n>>> {err_start} >>>\n{err}\n<<< {err_end} <<<\n".format(
err_start="START OF STDERR", err=kwargs.pop("stderr"), err_end="END OF STDERR")
if output:
kwargs["output"] = output
super(TaurusCalledProcessError, self).__init__(*args, **kwargs)
def __str__(self):
base_str = super(TaurusCalledProcessError, self).__str__()
if self.output:
base_str += '\n' + self.output
return base_str
def exec_and_communicate(*args, **kwargs):
process = shell_exec(*args, **kwargs)
out, err = communicate(process)
if process.returncode != 0:
raise TaurusCalledProcessError(process.returncode, cmd=args[0], output=out, stderr=err)
return out, err
def shell_exec(args, cwd=None, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=False, env=None, pgrp=True):
"""
Wrapper for subprocess starting
"""
if stdout and not isinstance(stdout, (int, IOBase)):
LOG.warning("stdout is not IOBase: %s", stdout)
stdout = None
if stderr and not isinstance(stderr, (int, IOBase)):
LOG.warning("stderr is not IOBase: %s", stderr)
stderr = None
if isinstance(args, str) and not shell:
args = shlex.split(args, posix=not is_windows())
LOG.debug("Executing shell: %s at %s", args, cwd or os.curdir)
kwargs = {
"stdout": stdout,
"stderr": stderr,
"stdin": stdin,
"bufsize": 0,
"cwd": cwd,
"shell": shell,
"env": env
}
if is_windows():
if pgrp:
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
return psutil.Popen(args, **kwargs)
else:
kwargs["close_fds"] = True
if pgrp:
kwargs["preexec_fn"] = os.setpgrp
return psutil.Popen(args, **kwargs)
class Environment(object):
def __init__(self, log=None, parent=None):
self.data = {}
self._queue = []
log = log or LOG
self.log = log.getChild(self.__class__.__name__)
if parent:
self._queue.extend(
[(self.__getattribute__(method), args, kwargs) for method, args, kwargs in parent.get_queue()])
def get_queue(self):
return [(method.__name__, args, kwargs) for method, args, kwargs in self._queue]
def set(self, *args, **kwargs):
self._add_to_queue(self._set, *args, **kwargs)
def add_path(self, *args, **kwargs):
self._add_to_queue(self._add_path, *args, **kwargs)
def add_java_param(self, *args, **kwargs):
self._add_to_queue(self._add_java_param, *args, **kwargs)
def update(self, *args, **kwargs):
self._add_to_queue(self._update, *args, **kwargs)
def _add_to_queue(self, *args, **kwargs):
self._queue.append((args[0], args[1:], kwargs))
def _set(self, env):
"""
:type env: dict
"""
for key in env:
key = str(key)
val = env[key]
if is_windows():
key = key.upper()
if key in self.data:
if val is None:
self.log.debug("Remove '%s' from environment", key)
self.data.pop(key)
else:
self.log.debug("Replace '%s' in environment", key)
self.data[key] = str(val)
else:
self._add({key: val}, '', finish=False)
def _add_path(self, pair, finish=False):
self._add(pair, os.pathsep, finish)
def _add_java_param(self, pair, finish=False):
self._add(pair, " ", finish)
def _update(self, env): # compatibility with taurus-server
self.set(env)
def _add(self, pair, separator, finish):
for key in pair:
val = pair[key]
key = str(key)
if is_windows():
key = key.upper()
if val is None:
self.log.debug("Skip empty variable '%s'", key)
return
val = str(val)
if key in self.data:
if finish:
self.data[key] += separator + val # add to the end
else:
self.data[key] = val + separator + self.data[key] # add to the beginning
else:
self.data[key] = str(val)
def get(self, key=None):
self._apply_queue()
if key:
key = str(key)
if is_windows():
key = key.upper()
return self.data.get(key, None)
else:
# full environment
return copy.deepcopy(self.data)
def _apply_queue(self):
self.data = {}
self._set(os.environ)
for method, args, kwargs in self._queue:
method(*args, **kwargs)
class FileReader(object):
SYS_ENCODING = locale.getpreferredencoding()
def __init__(self, filename="", file_opener=None, parent_logger=None):
self.fds = None
if parent_logger:
self.log = parent_logger.getChild(self.__class__.__name__)
else:
self.log = logging.getLogger(self.__class__.__name__)
if file_opener:
self.file_opener = file_opener # external method for opening of file
else:
self.file_opener = lambda f: open(f, mode='rb') # default mode is binary
# for non-trivial openers filename must be empty (more complicate than just open())
# it turns all regular file checks off, see is_ready()
self.name = filename
self.cp = 'utf-8' # default code page is utf-8
self.decoder = codecs.lookup(self.cp).incrementaldecoder()
self.fallback_decoder = codecs.lookup(self.SYS_ENCODING).incrementaldecoder(errors='ignore')
self.offset = 0
def _readlines(self, hint=None):
# get generator instead of list (in regular readlines())
length = 0
for line in self.fds:
yield line
if hint and hint > 0:
length += len(line)
if length >= hint:
return
def is_ready(self):
if not self.fds:
if self.name:
if not os.path.isfile(self.name):
self.log.debug("File not appeared yet: %s", self.name)
return False
if not os.path.getsize(self.name):
self.log.debug("File is empty: %s", self.name)
return False
self.log.debug("Opening file: %s", self.name)
# call opener regardless of the name value as it can use empty name as flag
self.fds = self.file_opener(self.name)
if self.fds:
self.name = self.fds.name
return True
def _decode(self, line, last_pass=False):
try:
return self.decoder.decode(line, final=last_pass)
except UnicodeDecodeError:
self.log.warning("Content encoding of '%s' doesn't match %s", self.name, self.cp)
self.cp = self.SYS_ENCODING
self.decoder = self.fallback_decoder
self.decoder.reset()
self.log.warning("Proposed code page: %s", self.cp)
return self.decoder.decode(line, final=last_pass)
def get_lines(self, size=-1, last_pass=False):
if self.is_ready():
if last_pass:
size = -1
self.fds.seek(self.offset)
for line in self._readlines(hint=size):
self.offset += len(line)
yield self._decode(line, last_pass)
def get_line(self):
line = ""
if self.is_ready():
self.fds.seek(self.offset)
line = self.fds.readline()
self.offset += len(line)
return self._decode(line)
def get_bytes(self, size=-1, last_pass=False, decode=True):
if self.is_ready():
if last_pass:
size = -1
self.fds.seek(self.offset)
_bytes = self.fds.read(size)
self.offset += len(_bytes)
if decode:
return self._decode(_bytes, last_pass)
else:
return _bytes
def __del__(self):
self.close()
def close(self):
if self.fds:
self.fds.close()
def ensure_is_dict(container, key, sub_key):
"""
Ensure that dict item is dict, convert if needed
:type container: dict or list
:type key: basestring or int
:type sub_key: basestring
:return:
"""
if isinstance(container, BetterDict):
container.get(key, force_set=True)
elif isinstance(container, dict): # todo: remove after fixing merge
container[key] = BetterDict()
if not isinstance(container[key], dict): # todo: replace dict with BetterDict after fixing merge
container[key] = BetterDict.from_dict({sub_key: container[key]})
return container[key]
class MultiPartForm(object):
"""
Accumulate the data to be used when posting a form.
http://blog.doughellmann.com/2009/07/
pymotw-urllib2-library-for-opening-urls.html
:type form_fields: list[str,str]
"""
def __init__(self):
self.form_fields = []
self.files = []
self.boundary = make_boundary()
def get_content_type(self):
""" returns content type """
return 'multipart/form-data; boundary=%s' % self.boundary
def add_field(self, name, value):
"""
Add a simple field to the form data.
:type name: str
:type value: str
"""
self.form_fields.append((name, value))
def add_file_as_string(self, fieldname, filename, body, mimetype=None):
""" add raw string file
:type fieldname: str
:type filename: str
:type body: str | bytes
:type mimetype: str
"""
default = 'application/octet-stream'
if mimetype is None:
mimetype = mimetypes.guess_type(filename)[0] or default
self.files.append((fieldname, filename, mimetype, body))
def add_file(self, fieldname, filename, file_handle=None, mimetype=None):
"""Add a file to be uploaded.
:type mimetype: str
:type file_handle: file
:type filename: str
:type fieldname: str
"""
if not file_handle:
with open(filename, 'rb') as fds:
body = fds.read()
filename = os.path.basename(filename)
else:
body = file_handle.read()
self.add_file_as_string(fieldname, filename, body, mimetype)
def __convert_to_list(self):
"""Return a string representing the form, including attached files."""
# Build a list of lists, each containing "lines" of the
# request. Each part is separated by a boundary string.
# Once the list is built, return a string where each
# line is separated by '\r\n'.
parts = []
part_boundary = '--' + self.boundary
# Add the form fields
parts.extend(
[part_boundary, 'Content-Disposition: form-data; name="%s"' % name, '', value, ]
for name, value in self.form_fields
)
# Add the files to upload
parts.extend(
[part_boundary,
'Content-Disposition: file; name="%s"; filename="%s"' % (field_name, filename),
'Content-Type: %s' % content_type, '', body]
for field_name, filename, content_type, body in self.files
)
# Flatten the list and add closing boundary marker,
# then return CR+LF separated data
flattened = list(itertools.chain(*parts))
flattened.append('--' + self.boundary + '--')
return flattened
def form_as_bytes(self):
"""
represents form contents as bytes
"""
result_list = []
for item in self.__convert_to_list():
# if (bytes (3.x), then no processing, just add, else - encode)
if isinstance(item, bytes):
result_list.append(item)
elif isinstance(item, str):
result_list.append(item.encode())
else:
raise TaurusInternalException("Unhandled form data type: %s" % type(item))
res_bytes = b("\r\n").join(result_list)
res_bytes += b("\r\n")
return res_bytes
def to_json(obj, indent=True):
"""
Convert object into indented json
:param indent: whether to generate indented JSON
:param obj: object to convert
:return:
"""
return json.dumps(obj, indent=indent, cls=ComplexEncoder)
class JSONDumpable(object):
"""
Marker class for json dumpable classes
"""
pass
class JSONConvertible(object):
@abstractmethod
def __json__(self):
"Convert class instance into JSON-dumpable structure (e.g. dict)"
pass
class ComplexEncoder(json.JSONEncoder):
"""
Magic class to help serialize in JSON any object.
"""
TYPES = (dict, list, tuple, str, int, float, bool, type(None))
def default(self, obj): # pylint: disable=method-hidden
"""
Filters out protected and private fields
:param obj:
:return:
"""
if self.__dumpable(obj):
res = {}
for key, val in iteritems(obj.__dict__):
if not self.__dumpable(val):
# logging.debug("Filtered out: %s.%s", key, val)
pass
elif key.startswith('_'):
# logging.debug("Filtered out: %s", key)
pass
else:
res[key] = val
return res
elif ComplexEncoder.__convertible(obj):
return obj.__json__()
else:
return None
@classmethod
def __dumpable(cls, obj):
"""
Re
:param obj:
:rtype: bool
"""
dumpable_types = tuple(cls.TYPES + (JSONDumpable,))
return isinstance(obj, dumpable_types)
@staticmethod
def __convertible(obj):
return isinstance(obj, JSONConvertible)
@classmethod
def of_basic_type(cls, val):
"""
Returns true if val is of basic type
:param val:
:return:
"""
return isinstance(val, cls.TYPES)
def humanize_time(secs):
"""
taken from http://testingreflections.com/node/6534
:param secs:
:return:
"""
mins, secs = divmod(secs, 60)
hours, mins = divmod(mins, 60)
return '%02d:%02d:%02d' % (hours, mins, secs)
def guess_csv_dialect(header, force_doublequote=False):
""" completely arbitrary fn to detect the delimiter
:param force_doublequote: bool
:type header: str
:rtype: csv.Dialect
"""
possible_delims = ",;\t"
dialect = csv.Sniffer().sniff(header, delimiters=possible_delims)
if force_doublequote:
dialect.doublequote = True
return dialect
def load_class(full_name):
"""
Load class by its full name like bzt.cli.CLI
:type full_name: str
:return:
:rtype: callable
"""
module_name = full_name[:full_name.rfind('.')]
class_name = full_name[full_name.rfind('.') + 1:]
LOG.debug("Importing module: %s", module_name)
module = __import__(module_name)
for mod in module_name.split('.')[1:]:
module = getattr(module, mod)
LOG.debug("Loading class: '%s' from %s", class_name, module)
return getattr(module, class_name)
def unzip(source_filename, dest_dir, rel_path=None):
"""
:param source_filename:
:param dest_dir:
:param rel_path:
:return:
"""
LOG.debug("Extracting %s to %s", source_filename, dest_dir)
with zipfile.ZipFile(source_filename) as zfd:
for member in zfd.infolist():