speed up ==, hash, <, >, <=, and >= for plain_data
[nmutil.git] / src / nmutil / get_test_path.py
1 # SPDX-License-Identifier: LGPL-3-or-later
2 # Copyright 2021 Jacob Lifshay
3
4 # Funded by NLnet Assure Programme 2021-02-052, https://nlnet.nl/assure part
5 # of Horizon 2020 EU Programme 957073.
6
7 import weakref
8 from pathlib import Path
9
10
11 class RunCounter:
12 def __init__(self):
13 self.__run_counts = {}
14 """dict mapping self.next() keys to the next int value returned by
15 self.next()"""
16
17 def next(self, k):
18 """get a incrementing run counter for a `str` key `k`. returns an `int`."""
19 retval = self.__run_counts.get(k, 0)
20 self.__run_counts[k] = retval + 1
21 return retval
22
23 __RUN_COUNTERS = {}
24 """dict mapping object ids (int) to a tuple of a weakref.ref to that
25 object, and the corresponding RunCounter"""
26
27 @staticmethod
28 def get(obj):
29 k = id(obj)
30 t = RunCounter.__RUN_COUNTERS
31 try:
32 return t[k][1]
33 except KeyError:
34 retval = RunCounter()
35
36 def on_finalize(obj):
37 del t[k]
38 t[k] = weakref.ref(obj, on_finalize), retval
39 return retval
40
41
42 def get_test_path(test_case, base_path):
43 """get the `Path` for a particular unittest.TestCase instance
44 (`test_case`). base_path is either a str or a path-like."""
45 count = RunCounter.get(test_case).next(test_case.id())
46 return Path(base_path) / test_case.id() / str(count)