52bd53066d2254f87888a9c2b549ee3d5776b36d
[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 import weakref
5 from pathlib import Path
6
7
8 class RunCounter:
9 def __init__(self):
10 self.__run_counts = {}
11 """dict mapping self.next() keys to the next int value returned by
12 self.next()"""
13
14 def next(self, k):
15 """get a incrementing run counter for a `str` key `k`. returns an `int`."""
16 retval = self.__run_counts.get(k, 0)
17 self.__run_counts[k] = retval + 1
18 return retval
19
20 __RUN_COUNTERS = {}
21 """dict mapping object ids (int) to a tuple of a weakref.ref to that
22 object, and the corresponding RunCounter"""
23
24 @staticmethod
25 def get(obj):
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 def get_test_path(test_case, base_path):
40 """get the `Path` for a particular unittest.TestCase instance
41 (`test_case`). base_path is either a str or a path-like."""
42 count = RunCounter.get(test_case).next(test_case.id())
43 return Path(base_path) / test_case.id() / str(count)