3 # © Copyright 2021-2022, Scott Gasch
5 """Helpers for unittests. Note that when you import this we
6 automatically wrap unittest.main() with a call to bootstrap.initialize
7 so that we getLogger config, commandline args, logging control,
8 etc... this works fine but it's a little hacky so caveat emptor.
24 from abc import ABC, abstractmethod
25 from typing import Any, Callable, Dict, List, Literal, Optional
27 import sqlalchemy as sa
34 logger = logging.getLogger(__name__)
35 cfg = config.add_commandline_args(f'Logging ({__file__})', 'Args related to function decorators')
37 '--unittests_ignore_perf',
40 help='Ignore unittest perf regression in @check_method_for_perf_regressions',
43 '--unittests_num_perf_samples',
46 help='The count of perf timing samples we need to see before blocking slow runs on perf grounds',
49 '--unittests_drop_perf_traces',
53 help='The identifier (i.e. file!test_fixture) for which we should drop all perf data',
56 '--unittests_persistance_strategy',
57 choices=['FILE', 'DATABASE'],
59 help='Should we persist perf data in a file or db?',
62 '--unittests_perfdb_filename',
65 default=f'{os.environ["HOME"]}/.python_unittest_performance_db',
66 help='File in which to store perf data (iff --unittests_persistance_strategy is FILE)',
69 '--unittests_perfdb_spec',
72 default='mariadb+pymysql://python_unittest:<PASSWORD>@db.house:3306/python_unittest_performance',
73 help='Db connection spec for perf data (iff --unittest_persistance_strategy is DATABASE)',
76 # >>> This is the hacky business, FYI. <<<
77 unittest.main = bootstrap.initialize(unittest.main)
80 class PerfRegressionDataPersister(ABC):
81 """A base class for a signature dealing with persisting perf
88 def load_performance_data(self, method_id: str) -> Dict[str, List[float]]:
92 def save_performance_data(self, method_id: str, data: Dict[str, List[float]]):
96 def delete_performance_data(self, method_id: str):
100 class FileBasedPerfRegressionDataPersister(PerfRegressionDataPersister):
101 """A perf regression data persister that uses files."""
103 def __init__(self, filename: str):
105 self.filename = filename
106 self.traces_to_delete: List[str] = []
108 def load_performance_data(self, method_id: str) -> Dict[str, List[float]]:
109 with open(self.filename, 'rb') as f:
110 return pickle.load(f)
112 def save_performance_data(self, method_id: str, data: Dict[str, List[float]]):
113 for trace in self.traces_to_delete:
117 with open(self.filename, 'wb') as f:
118 pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
120 def delete_performance_data(self, method_id: str):
121 self.traces_to_delete.append(method_id)
124 class DatabasePerfRegressionDataPersister(PerfRegressionDataPersister):
125 """A perf regression data persister that uses a database backend."""
127 def __init__(self, dbspec: str):
130 self.engine = sa.create_engine(self.dbspec)
131 self.conn = self.engine.connect()
133 def load_performance_data(self, method_id: str) -> Dict[str, List[float]]:
134 results = self.conn.execute(
135 sa.text(f'SELECT * FROM runtimes_by_function WHERE function = "{method_id}";')
137 ret: Dict[str, List[float]] = {method_id: []}
138 for result in results.all():
139 ret[method_id].append(result['runtime'])
143 def save_performance_data(self, method_id: str, data: Dict[str, List[float]]):
144 self.delete_performance_data(method_id)
145 for (mid, perf_data) in data.items():
146 sql = 'INSERT INTO runtimes_by_function (function, runtime) VALUES '
147 for perf in perf_data:
148 self.conn.execute(sql + f'("{mid}", {perf});')
150 def delete_performance_data(self, method_id: str):
151 sql = f'DELETE FROM runtimes_by_function WHERE function = "{method_id}"'
152 self.conn.execute(sql)
155 def check_method_for_perf_regressions(func: Callable) -> Callable:
157 This is meant to be used on a method in a class that subclasses
158 unittest.TestCase. When thus decorated it will time the execution
159 of the code in the method, compare it with a database of
160 historical perfmance, and fail the test with a perf-related
161 message if it has become too slow.
165 @functools.wraps(func)
166 def wrapper_perf_monitor(*args, **kwargs):
167 if config.config['unittests_ignore_perf']:
168 return func(*args, **kwargs)
170 if config.config['unittests_persistance_strategy'] == 'FILE':
171 filename = config.config['unittests_perfdb_filename']
172 helper = FileBasedPerfRegressionDataPersister(filename)
173 elif config.config['unittests_persistance_strategy'] == 'DATABASE':
174 dbspec = config.config['unittests_perfdb_spec']
175 dbspec = dbspec.replace('<PASSWORD>', scott_secrets.MARIADB_UNITTEST_PERF_PASSWORD)
176 helper = DatabasePerfRegressionDataPersister(dbspec)
178 raise Exception('Unknown/unexpected --unittests_persistance_strategy value')
180 func_id = function_utils.function_identifier(func)
181 func_name = func.__name__
182 logger.debug('Watching %s\'s performance...', func_name)
183 logger.debug('Canonical function identifier = "%s"', func_id)
186 perfdb = helper.load_performance_data(func_id)
187 except Exception as e:
189 msg = 'Unable to load perfdb; skipping it...'
194 # cmdline arg to forget perf traces for function
195 drop_id = config.config['unittests_drop_perf_traces']
196 if drop_id is not None:
197 helper.delete_performance_data(drop_id)
199 # Run the wrapped test paying attention to latency.
200 start_time = time.perf_counter()
201 value = func(*args, **kwargs)
202 end_time = time.perf_counter()
203 run_time = end_time - start_time
205 # See if it was unexpectedly slow.
206 hist = perfdb.get(func_id, [])
207 if len(hist) < config.config['unittests_num_perf_samples']:
208 hist.append(run_time)
209 logger.debug('Still establishing a perf baseline for %s', func_name)
211 stdev = statistics.stdev(hist)
212 logger.debug('For %s, performance stdev=%.2f', func_name, stdev)
214 logger.debug('For %s, slowest perf on record is %.2fs', func_name, slowest)
215 limit = slowest + stdev * 4
216 logger.debug('For %s, max acceptable runtime is %.2fs', func_name, limit)
217 logger.debug('For %s, actual observed runtime was %.2fs', func_name, run_time)
219 msg = f'''{func_id} performance has regressed unacceptably.
220 {slowest:f}s is the slowest runtime on record in {len(hist)} perf samples.
221 It just ran in {run_time:f}s which is 4+ stdevs slower than the slowest.
222 Here is the current, full db perf timing distribution:
228 slf = args[0] # Peek at the wrapped function's self ref.
229 slf.fail(msg) # ...to fail the testcase.
231 hist.append(run_time)
233 # Don't spam the database with samples; just pick a random
234 # sample from what we have and store that back.
235 n = min(config.config['unittests_num_perf_samples'], len(hist))
236 hist = random.sample(hist, n)
238 perfdb[func_id] = hist
239 helper.save_performance_data(func_id, perfdb)
242 return wrapper_perf_monitor
245 def check_all_methods_for_perf_regressions(prefix='test_'):
246 """Decorate unittests with this to pay attention to the perf of the
247 testcode and flag perf regressions. e.g.
249 import unittest_utils as uu
251 @uu.check_all_methods_for_perf_regressions()
252 class TestMyClass(unittest.TestCase):
254 def test_some_part_of_my_class(self):
259 def decorate_the_testcase(cls):
260 if issubclass(cls, unittest.TestCase):
261 for name, m in inspect.getmembers(cls, inspect.isfunction):
262 if name.startswith(prefix):
263 setattr(cls, name, check_method_for_perf_regressions(m))
264 logger.debug('Wrapping %s:%s.', cls.__name__, name)
267 return decorate_the_testcase
270 class RecordStdout(contextlib.AbstractContextManager):
272 Record what is emitted to stdout.
274 >>> with RecordStdout() as record:
275 ... print("This is a test!")
276 >>> print({record().readline()})
277 {'This is a test!\\n'}
281 def __init__(self) -> None:
283 self.destination = tempfile.SpooledTemporaryFile(mode='r+')
284 self.recorder: Optional[contextlib.redirect_stdout] = None
286 def __enter__(self) -> Callable[[], tempfile.SpooledTemporaryFile]:
287 self.recorder = contextlib.redirect_stdout(self.destination)
288 assert self.recorder is not None
289 self.recorder.__enter__()
290 return lambda: self.destination
292 def __exit__(self, *args) -> Literal[False]:
293 assert self.recorder is not None
294 self.recorder.__exit__(*args)
295 self.destination.seek(0)
299 class RecordStderr(contextlib.AbstractContextManager):
301 Record what is emitted to stderr.
304 >>> with RecordStderr() as record:
305 ... print("This is a test!", file=sys.stderr)
306 >>> print({record().readline()})
307 {'This is a test!\\n'}
311 def __init__(self) -> None:
313 self.destination = tempfile.SpooledTemporaryFile(mode='r+')
314 self.recorder: Optional[contextlib.redirect_stdout[Any]] = None
316 def __enter__(self) -> Callable[[], tempfile.SpooledTemporaryFile]:
317 self.recorder = contextlib.redirect_stderr(self.destination) # type: ignore
318 assert self.recorder is not None
319 self.recorder.__enter__()
320 return lambda: self.destination
322 def __exit__(self, *args) -> Literal[False]:
323 assert self.recorder is not None
324 self.recorder.__exit__(*args)
325 self.destination.seek(0)
329 class RecordMultipleStreams(contextlib.AbstractContextManager):
331 Record the output to more than one stream.
334 def __init__(self, *files) -> None:
336 self.files = [*files]
337 self.destination = tempfile.SpooledTemporaryFile(mode='r+')
338 self.saved_writes: List[Callable[..., Any]] = []
340 def __enter__(self) -> Callable[[], tempfile.SpooledTemporaryFile]:
342 self.saved_writes.append(f.write)
343 f.write = self.destination.write
344 return lambda: self.destination
346 def __exit__(self, *args) -> Literal[False]:
348 f.write = self.saved_writes.pop()
349 self.destination.seek(0)
353 if __name__ == '__main__':