FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
allure-python/allure-python-commons/src/utils.py at master · QAAAAAAAA/allure-python · GitHub
QAAAAAAAA
/
allure-python
Public
forked from
allure-framework/allure-python
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
allure-python
/
allure-python-commons
/
src
/
utils.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
385 lines (292 loc) · 9.34 KB
Breadcrumbs
allure-python
/
allure-python-commons
/
src
/
utils.py
Copy path
File metadata and controls
385 lines (292 loc) · 9.34 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import
os
import
string
import
sys
import
time
import
uuid
import
json
import
socket
import
inspect
import
hashlib
import
platform
import
threading
import
traceback
import
collections
from
traceback
import
format_exception_only
def
md5
(
*
args
):
m
=
hashlib
.
md5
()
for
arg
in
args
:
if
not
isinstance
(
arg
,
bytes
):
if
not
isinstance
(
arg
,
str
):
arg
=
repr
(
arg
)
arg
=
arg
.
encode
(
'utf-8'
)
m
.
update
(
arg
)
return
m
.
hexdigest
()
def
uuid4
():
return
str
(
uuid
.
uuid4
())
def
now
():
return
int
(
round
(
1000
*
time
.
time
()))
def
platform_label
():
major_version
,
*
_
=
platform
.
python_version_tuple
()
implementation
=
platform
.
python_implementation
().
lower
()
return
f'
{
implementation
}
{
major_version
}
'
def
thread_tag
():
return
'{0}-{1}'
.
format
(
os
.
getpid
(),
threading
.
current_thread
().
name
)
def
host_tag
():
return
socket
.
gethostname
()
def
represent
(
item
):
"""
>>> represent(None)
'None'
>>> represent(123)
'123'
>>> represent('hi')
"'hi'"
>>> represent('привет')
"'привет'"
>>> represent(bytearray([0xd0, 0xbf])) # doctest: +ELLIPSIS
"<... 'bytearray'>"
>>> from struct import pack
>>> represent(pack('h', 0x89))
"<class 'bytes'>"
>>> represent(int)
"<class 'int'>"
>>> represent(represent) # doctest: +ELLIPSIS
'<function represent at ...>'
>>> represent([represent]) # doctest: +ELLIPSIS
'[<function represent at ...>]'
>>> class ClassWithName:
... pass
>>> represent(ClassWithName)
"<class 'utils.ClassWithName'>"
"""
if
isinstance
(
item
,
str
):
return
f"'
{
item
}
'"
elif
isinstance
(
item
, (
bytes
,
bytearray
)):
return
repr
(
type
(
item
))
else
:
return
repr
(
item
)
def
func_parameters
(
func
,
*
args
,
**
kwargs
):
"""
>>> def helper(func):
... def wrapper(*args, **kwargs):
... params = func_parameters(func, *args, **kwargs)
... print(list(params.items()))
... return func(*args, **kwargs)
... return wrapper
>>> @helper
... def args(a, b):
... pass
>>> args(1, 2)
[('a', '1'), ('b', '2')]
>>> args(*(1,2))
[('a', '1'), ('b', '2')]
>>> args(1, b=2)
[('a', '1'), ('b', '2')]
>>> @helper
... def kwargs(a=1, b=2):
... pass
>>> kwargs()
[('a', '1'), ('b', '2')]
>>> kwargs(a=3, b=4)
[('a', '3'), ('b', '4')]
>>> kwargs(b=4, a=3)
[('a', '3'), ('b', '4')]
>>> kwargs(a=3)
[('a', '3'), ('b', '2')]
>>> kwargs(b=4)
[('a', '1'), ('b', '4')]
>>> @helper
... def args_kwargs(a, b, c=3, d=4):
... pass
>>> args_kwargs(1, 2)
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
>>> args_kwargs(1, 2, d=5)
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '5')]
>>> args_kwargs(1, 2, 5, 6)
[('a', '1'), ('b', '2'), ('c', '5'), ('d', '6')]
>>> args_kwargs(1, b=2)
[('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]
>>> @helper
... def varargs(*a):
... pass
>>> varargs()
[]
>>> varargs(1, 2)
[('a', '(1, 2)')]
>>> @helper
... def keywords(**a):
... pass
>>> keywords()
[]
>>> keywords(a=1, b=2)
[('a', '1'), ('b', '2')]
>>> @helper
... def args_varargs(a, b, *c):
... pass
>>> args_varargs(1, 2)
[('a', '1'), ('b', '2')]
>>> args_varargs(1, 2, 2)
[('a', '1'), ('b', '2'), ('c', '(2,)')]
>>> @helper
... def args_kwargs_varargs(a, b, c=3, **d):
... pass
>>> args_kwargs_varargs(1, 2)
[('a', '1'), ('b', '2'), ('c', '3')]
>>> args_kwargs_varargs(1, 2, 4, d=5, e=6)
[('a', '1'), ('b', '2'), ('c', '4'), ('d', '5'), ('e', '6')]
>>> @helper
... def args_kwargs_varargs_keywords(a, b=2, *c, **d):
... pass
>>> args_kwargs_varargs_keywords(1)
[('a', '1'), ('b', '2')]
>>> args_kwargs_varargs_keywords(1, 2, 4, d=5, e=6)
[('a', '1'), ('b', '2'), ('c', '(4,)'), ('d', '5'), ('e', '6')]
>>> class Class:
... @staticmethod
... @helper
... def static_args(a, b):
... pass
...
... @classmethod
... @helper
... def method_args(cls, a, b):
... pass
...
... @helper
... def args(self, a, b):
... pass
>>> cls = Class()
>>> cls.args(1, 2)
[('a', '1'), ('b', '2')]
>>> cls.method_args(1, 2)
[('a', '1'), ('b', '2')]
>>> cls.static_args(1, 2)
[('a', '1'), ('b', '2')]
"""
parameters
=
{}
arg_spec
=
inspect
.
getfullargspec
(
func
)
arg_order
=
list
(
arg_spec
.
args
)
args_dict
=
dict
(
zip
(
arg_spec
.
args
,
args
))
if
arg_spec
.
defaults
:
kwargs_defaults_dict
=
dict
(
zip
(
arg_spec
.
args
[
-
len
(
arg_spec
.
defaults
):],
arg_spec
.
defaults
))
parameters
.
update
(
kwargs_defaults_dict
)
if
arg_spec
.
varargs
:
arg_order
.
append
(
arg_spec
.
varargs
)
varargs
=
args
[
len
(
arg_spec
.
args
):]
parameters
.
update
({
arg_spec
.
varargs
:
varargs
}
if
varargs
else
{})
if
arg_spec
.
args
and
arg_spec
.
args
[
0
]
in
[
'cls'
,
'self'
]:
args_dict
.
pop
(
arg_spec
.
args
[
0
],
None
)
if
kwargs
:
if
sys
.
version_info
<
(
3
,
7
):
# Sort alphabetically as old python versions does
# not preserve call order for kwargs.
arg_order
.
extend
(
sorted
(
list
(
kwargs
.
keys
())))
else
:
# Keep py3.7 behaviour to preserve kwargs order
arg_order
.
extend
(
list
(
kwargs
.
keys
()))
parameters
.
update
(
kwargs
)
parameters
.
update
(
args_dict
)
items
=
parameters
.
items
()
sorted_items
=
sorted
(
map
(
lambda
kv
: (
kv
[
0
],
represent
(
kv
[
1
])),
items
),
key
=
lambda
x
:
arg_order
.
index
(
x
[
0
])
)
return
collections
.
OrderedDict
(
sorted_items
)
def
format_traceback
(
exc_traceback
):
return
''
.
join
(
traceback
.
format_tb
(
exc_traceback
))
if
exc_traceback
else
None
def
format_exception
(
etype
,
value
):
"""
>>> import sys
>>> try:
... assert False, 'Привет'
... except AssertionError:
... etype, e, _ = sys.exc_info()
... format_exception(etype, e) # doctest: +ELLIPSIS
'AssertionError: ...
\\
n'
>>> try:
... assert False, 'Привет'
... except AssertionError:
... etype, e, _ = sys.exc_info()
... format_exception(etype, e) # doctest: +ELLIPSIS
'AssertionError: ...
\\
n'
>>> try:
... compile("bla 'Привет'", "fake.py", "exec")
... except SyntaxError:
... etype, e, _ = sys.exc_info()
... format_exception(etype, e) # doctest: +ELLIPSIS
' File "fake.py", line 1...SyntaxError: invalid syntax
\\
n'
>>> try:
... compile("bla 'Привет'", "fake.py", "exec")
... except SyntaxError:
... etype, e, _ = sys.exc_info()
... format_exception(etype, e) # doctest: +ELLIPSIS
' File "fake.py", line 1...SyntaxError: invalid syntax
\\
n'
>>> from hamcrest import assert_that, equal_to
>>> try:
... assert_that('left', equal_to('right'))
... except AssertionError:
... etype, e, _ = sys.exc_info()
... format_exception(etype, e) # doctest: +ELLIPSIS
"AssertionError:
\\
nExpected:...but:..."
>>> try:
... assert_that('left', equal_to('right'))
... except AssertionError:
... etype, e, _ = sys.exc_info()
... format_exception(etype, e) # doctest: +ELLIPSIS
"AssertionError:
\\
nExpected:...but:..."
"""
return
'
\n
'
.
join
(
format_exception_only
(
etype
,
value
))
if
etype
or
value
else
None
def
get_testplan
():
planned_tests
=
[]
file_path
=
os
.
environ
.
get
(
"ALLURE_TESTPLAN_PATH"
)
if
file_path
and
os
.
path
.
exists
(
file_path
):
with
open
(
file_path
,
'r'
)
as
plan_file
:
plan
=
json
.
load
(
plan_file
)
planned_tests
=
plan
.
get
(
"tests"
, [])
return
planned_tests
class
SafeFormatter
(
string
.
Formatter
):
"""
Format string safely - skip any non-passed keys
>>> f = SafeFormatter().format
Make sure we don't broke default formatting behaviour
>>> f("literal string")
'literal string'
>>> f("{expected.format}", expected=str)
"<method 'format' of 'str' objects>"
>>> f("{expected[0]}", expected=["value"])
'value'
>>> f("{expected[0]}", expected=123)
Traceback (most recent call last):
...
TypeError: 'int' object is not subscriptable
>>> f("{expected[0]}", expected=[])
Traceback (most recent call last):
...
IndexError: list index out of range
>>> f("{expected.format}", expected=int)
Traceback (most recent call last):
...
AttributeError: type object 'int' has no attribute 'format'
Check that unexpected keys do not cause some errors
>>> f("{expected} {unexpected}", expected="value")
'value {unexpected}'
>>> f("{unexpected[0]}", expected=["value"])
'{unexpected[0]}'
>>> f("{unexpected.format}", expected=str)
'{unexpected.format}'
"""
class
SafeKeyOrIndexError
(
Exception
):
pass
def
get_field
(
self
,
field_name
,
args
,
kwargs
):
try
:
return
super
().
get_field
(
field_name
,
args
,
kwargs
)
except
self
.
SafeKeyOrIndexError
:
return
"{"
+
field_name
+
"}"
,
field_name
def
get_value
(
self
,
key
,
args
,
kwargs
):
try
:
return
super
().
get_value
(
key
,
args
,
kwargs
)
except
(
KeyError
,
IndexError
):
raise
self
.
SafeKeyOrIndexError
()
Back
|
FazBrowse Home
|
New Git URL