Debian Codegraph @

tests/test_codetiming.py

raw
1 """Tests for codetiming.Timer
2
3 Based on the Pytest test runner
4 """
5 # Standard library imports
6 import math
7 import re
8 import time
9
10 # Third party imports
11 import pytest
12
13 # Codetiming imports
14 from codetiming import Timer, TimerError
15
16 #
17 # Constants, functions, and classes used by tests
18 #
19 TIME_PREFIX = "Wasted time:"
20 TIME_MESSAGE = f"{TIME_PREFIX} {{:.4f}} seconds"
21 RE_TIME_MESSAGE = re.compile(TIME_PREFIX + r" 0\.\d{4} seconds")
22 RE_TIME_MESSAGE_INITIAL_TEXT_TRUE = re.compile(
23 f"Timer started\n{TIME_PREFIX}" + r" 0\.\d{4} seconds"
24 )
25 RE_TIME_MESSAGE_INITIAL_TEXT_CUSTOM = re.compile(
26 f"Starting the party\n{TIME_PREFIX}" + r" 0\.\d{4} seconds"
27 )
28
29
30 def waste_time(num=1000):
31 """Just waste a little bit of time."""
32 sum(n**2 for n in range(num))
33
34
35 @Timer(text=TIME_MESSAGE)
36 def decorated_timewaste(num=1000):
37 """Just waste a little bit of time."""
38 sum(n**2 for n in range(num))
39
40
41 @Timer(text=TIME_MESSAGE, initial_text=True)
42 def decorated_timewaste_initial_text_true(num=1000):
43 """Just waste a little bit of time."""
44 sum(n**2 for n in range(num))
45
46
47 @Timer(text=TIME_MESSAGE, initial_text="Starting the party")
48 def decorated_timewaste_initial_text_custom(num=1000):
49 """Just waste a little bit of time."""
50 sum(n**2 for n in range(num))
51
52
53 @Timer(name="accumulator", text=TIME_MESSAGE)
54 def accumulated_timewaste(num=1000):
55 """Just waste a little bit of time."""
56 sum(n**2 for n in range(num))
57
58
59 class CustomLogger:
60 """Simple class used to test custom logging capabilities in Timer."""
61
62 def __init__(self):
63 """Store log messages in the .messages attribute."""
64 self.messages = ""
65
66 def __call__(self, message):
67 """Add a log message to the .messages attribute."""
68 self.messages += message
69
70
71 #
72 # Tests
73 #
74 def test_timer_as_decorator(capsys):
75 """Test that decorated function prints timing information."""
76 decorated_timewaste()
77
78 stdout, stderr = capsys.readouterr()
79 assert RE_TIME_MESSAGE.match(stdout)
80 assert stdout.count("\n") == 1
81 assert stderr == ""
82
83
84 def test_timer_as_context_manager(capsys):
85 """Test that timed context prints timing information."""
86 with Timer(text=TIME_MESSAGE):
87 waste_time()
88
89 stdout, stderr = capsys.readouterr()
90 assert RE_TIME_MESSAGE.match(stdout)
91 assert stdout.count("\n") == 1
92 assert stderr == ""
93
94
95 def test_explicit_timer(capsys):
96 """Test that timed section prints timing information."""
97 t = Timer(text=TIME_MESSAGE)
98 t.start()
99 waste_time()
100 t.stop()
101
102 stdout, stderr = capsys.readouterr()
103 assert RE_TIME_MESSAGE.match(stdout)
104 assert stdout.count("\n") == 1
105 assert stderr == ""
106
107
108 def test_error_if_timer_not_running():
109 """Test that timer raises error if it is stopped before started."""
110 t = Timer(text=TIME_MESSAGE)
111 with pytest.raises(TimerError):
112 t.stop()
113
114
115 def test_access_timer_object_in_context(capsys):
116 """Test that we can access the timer object inside a context."""
117 with Timer(text=TIME_MESSAGE) as t:
118 assert isinstance(t, Timer)
119 assert t.text.startswith(TIME_PREFIX)
120 _, _ = capsys.readouterr() # Do not print log message to standard out
121
122
123 def test_custom_logger():
124 """Test that we can use a custom logger."""
125 logger = CustomLogger()
126 with Timer(text=TIME_MESSAGE, logger=logger):
127 waste_time()
128 assert RE_TIME_MESSAGE.match(logger.messages)
129
130
131 def test_timer_without_text(capsys):
132 """Test that timer with logger=None does not print anything."""
133 with Timer(logger=None):
134 waste_time()
135
136 stdout, stderr = capsys.readouterr()
137 assert stdout == ""
138 assert stderr == ""
139
140
141 def test_accumulated_decorator(capsys):
142 """Test that decorated timer can accumulate."""
143 accumulated_timewaste()
144 accumulated_timewaste()
145
146 stdout, stderr = capsys.readouterr()
147 lines = stdout.strip().split("\n")
148 assert len(lines) == 2
149 assert RE_TIME_MESSAGE.match(lines[0])
150 assert RE_TIME_MESSAGE.match(lines[1])
151 assert stderr == ""
152
153
154 def test_accumulated_context_manager(capsys):
155 """Test that context manager timer can accumulate."""
156 t = Timer(name="accumulator", text=TIME_MESSAGE)
157 with t:
158 waste_time()
159 with t:
160 waste_time()
161
162 stdout, stderr = capsys.readouterr()
163 lines = stdout.strip().split("\n")
164 assert len(lines) == 2
165 assert RE_TIME_MESSAGE.match(lines[0])
166 assert RE_TIME_MESSAGE.match(lines[1])
167 assert stderr == ""
168
169
170 def test_accumulated_explicit_timer(capsys):
171 """Test that explicit timer can accumulate."""
172 t = Timer(name="accumulated_explicit_timer", text=TIME_MESSAGE)
173 total = 0
174 t.start()
175 waste_time()
176 total += t.stop()
177 t.start()
178 waste_time()
179 total += t.stop()
180
181 stdout, stderr = capsys.readouterr()
182 lines = stdout.strip().split("\n")
183 assert len(lines) == 2
184 assert RE_TIME_MESSAGE.match(lines[0])
185 assert RE_TIME_MESSAGE.match(lines[1])
186 assert stderr == ""
187 assert total == Timer.timers["accumulated_explicit_timer"]
188
189
190 def test_error_if_restarting_running_timer():
191 """Test that restarting a running timer raises an error."""
192 t = Timer(text=TIME_MESSAGE)
193 t.start()
194 with pytest.raises(TimerError):
195 t.start()
196
197
198 def test_last_starts_as_nan():
199 """Test that .last attribute is initialized as nan."""
200 t = Timer()
201 assert math.isnan(t.last)
202
203
204 def test_timer_sets_last():
205 """Test that .last attribute is properly set."""
206 with Timer() as t:
207 time.sleep(0.02)
208
209 assert t.last >= 0.02
210
211
212 def test_using_name_in_text_without_explicit_timer(capsys):
213 """Test that the name of the timer can be referenced in the text."""
214 name = "NamedTimer"
215 with Timer(name=name, text="{name}: {:.2f}"):
216 waste_time()
217
218 stdout, stderr = capsys.readouterr()
219 assert re.match(f"{name}: " + r"0\.\d{2}", stdout)
220 assert stderr == ""
221
222
223 def test_using_name_in_text_with_explicit_timer(capsys):
224 """Test that timer name and seconds attribute can be referenced in the text."""
225 name = "NamedTimer"
226 with Timer(name=name, text="{name}: {seconds:.2f}"):
227 waste_time()
228
229 stdout, stderr = capsys.readouterr()
230 assert re.match(f"{name}: " + r"0\.\d{2}", stdout.strip())
231 assert stderr == ""
232
233
234 def test_using_minutes_attribute_in_text(capsys):
235 """Test that timer can report its duration in minutes."""
236 with Timer(text="{minutes:.1f} minutes"):
237 waste_time()
238
239 stdout, stderr = capsys.readouterr()
240 assert stdout.strip() == "0.0 minutes"
241 assert stderr == ""
242
243
244 def test_using_milliseconds_attribute_in_text(capsys):
245 """Test that timer can report its duration in milliseconds."""
246 with Timer(text="{milliseconds:.0f} {seconds:.3f}"):
247 waste_time()
248
249 stdout, stderr = capsys.readouterr()
250 milliseconds, _, seconds = stdout.partition(" ")
251 assert int(milliseconds) == round(float(seconds) * 1000)
252 assert stderr == ""
253
254
255 def test_text_formatting_function(capsys):
256 """Test that text can be formatted by a separate function."""
257
258 def format_text(seconds):
259 """Function that returns a formatted text"""
260 return f"Function: {seconds + 1:.0f}"
261
262 with Timer(text=format_text):
263 waste_time()
264
265 stdout, stderr = capsys.readouterr()
266 assert stdout.strip() == "Function: 1"
267 assert not stderr.strip()
268
269
270 def test_text_formatting_class(capsys):
271 """Test that text can be formatted by a separate class."""
272
273 class TextFormatter:
274 """Class that behaves like a formatted text."""
275
276 def __init__(self, seconds):
277 """Initialize with number of seconds"""
278 self.seconds = seconds
279
280 def __str__(self):
281 """Represent the class as a formatted text"""
282 return f"Class: {self.seconds + 1:.0f}"
283
284 with Timer(text=TextFormatter):
285 waste_time()
286
287 stdout, stderr = capsys.readouterr()
288 assert stdout.strip() == "Class: 1"
289 assert not stderr.strip()
290
291
292 def test_timers_cleared():
293 """Test that timers can be cleared."""
294 with Timer(name="timer_to_be_cleared"):
295 waste_time()
296
297 assert "timer_to_be_cleared" in Timer.timers
298 Timer.timers.clear()
299 assert not Timer.timers
300
301
302 def test_running_cleared_timers():
303 """Test that timers can still be run after they're cleared."""
304 t = Timer(name="timer_to_be_cleared")
305 Timer.timers.clear()
306
307 accumulated_timewaste()
308 with t:
309 waste_time()
310
311 assert "accumulator" in Timer.timers
312 assert "timer_to_be_cleared" in Timer.timers
313
314
315 def test_timers_stats():
316 """Test that we can get basic statistics from timers."""
317 name = "timer_with_stats"
318 t = Timer(name=name)
319 for num in range(5, 10):
320 with t:
321 waste_time(num=100 * num)
322
323 stats = Timer.timers
324 assert stats.total(name) == stats[name]
325 assert stats.count(name) == 5
326 assert stats.min(name) <= stats.median(name) <= stats.max(name)
327 assert stats.mean(name) >= stats.min(name)
328 assert stats.stdev(name) >= 0
329
330
331 def test_stats_missing_timers():
332 """Test that getting statistics from non-existent timers raises exception."""
333 with pytest.raises(KeyError):
334 Timer.timers.count("non_existent_timer")
335
336 with pytest.raises(KeyError):
337 Timer.timers.stdev("non_existent_timer")
338
339
340 def test_setting_timers_exception():
341 """Test that setting .timers items raises exception."""
342 with pytest.raises(TypeError):
343 Timer.timers["set_timer"] = 1.23
344
345
346 def test_timer_as_decorator_with_initial_text_true(capsys):
347 """Test that decorated function prints at start with default initial text."""
348 decorated_timewaste_initial_text_true()
349
350 stdout, stderr = capsys.readouterr()
351 assert RE_TIME_MESSAGE_INITIAL_TEXT_TRUE.match(stdout)
352 assert stdout.count("\n") == 2
353 assert stderr == ""
354
355
356 def test_timer_as_context_manager_with_initial_text_true(capsys):
357 """Test that timed context prints at start with default initial text."""
358 with Timer(text=TIME_MESSAGE, initial_text=True):
359 waste_time()
360
361 stdout, stderr = capsys.readouterr()
362 assert RE_TIME_MESSAGE_INITIAL_TEXT_TRUE.match(stdout)
363 assert stdout.count("\n") == 2
364 assert stderr == ""
365
366
367 def test_explicit_timer_with_initial_text_true(capsys):
368 """Test that timed section prints at start with default initial text."""
369 t = Timer(text=TIME_MESSAGE, initial_text=True)
370 t.start()
371 waste_time()
372 t.stop()
373
374 stdout, stderr = capsys.readouterr()
375 assert RE_TIME_MESSAGE_INITIAL_TEXT_TRUE.match(stdout)
376 assert stdout.count("\n") == 2
377 assert stderr == ""
378
379
380 def test_timer_as_decorator_with_initial_text_custom(capsys):
381 """Test that decorated function prints at start with custom initial text."""
382 decorated_timewaste_initial_text_custom()
383
384 stdout, stderr = capsys.readouterr()
385 assert RE_TIME_MESSAGE_INITIAL_TEXT_CUSTOM.match(stdout)
386 assert stdout.count("\n") == 2
387 assert stderr == ""
388
389
390 def test_timer_as_context_manager_with_initial_text_custom(capsys):
391 """Test that timed context prints at start with custom initial text."""
392 with Timer(text=TIME_MESSAGE, initial_text="Starting the party"):
393 waste_time()
394
395 stdout, stderr = capsys.readouterr()
396 assert RE_TIME_MESSAGE_INITIAL_TEXT_CUSTOM.match(stdout)
397 assert stdout.count("\n") == 2
398 assert stderr == ""
399
400
401 def test_explicit_timer_with_initial_text_custom(capsys):
402 """Test that timed section prints at start with custom initial text."""
403 t = Timer(text=TIME_MESSAGE, initial_text="Starting the party")
404 t.start()
405 waste_time()
406 t.stop()
407
408 stdout, stderr = capsys.readouterr()
409 assert RE_TIME_MESSAGE_INITIAL_TEXT_CUSTOM.match(stdout)
410 assert stdout.count("\n") == 2
411 assert stderr == ""
412
413
414 def test_explicit_timer_with_initial_text_true_with_name(capsys):
415 """Test with default initial text referencing timer name."""
416 t = Timer(name="named", text=TIME_MESSAGE, initial_text=True)
417 t.start()
418 waste_time()
419 t.stop()
420
421 stdout, stderr = capsys.readouterr()
422 assert re.match(
423 f"Timer named started\n{TIME_PREFIX}" + r" 0\.\d{4} seconds", stdout
424 )
425 assert stdout.count("\n") == 2
426 assert stderr == ""
427
428
429 def test_explicit_timer_with_initial_text_with_name(capsys):
430 """Test with custom initial text referencing timer name."""
431 t = Timer(name="the party", text=TIME_MESSAGE, initial_text="Starting {name}")
432 t.start()
433 waste_time()
434 t.stop()
435
436 stdout, stderr = capsys.readouterr()
437 assert RE_TIME_MESSAGE_INITIAL_TEXT_CUSTOM.match(stdout)
438 assert stdout.count("\n") == 2
439 assert stderr == ""