| 1 |
import sys |
| 2 |
import time |
| 3 |
from contextlib import contextmanager |
| 4 |
from functools import wraps |
| 5 |
from resource import RUSAGE_SELF, getrusage |
| 6 |
from typing import Any, Callable, Iterator, Optional |
| 7 |
|
| 8 |
from pytest import skip |
| 9 |
|
| 10 |
|
| 11 |
def current_cpu_usage() -> float: |
| 12 |
rusage = getrusage(RUSAGE_SELF) |
| 13 |
return rusage.ru_utime + rusage.ru_stime |
| 14 |
|
| 15 |
|
| 16 |
@contextmanager |
| 17 |
def assert_cpu_usage(lt: float, verbose: bool = False) -> Iterator: |
| 18 |
""" |
| 19 |
Execute wrapped block, asserting CPU utilization was less than ``lt``%. |
| 20 |
|
| 21 |
:param float lt: CPU use percentage above which failure will occur. |
| 22 |
:param bool verbose: Whether to print out the calculated percentage. |
| 23 |
""" |
| 24 |
start_usage = current_cpu_usage() |
| 25 |
start_time = time.time() |
| 26 |
yield |
| 27 |
end_usage = current_cpu_usage() |
| 28 |
end_time = time.time() |
| 29 |
|
| 30 |
usage_diff = end_usage - start_usage |
| 31 |
time_diff = end_time - start_time |
| 32 |
|
| 33 |
if time_diff == 0: # Apparently possible! |
| 34 |
time_diff = 0.000001 |
| 35 |
|
| 36 |
percentage = (usage_diff / time_diff) * 100.0 |
| 37 |
|
| 38 |
if verbose: |
| 39 |
print("Used {0:.2}% CPU over {1:.2}s".format(percentage, time_diff)) |
| 40 |
|
| 41 |
assert percentage < lt |
| 42 |
|
| 43 |
|
| 44 |
def only_utf8(f: Callable) -> Callable: |
| 45 |
""" |
| 46 |
Decorator causing tests to skip if local shell pipes aren't UTF-8. |
| 47 |
""" |
| 48 |
|
| 49 |
# TODO: use actual test selection labels or whatever nose has |
| 50 |
@wraps(f) |
| 51 |
def inner(*args: Any, **kwargs: Any) -> Optional[Any]: |
| 52 |
if getattr(sys.stdout, "encoding", None) == "UTF-8": |
| 53 |
return f(*args, **kwargs) |
| 54 |
# TODO: could remove this so they show green, but figure yellow is more |
| 55 |
# appropriate |
| 56 |
skip() |
| 57 |
|
| 58 |
return inner |