1
1
#! /usr/bin/env python
2
2
# -*- coding: utf-8 -*-
3
3
4
- # Python Repo Template
4
+ # Python Test Repo Template
5
5
# ..................................
6
- # Copyright (c) 2017-2019 , Kendrick Walls
6
+ # Copyright (c) 2017-2022 , Kendrick Walls
7
7
# ..................................
8
8
# Licensed under MIT (the "License");
9
9
# you may not use this file except in compliance with the License.
18
18
# limitations under the License.
19
19
20
20
21
- # Third-party Acknowlegement :
21
+ # Third-party Acknowledgement :
22
22
# ..........................................
23
23
# Some code (namely: class timewith, @do_cprofile, @do_line_profile) was modified/derived from:
24
24
# https://github.com/zapier/profiling-python-like-a-boss/tree/1ab93a1154
30
30
31
31
32
32
try :
33
- import os
34
33
import sys
34
+ if sys .__name__ is None : # pragma: no branch
35
+ raise ImportError ("[CWE-758] OMG! we could not import sys! ABORT. ABORT." )
36
+ except Exception as err : # pragma: no branch
37
+ raise ImportError (err )
38
+
39
+
40
+ try :
41
+ if 'os' not in sys .modules :
42
+ import os
43
+ else : # pragma: no branch
44
+ os = sys .modules ["""os""" ]
45
+ except Exception : # pragma: no branch
46
+ raise ImportError ("[CWE-758] OS Failed to import." )
47
+
48
+
49
+ try :
35
50
import time
36
- import cProfile
37
- for keyModule in [os , sys , time , cProfile ]:
38
- if keyModule .__name__ is None :
39
- raise NotImplementedError (
40
- str ("OMG! We could not import the {}!" ).format (
41
- str (keyModule )
42
- )
43
- )
51
+ if time .__name__ is None : # pragma: no branch
52
+ raise NotImplementedError ("[CWE-440] We could not import time. Are we in the speed-force!" )
44
53
except Exception as err :
45
54
raise ImportError (err )
55
+ exit (3 )
56
+
57
+
58
+ try :
59
+ import cProfile
60
+ if cProfile .__name__ is None : # pragma: no branch
61
+ raise NotImplementedError ("[CWE-440] We could not import cProfile. ABORT!" )
62
+ except Exception as err : # pragma: no branch
63
+ raise ImportError (err )
64
+ exit (3 )
46
65
47
66
48
67
try :
49
68
try :
50
69
sys .path .insert (0 , os .path .abspath (os .path .join (os .path .dirname (__file__ ), str ('..' ))))
51
70
sys .path .insert (0 , os .path .abspath (os .path .join (os .path .dirname (__file__ ), str ('.' ))))
52
- except Exception as ImportErr :
71
+ except Exception as ImportErr : # pragma: no branch
53
72
print (str ('' ))
54
73
print (str (type (ImportErr )))
55
74
print (str (ImportErr ))
56
75
print (str ((ImportErr .args )))
57
76
print (str ('' ))
58
77
ImportErr = None
59
78
del ImportErr
60
- raise ImportError (str ("Profile module failed completely." ))
61
- except Exception :
62
- raise ImportError ("Failed to import test profiling" )
79
+ raise ImportError (str ("[CWE-758] Profile module failed completely." ))
80
+ except Exception : # pragma: no branch
81
+ raise ImportError ("[CWE-440] Failed to import test profiling" )
63
82
64
83
65
84
class timewith ():
@@ -86,15 +105,43 @@ def __enter__(self):
86
105
87
106
def __exit__ (self , type , value , traceback ):
88
107
self .checkpoint (str ("finished" ))
108
+ pass
89
109
90
110
91
111
def do_time_profile (func , timer_name = "time_profile" ):
92
- """Runs a function with a timer"""
112
+ """Run a function with a timer.
113
+
114
+ Time Testing:
115
+
116
+ First some test fixtures:
117
+
118
+ >>> import tests.context as context
119
+ >>> from context import profiling as profiling
120
+ >>>
121
+
122
+ Testcase 0: test the time_profile.
123
+
124
+ >>> def doWork():
125
+ ... \" ""Does some work.\" ""
126
+ ... for i in range(0, 42):
127
+ ... print(str("Do Task {}").format(int(i)))
128
+ >>>
129
+ >>> profiling.do_time_profile(
130
+ ... doWork,
131
+ ... timer_name=str("work time test")
132
+ ... )() #doctest: -DONT_ACCEPT_BLANKLINE, +ELLIPSIS
133
+ work...Start Timer...
134
+ ...Do Task...
135
+ work...Stop Timer...
136
+ work...took ... seconds
137
+ >>>
138
+
139
+ """
93
140
import functools
94
141
95
142
@functools .wraps (func )
96
143
def timer_profile_func (* args , ** kwargs ):
97
- """Wraps a function in timewith()"""
144
+ """Wraps a function in timewith() function. """
98
145
theOutput = None
99
146
with timewith (timer_name ) as timer :
100
147
timer .checkpoint (str ("Start Timer" ))
@@ -106,7 +153,36 @@ def timer_profile_func(*args, **kwargs):
106
153
107
154
108
155
def do_cprofile (func ):
109
- """use built-in profiler to profile."""
156
+ """Use built-in profiler to profile.
157
+
158
+ Time Testing:
159
+
160
+ First some test fixtures:
161
+
162
+ >>> import tests.context as context
163
+ >>> from context import profiling as profiling
164
+ >>>
165
+
166
+ Testcase 0: test the time_profile.
167
+
168
+ >>> def doWork():
169
+ ... \" ""Does some work.\" ""
170
+ ... for i in range(0, 42):
171
+ ... print(str("Do Task {}").format(int(i)))
172
+ >>>
173
+ >>> profiling.do_cprofile(
174
+ ... doWork
175
+ ... )() #doctest: -DONT_ACCEPT_BLANKLINE, +ELLIPSIS
176
+ Do Task 0...Do Task 10...Do Task 20...Do Task 30...Do Task 40...
177
+ ...function calls in ... seconds...Ordered by: standard name...
178
+ ...ncalls tottime percall cumtime percall filename:lineno(function)...
179
+ ...<...>:1(doWork)...{built-in method builtins.print}...
180
+ <BLANKLINE>
181
+ <BLANKLINE>
182
+ >>>
183
+
184
+
185
+ """
110
186
def profiled_func (* args , ** kwargs ):
111
187
profile = cProfile .Profile ()
112
188
try :
@@ -122,7 +198,7 @@ def profiled_func(*args, **kwargs):
122
198
try : # noqa
123
199
from line_profiler import LineProfiler
124
200
125
- def do_profile (follow = None ):
201
+ def do_profile (follow = None ): # pragma: no cover
126
202
if follow is None :
127
203
follow = []
128
204
@@ -140,9 +216,9 @@ def profiled_func(*args, **kwargs):
140
216
return profiled_func
141
217
return inner
142
218
143
- except ImportError :
219
+ except ImportError : # pragma: no cover
144
220
def do_profile (follow = None ):
145
- "Helpful if you accidentally leave in production!"
221
+ """ Helpful if you accidentally leave in production!"" "
146
222
if follow is None :
147
223
follow = []
148
224
@@ -153,16 +229,15 @@ def nothing(*args, **kwargs):
153
229
return inner
154
230
155
231
156
- def main (argv = None ):
157
- """The Main Event makes no sense to remediation ."""
232
+ def main (argv = None ): # pragma: no cover
233
+ """The Main Event makes no sense to profiling ."""
158
234
raise NotImplementedError ("CRITICAL - test profiling main() not implemented. yet?" )
159
235
160
236
161
- if __name__ in '__main__' :
237
+ if __name__ in '__main__' : # pragma: no cover
162
238
exitcode = 3
163
239
try :
164
240
exitcode = main (sys .argv [1 :])
165
241
finally :
166
242
exit (exitcode )
167
243
168
-
0 commit comments