-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtesting_functions.py
More file actions
372 lines (295 loc) · 9.79 KB
/
testing_functions.py
File metadata and controls
372 lines (295 loc) · 9.79 KB
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
"""
Function for checking if a measured value falls within the target range.
"""
import logging
import multiprocessing as mp
import platform
import sys
import time
logger = logging.getLogger()
def test_measurement(
name: str,
measured: float,
min_val: float | None = None,
max_val: float | None = None,
tolerance: float | None = None,
target: float | None = None,
units: str = "",
) -> bool:
"""
Log a standardized test result and automatically determine PASS/FAIL.
The function evaluates the measured value against one of the following
conditions (in priority order):
1. Range check (min_val / max_val)
2. Target with tolerance
3. Exact target match
Returns
-------
bool
True if the test passed, False if it failed.
"""
status: bool | None = None
deviation: float | None = None
if min_val is not None or max_val is not None:
lower = min_val if min_val is not None else float("-inf")
upper = max_val if max_val is not None else float("inf")
status = lower <= measured <= upper
elif target is not None and tolerance is not None:
lower = target - tolerance
upper = target + tolerance
status = lower <= measured <= upper
deviation = abs(measured - target)
elif target is not None:
status = measured == target
deviation = abs(measured - target)
else:
logger.warning("Test '%s' has no comparison criteria.", name)
return False
status_str = "PASS" if status else "FAIL"
parts: list[str] = [name, status_str]
parts.append(f"Measured: {measured}{units}")
if target is not None and tolerance is not None:
parts.append(f"Target: {target}±{tolerance}{units}")
if deviation is not None:
parts.append(f"Dev: {round(deviation, 6)}{units}")
elif target is not None:
parts.append(f"Target: {target}{units}")
if deviation is not None:
parts.append(f"Dev: {round(deviation, 6)}{units}")
elif min_val is not None or max_val is not None:
lower_str = f"{min_val}{units}" if min_val is not None else f"-inf{units}"
upper_str = f"{max_val}{units}" if max_val is not None else f"inf{units}"
parts.append(f"Range: {lower_str} to {upper_str}")
message = " | ".join(parts)
logger.info("%s", message)
return status
def _timeout_worker(queue, func, args, kwargs):
"""Internal worker executed in a separate process."""
try:
result = func(*args, **kwargs)
queue.put(("result", result))
except Exception as e:
queue.put(("error", e))
def run_with_timeout(func, timeout: float, *args, **kwargs):
"""
Run a function with a time limit. If the function exceeds the
timeout, the process is terminated.
Parameters
----------
func : callable
Function to execute.
timeout : float
Maximum runtime in seconds.
*args
Positional arguments passed to the function.
**kwargs
Keyword arguments passed to the function.
Returns
-------
Any
Function return value.
Raises
------
TimeoutError
If the function exceeds the allowed time.
Examples
--------
>>> def slow():
... import time
... time.sleep(5)
... return "done"
>>> run_with_timeout(slow, 2)
TimeoutError
"""
queue = mp.Queue()
process = mp.Process(
target=_timeout_worker,
args=(queue, func, args, kwargs)
)
process.start()
process.join(timeout)
if process.is_alive():
process.terminate()
process.join()
raise TimeoutError(f"Function '{func.__name__}' exceeded {timeout} seconds")
if not queue.empty():
status, value = queue.get()
if status == "error":
raise value
return value
return None
def _retry_timeout_worker(queue, func, args, kwargs):
"""Worker process that executes the target function."""
try:
result = func(*args, **kwargs)
queue.put(("result", result))
except Exception as e:
queue.put(("error", e))
def retry_with_timeout(
func,
*args,
timeout: float,
retries: int = 3,
delay: float = 0,
timeout_return=None,
exceptions=(Exception,),
**kwargs,
):
"""
Execute a function with retry and timeout protection.
The function runs in a separate process so it can be forcefully
terminated if it exceeds the specified timeout.
Parameters
----------
func : callable
Function to execute.
*args
Positional arguments passed to the function.
timeout : float
Maximum execution time per attempt (seconds).
retries : int, default=3
Number of attempts before giving up.
delay : float, default=0
Delay between retries (seconds).
timeout_return : Any, optional
Value returned if all attempts time out. If None, a TimeoutError is raised.
exceptions : tuple[type], default=(Exception,)
Exceptions that should trigger a retry.
**kwargs
Keyword arguments passed to the function.
Returns
-------
Any
Result of the function.
Raises
------
TimeoutError
If all attempts time out and timeout_return is None.
Exception
Re-raises the last exception if retries are exhausted.
"""
last_exception = None
for attempt in range(1, retries + 1):
logger.info(
"Executing %s (attempt %d/%d)",
func.__name__,
attempt,
retries,
)
queue = mp.Queue()
process = mp.Process(
target=_retry_timeout_worker,
args=(queue, func, args, kwargs),
)
start_time = time.perf_counter()
process.start()
process.join(timeout)
runtime = time.perf_counter() - start_time
if process.is_alive():
process.terminate()
process.join()
logger.warning(
"%s timed out after %.2f seconds (attempt %d/%d)",
func.__name__,
timeout,
attempt,
retries,
)
if attempt == retries:
if timeout_return is not None:
logger.error(
"%s exceeded timeout after %d attempts. Returning fallback value.",
func.__name__,
retries,
)
return timeout_return
raise TimeoutError(
f"{func.__name__} exceeded {timeout}s after {retries} attempts"
)
else:
if not queue.empty():
status, value = queue.get()
if status == "result":
logger.info(
"%s completed successfully in %.3f seconds",
func.__name__,
runtime,
)
return value
if status == "error":
if isinstance(value, exceptions):
last_exception = value
logger.warning(
"%s raised %s: %s (attempt %d/%d)",
func.__name__,
type(value).__name__,
value,
attempt,
retries,
)
else:
logger.exception(
"%s raised unexpected exception",
func.__name__,
)
raise value
if attempt < retries and delay > 0:
logger.debug("Retrying %s in %.2f seconds", func.__name__, delay)
time.sleep(delay)
if last_exception:
logger.error(
"%s failed after %d attempts",
func.__name__,
retries,
)
raise last_exception
return timeout_return
def run_test_sequence() -> None:
"""
Test execution framework.
Flow:
1. Attempt system initialization and connection (critical). If this fails, testing stops immediately.
2. Run test sequence. Any exception stops further tests.
3. If initialization succeeded, always attempt system deinitialization to return hardware to a safe state.
All steps should be designed so that if they fail, they raise an error.
"""
initialized = False
try:
step = "INIT"
logger.info("STEP: %s | START", step)
# init()
initialized = True
logger.info("STEP: %s | COMPLETED", step)
except Exception as e:
logger.critical("STEP: %s | CRITICAL ERROR", step)
logger.critical("%s. Verify hardware is safe before continuing.", e)
return
try:
step = "CONNECT"
logger.info("STEP: %s | START", step)
# connect()
initialized = True
logger.info("STEP: %s | COMPLETED", step)
except Exception as e:
logger.error("STEP: %s | ERROR", step)
logger.error("%s", e)
return
try:
step = "TEST1"
logger.info("STEP: %s | START", step)
# test1()
logger.info("STEP: %s | COMPLETED", step)
except Exception as e:
logger.warning("STEP: %s | FAILURE", step)
logger.warning("%s", e)
# --- DEINIT PHASE ---
finally:
if initialized:
step = "DEINIT"
try:
logger.info("STEP: %s | START", step)
# deinit()
logger.info("STEP: %s | COMPLETED", step)
except Exception as e:
logger.critical("STEP: %s | CRITICAL ERROR", step)
logger.critical("%s. Verify hardware is safe before continuing.", e)