Skip to content

Commit 0751ed9

Browse files
Less is More...
1 parent 8cb602f commit 0751ed9

File tree

4 files changed

+112
-36
lines changed

4 files changed

+112
-36
lines changed

pythonrepo/__init__.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818

1919

2020
__module__ = """pythonrepo"""
21-
"""This is pythonrepo __module Template"""
21+
"""This is pythonrepo module Template."""
2222

2323

2424
__version__ = """1.1.4"""
@@ -40,4 +40,3 @@
4040
baton.__cause__ = err
4141
raise baton
4242

43-

pythonrepo/pythonrepo.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020

2121
__module__ = """pythonrepo.pythonrepo"""
22+
"""This is pythonrepo component Template."""
2223

2324

2425
try:
@@ -132,5 +133,6 @@ def main(*argv):
132133

133134

134135
if __name__ in '__main__':
136+
# deepsource overlooks the readability of "if main" type code here. (See PTC-W0048)
135137
if (sys.argv is not None) and (len(sys.argv) >= 1):
136138
main(sys.argv[1:])

tests/profiling.py

Lines changed: 101 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
#! /usr/bin/env python
22
# -*- coding: utf-8 -*-
33

4-
# Python Repo Template
4+
# Python Test Repo Template
55
# ..................................
6-
# Copyright (c) 2017-2019, Kendrick Walls
6+
# Copyright (c) 2017-2022, Kendrick Walls
77
# ..................................
88
# Licensed under MIT (the "License");
99
# you may not use this file except in compliance with the License.
@@ -18,7 +18,7 @@
1818
# limitations under the License.
1919

2020

21-
# Third-party Acknowlegement:
21+
# Third-party Acknowledgement:
2222
# ..........................................
2323
# Some code (namely: class timewith, @do_cprofile, @do_line_profile) was modified/derived from:
2424
# https://github.com/zapier/profiling-python-like-a-boss/tree/1ab93a1154
@@ -30,36 +30,55 @@
3030

3131

3232
try:
33-
import os
3433
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:
3550
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!")
4453
except Exception as err:
4554
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)
4665

4766

4867
try:
4968
try:
5069
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), str('..'))))
5170
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
5372
print(str(''))
5473
print(str(type(ImportErr)))
5574
print(str(ImportErr))
5675
print(str((ImportErr.args)))
5776
print(str(''))
5877
ImportErr = None
5978
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")
6382

6483

6584
class timewith():
@@ -86,15 +105,43 @@ def __enter__(self):
86105

87106
def __exit__(self, type, value, traceback):
88107
self.checkpoint(str("finished"))
108+
pass
89109

90110

91111
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+
"""
93140
import functools
94141

95142
@functools.wraps(func)
96143
def timer_profile_func(*args, **kwargs):
97-
"""Wraps a function in timewith()"""
144+
"""Wraps a function in timewith() function."""
98145
theOutput = None
99146
with timewith(timer_name) as timer:
100147
timer.checkpoint(str("Start Timer"))
@@ -106,7 +153,36 @@ def timer_profile_func(*args, **kwargs):
106153

107154

108155
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+
"""
110186
def profiled_func(*args, **kwargs):
111187
profile = cProfile.Profile()
112188
try:
@@ -122,7 +198,7 @@ def profiled_func(*args, **kwargs):
122198
try: # noqa
123199
from line_profiler import LineProfiler
124200

125-
def do_profile(follow=None):
201+
def do_profile(follow=None): # pragma: no cover
126202
if follow is None:
127203
follow = []
128204

@@ -140,9 +216,9 @@ def profiled_func(*args, **kwargs):
140216
return profiled_func
141217
return inner
142218

143-
except ImportError:
219+
except ImportError: # pragma: no cover
144220
def do_profile(follow=None):
145-
"Helpful if you accidentally leave in production!"
221+
"""Helpful if you accidentally leave in production!"""
146222
if follow is None:
147223
follow = []
148224

@@ -153,16 +229,15 @@ def nothing(*args, **kwargs):
153229
return inner
154230

155231

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."""
158234
raise NotImplementedError("CRITICAL - test profiling main() not implemented. yet?")
159235

160236

161-
if __name__ in '__main__':
237+
if __name__ in '__main__': # pragma: no cover
162238
exitcode = 3
163239
try:
164240
exitcode = main(sys.argv[1:])
165241
finally:
166242
exit(exitcode)
167243

168-

tests/test_usage.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def getPythonCommand():
5252

5353

5454
def buildPythonCommand(args=None):
55-
"""Function for building backend subprocess command line"""
55+
"""Function for building backend subprocess command line."""
5656
theArgs = args
5757
# you need to change this to the name of your project
5858
__project__ = str("pythonrepo")
@@ -80,7 +80,7 @@ def buildPythonCommand(args=None):
8080

8181

8282
def checkPythonCommand(args=None, stderr=None):
83-
"""Function for backend subprocess check_output command like testing with coverage support"""
83+
"""Function for backend subprocess check_output command like testing with coverage support."""
8484
theOutput = None
8585
try:
8686
taintArgs = buildPythonCommand(args)
@@ -163,11 +163,11 @@ class BasicUsageTestSuite(unittest.TestCase):
163163
"""Basic functional test cases."""
164164

165165
def test_absolute_truth_and_meaning(self):
166-
"""Insanity Test. if ( is true ) """
166+
"""Insanity Test. if ( is true ) usage."""
167167
assert True
168168

169169
def test_syntax(self):
170-
"""Test case importing code. if ( import is not None ) """
170+
"""Test case importing code. if ( import is not None ) usage."""
171171
theResult = False
172172
try:
173173
from .context import pythonrepo
@@ -181,7 +181,7 @@ def test_syntax(self):
181181
assert theResult
182182

183183
def test_template_case(self):
184-
"""Test case template for: python -m pythonrepo.* --version """
184+
"""Test case template for: python -m pythonrepo.* --version usage."""
185185
theResult = False
186186
thepython = getPythonCommand()
187187
if (thepython is not None):
@@ -220,7 +220,7 @@ def test_template_case(self):
220220
assert theResult
221221

222222
def test_profile_template_case(self):
223-
"""Test case template for profiling"""
223+
"""Test case template for profiling."""
224224
theResult = False
225225
thepython = getPythonCommand()
226226
if (thepython is not None):
@@ -259,7 +259,7 @@ def test_profile_template_case(self):
259259

260260
@unittest.expectedFailure
261261
def test_fail_template_case(self):
262-
"""Test case template for profiling"""
262+
"""Test case template for profiling."""
263263
theResult = False
264264
thepython = getPythonCommand()
265265
if (thepython is not None):
@@ -298,7 +298,7 @@ def test_fail_template_case(self):
298298

299299
@unittest.expectedFailure
300300
def test_bad_template_case(self):
301-
"""Test case template for profiling"""
301+
"""Test case template for profiling."""
302302
theResult = False
303303
thepython = getPythonCommand()
304304
if (thepython is not None):

0 commit comments

Comments
 (0)