speed up ==, hash, <, >, <=, and >= for plain_data
[nmutil.git] / src / nmutil / get_test_path.py
1 # SPDX-License-Identifier: LGPL-3-or-later
2 # See Notices.txt for copyright information
3
4 from os import PathLike
5 from typing import Dict, Tuple, Union
6 import unittest
7 import weakref
8 from pathlib import Path
9
10
11 class RunCounter:
12 __run_counts: Dict[str, int]
13
14 def __init__(self) -> None:
15 self.__run_counts = {}
16
17 def next(self, k: str) -> int:
18 retval = self.__run_counts.get(k, 0)
19 self.__run_counts[k] = retval + 1
20 return retval
21
22 __RUN_COUNTERS: Dict[int, Tuple[weakref.ref, "RunCounter"]] = {}
23
24 @staticmethod
25 def get(obj: object) -> "RunCounter":
26 k = id(obj)
27 t = RunCounter.__RUN_COUNTERS
28 try:
29 return t[k][1]
30 except KeyError:
31 retval = RunCounter()
32
33 def on_finalize(obj):
34 del t[k]
35 t[k] = weakref.ref(obj, on_finalize), retval
36 return retval
37
38
39 _StrPath = Union[str, PathLike]
40
41
42 def get_test_path(test_case: unittest.TestCase, base_path: _StrPath) -> Path:
43 count = RunCounter.get(test_case).next(test_case.id())
44 return Path(base_path) / test_case.id() / str(count)