codecraftai-testbase 1.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. ccai/factories/py.typed +0 -0
  2. ccai/factories/testbasedefaulttypefactory.py +25 -0
  3. ccai/testbase/__init__.py +63 -0
  4. ccai/testbase/breakpoints.py +110 -0
  5. ccai/testbase/cli/__init__.py +13 -0
  6. ccai/testbase/cli/cmdtree/agents/__init__.py +28 -0
  7. ccai/testbase/cli/cmdtree/agents/config/__init__.py +24 -0
  8. ccai/testbase/cli/cmdtree/agents/config/extract.py +94 -0
  9. ccai/testbase/cli/cmdtree/agents/formatting.py +71 -0
  10. ccai/testbase/cli/cmdtree/agents/jsosparser.py +119 -0
  11. ccai/testbase/cli/cmdtree/agents/pathresolver.py +34 -0
  12. ccai/testbase/cli/cmdtree/agents/summary/__init__.py +26 -0
  13. ccai/testbase/cli/cmdtree/agents/summary/compare.py +128 -0
  14. ccai/testbase/cli/cmdtree/agents/summary/extract.py +91 -0
  15. ccai/testbase/cli/cmdtree/agents/testresult/__init__.py +28 -0
  16. ccai/testbase/cli/cmdtree/agents/testresult/extract.py +77 -0
  17. ccai/testbase/cli/cmdtree/agents/testresult/failures.py +73 -0
  18. ccai/testbase/cli/cmdtree/agents/testresult/list.py +63 -0
  19. ccai/testbase/cli/cmdtree/services/__init__.py +27 -0
  20. ccai/testbase/cli/cmdtree/services/results.py +66 -0
  21. ccai/testbase/cli/cmdtree/testing/__init__.py +30 -0
  22. ccai/testbase/cli/cmdtree/testing/jobs.py +175 -0
  23. ccai/testbase/cli/cmdtree/testing/query.py +131 -0
  24. ccai/testbase/cli/cmdtree/testing/run.py +263 -0
  25. ccai/testbase/cli/cmdtree/utilities/__init__.py +28 -0
  26. ccai/testbase/cli/cmdtree/utilities/timestamp.py +33 -0
  27. ccai/testbase/cli/options.py +370 -0
  28. ccai/testbase/cli/testbase_command.py +64 -0
  29. ccai/testbase/cli/utilities.py +31 -0
  30. ccai/testbase/configuration.py +324 -0
  31. ccai/testbase/constraints.py +998 -0
  32. ccai/testbase/coupling/__init__.py +569 -0
  33. ccai/testbase/coupling/basecoupling.py +69 -0
  34. ccai/testbase/coupling/configurationcoupling.py +138 -0
  35. ccai/testbase/coupling/integrationcoupling.py +842 -0
  36. ccai/testbase/coupling/validatorcoupling.py +127 -0
  37. ccai/testbase/debuggingext.py +281 -0
  38. ccai/testbase/debuglogging.py +407 -0
  39. ccai/testbase/debugports.py +469 -0
  40. ccai/testbase/declaration/__init__.py +13 -0
  41. ccai/testbase/declaration/attachments.py +222 -0
  42. ccai/testbase/declaration/originations.py +217 -0
  43. ccai/testbase/declaration/parameterization.py +160 -0
  44. ccai/testbase/declaration/registrations.py +476 -0
  45. ccai/testbase/diagnostic_level.py +197 -0
  46. ccai/testbase/diagnostic_streaming.py +1534 -0
  47. ccai/testbase/diagnostics.py +1685 -0
  48. ccai/testbase/entrypoints.py +485 -0
  49. ccai/testbase/environment.py +162 -0
  50. ccai/testbase/errors/testruntimeouterror.py +50 -0
  51. ccai/testbase/expressions.py +355 -0
  52. ccai/testbase/factories.py +277 -0
  53. ccai/testbase/factoryprotocols.py +35 -0
  54. ccai/testbase/features.py +913 -0
  55. ccai/testbase/initialize.py +210 -0
  56. ccai/testbase/injection/__init__.py +25 -0
  57. ccai/testbase/injection/injectiongroup.py +493 -0
  58. ccai/testbase/injection/injectionmoment.py +155 -0
  59. ccai/testbase/injection/injectionregistry.py +823 -0
  60. ccai/testbase/injection/injectionscope.py +2589 -0
  61. ccai/testbase/injection/introspection.py +514 -0
  62. ccai/testbase/markers.py +665 -0
  63. ccai/testbase/mocking.py +4856 -0
  64. ccai/testbase/origins/__init__.py +13 -0
  65. ccai/testbase/origins/resourceorigin.py +110 -0
  66. ccai/testbase/origins/validatororigin.py +111 -0
  67. ccai/testbase/output/__init__.py +17 -0
  68. ccai/testbase/output/outputcontext.py +201 -0
  69. ccai/testbase/output/runmetadata.py +184 -0
  70. ccai/testbase/properties/__init__.py +40 -0
  71. ccai/testbase/properties/assumptions.py +56 -0
  72. ccai/testbase/properties/decorators.py +173 -0
  73. ccai/testbase/properties/propertyrunner.py +449 -0
  74. ccai/testbase/properties/strategies.py +1592 -0
  75. ccai/testbase/properties/unittestsupport.py +87 -0
  76. ccai/testbase/py.typed +0 -0
  77. ccai/testbase/queries.py +95 -0
  78. ccai/testbase/resourcelifespan.py +24 -0
  79. ccai/testbase/results/__init__.py +35 -0
  80. ccai/testbase/results/exceptions.py +60 -0
  81. ccai/testbase/results/filtering/__init__.py +26 -0
  82. ccai/testbase/results/filtering/resultfilter.py +570 -0
  83. ccai/testbase/results/model/__init__.py +32 -0
  84. ccai/testbase/results/model/buildinfo.py +54 -0
  85. ccai/testbase/results/model/checkresult.py +183 -0
  86. ccai/testbase/results/model/forwardinginfo.py +30 -0
  87. ccai/testbase/results/model/jobcontainer.py +32 -0
  88. ccai/testbase/results/model/jobinfo.py +91 -0
  89. ccai/testbase/results/model/nestedprogressinfo.py +211 -0
  90. ccai/testbase/results/model/pipelineinfo.py +51 -0
  91. ccai/testbase/results/model/progressaggregator.py +551 -0
  92. ccai/testbase/results/model/progresscode.py +29 -0
  93. ccai/testbase/results/model/progressdelivery.py +51 -0
  94. ccai/testbase/results/model/progressinfo.py +84 -0
  95. ccai/testbase/results/model/progresstype.py +24 -0
  96. ccai/testbase/results/model/renderinfo.py +30 -0
  97. ccai/testbase/results/model/resultcode.py +28 -0
  98. ccai/testbase/results/model/resultcontainer.py +95 -0
  99. ccai/testbase/results/model/resultnode.py +258 -0
  100. ccai/testbase/results/model/resulttype.py +34 -0
  101. ccai/testbase/results/model/streaminginfo.py +111 -0
  102. ccai/testbase/results/model/taskinggroup.py +85 -0
  103. ccai/testbase/results/model/taskingresult.py +297 -0
  104. ccai/testbase/results/model/testcontainer.py +35 -0
  105. ccai/testbase/results/model/testresult.py +170 -0
  106. ccai/testbase/results/recorders/__init__.py +31 -0
  107. ccai/testbase/results/recorders/csvresultrecorder.py +414 -0
  108. ccai/testbase/results/recorders/jsonresultrecorder.py +467 -0
  109. ccai/testbase/results/recorders/resultrecorder.py +1472 -0
  110. ccai/testbase/results/recorders/stdoutresultrecorder.py +70 -0
  111. ccai/testbase/results/recorders/xmlresultrecorder.py +305 -0
  112. ccai/testbase/results/utilities.py +141 -0
  113. ccai/testbase/sequencing/__init__.py +13 -0
  114. ccai/testbase/sequencing/sequencermodulescope.py +96 -0
  115. ccai/testbase/sequencing/sequencerscopebase.py +91 -0
  116. ccai/testbase/sequencing/sequencersessionscope.py +84 -0
  117. ccai/testbase/sequencing/sequencertestscope.py +249 -0
  118. ccai/testbase/sequencing/sequencertestsetupscope.py +86 -0
  119. ccai/testbase/sequencing/testactivity.py +111 -0
  120. ccai/testbase/sequencing/testsequencer.py +3072 -0
  121. ccai/testbase/server/__init__.py +13 -0
  122. ccai/testbase/server/resultserver.py +599 -0
  123. ccai/testbase/sources/__init__.py +13 -0
  124. ccai/testbase/sources/configurationsource.py +32 -0
  125. ccai/testbase/sources/integrationsource.py +29 -0
  126. ccai/testbase/sources/resourcesource.py +27 -0
  127. ccai/testbase/sources/sourcebase.py +71 -0
  128. ccai/testbase/sources/unknownsource.py +30 -0
  129. ccai/testbase/sources/validatorsource.py +28 -0
  130. ccai/testbase/tandem/__init__.py +13 -0
  131. ccai/testbase/tandem/validators.py +286 -0
  132. ccai/testbase/testcollector.py +230 -0
  133. ccai/testbase/testgroup.py +54 -0
  134. ccai/testbase/testjob.py +600 -0
  135. ccai/testbase/testref.py +64 -0
  136. ccai/testbase/utilities.py +472 -0
  137. ccai/testbase/verification.py +768 -0
  138. codecraftai_testbase-1.3.0.dist-info/METADATA +99 -0
  139. codecraftai_testbase-1.3.0.dist-info/RECORD +142 -0
  140. codecraftai_testbase-1.3.0.dist-info/WHEEL +4 -0
  141. codecraftai_testbase-1.3.0.dist-info/entry_points.txt +3 -0
  142. codecraftai_testbase-1.3.0.dist-info/licenses/LICENSE.md +204 -0
@@ -0,0 +1,64 @@
1
+ """
2
+ .. module:: ccai.testbase.testref
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module for testref.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+
10
+
11
+ __author__ = "Myron Walker"
12
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
13
+ __credits__ = []
14
+
15
+
16
+ from typing import Any, List, Optional, OrderedDict
17
+
18
+ from types import FunctionType
19
+
20
+ import collections
21
+ import inspect
22
+
23
+ from ccai.testbase.injection.injectionmoment import InjectionMoment
24
+
25
+ class TestRef(InjectionMoment):
26
+ """
27
+ The :class:`TestRef` objects are used to refer to a reference to a test. We use :class:`TestRef` instances
28
+ to reference the tests that are going to be run so we can control the lifespan of test case instances
29
+ and control our memory consumption during test runs with large collections of test cases.
30
+
31
+ The :class:`TestRef` object allows us to delay the creation of test runtime instance data and state until it is
32
+ necessary to instantiate it and allows us to cleanup the runtime instance and state as soon as it is no longer
33
+ being used.
34
+ """
35
+
36
+ def __init__(self, testfunc: FunctionType, monikers: Optional[List[str]] = None,
37
+ pivots: Optional[OrderedDict[str, Any]] = None, is_async: Optional[bool] = None):
38
+ """
39
+ Initializes the test reference object.
40
+
41
+ :param FunctionType testfunc: The test function being referenced.
42
+ :param List[str] monikers: Optional list of monikers associated with the test.
43
+ :param OrderedDict[str, Any] pivots: Optional mapping describing pivot variations.
44
+ :param bool is_async: Optional flag indicating whether the test function is async.
45
+
46
+ :returns: ``None``
47
+ :rtype: None
48
+ """
49
+ if monikers is None:
50
+ monikers = []
51
+
52
+ if pivots is None:
53
+ pivots = collections.OrderedDict()
54
+
55
+ if is_async is None:
56
+ is_async = inspect.iscoroutinefunction(testfunc)
57
+
58
+ super().__init__(testfunc, monikers=monikers, pivots=pivots)
59
+ self._is_async = is_async
60
+ return
61
+
62
+ @property
63
+ def is_async(self) -> bool:
64
+ return self._is_async
@@ -0,0 +1,472 @@
1
+ """
2
+ .. module:: ccai.testbase.utilities
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module for utilities.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+
10
+
11
+ __author__ = "Myron Walker"
12
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
13
+ __credits__ = []
14
+
15
+
16
+ from typing import Dict, Union
17
+
18
+ import fnmatch
19
+ import json
20
+ import os
21
+
22
+ from ccai.errors.exceptions import ConfigurationError, UnSupportedPlatformError
23
+ from ccai.xmodules.ximport import import_file
24
+
25
+ def catalog_tree(rootdir: str, ignore_dirs=[]):
26
+ """
27
+ Adds json catalog files to a file system tree to help provide directory
28
+ services to javascript in html files.
29
+ """
30
+ for dirpath, dirnames, filenames in os.walk(rootdir, topdown=True):
31
+ dir_base_name = os.path.basename(dirpath)
32
+ if dir_base_name not in ignore_dirs:
33
+
34
+ for igdir in ignore_dirs:
35
+ if igdir in dirnames:
36
+ dirnames.remove(igdir)
37
+
38
+ catalog = {
39
+ "files": filenames,
40
+ "folders": dirnames
41
+ }
42
+
43
+ catalogfile = os.path.join(dirpath, "catalog.json")
44
+ with open(catalogfile, 'w') as cf:
45
+ json.dump(catalog, cf, indent=4)
46
+
47
+ return
48
+
49
+ def create_testpack_key(testpack_cls):
50
+ mtpkey = testpack_cls.__module__ + "@" + testpack_cls.__name__
51
+ return mtpkey
52
+
53
+ def _build_platforms_module_name(root: str, dirpath: str) -> str:
54
+ root = os.path.abspath(root)
55
+ dirpath = os.path.abspath(dirpath)
56
+
57
+ root_pkg = os.path.basename(root)
58
+ rel_dir = os.path.relpath(dirpath, root)
59
+
60
+ if rel_dir in (".", ""):
61
+ modname = "{}.{}".format(root_pkg, "__platforms__")
62
+ else:
63
+ rel_mod = rel_dir.replace(os.path.sep, ".")
64
+ modname = "{}.{}.{}".format(root_pkg, rel_mod, "__platforms__")
65
+
66
+ return modname
67
+
68
+ def _is_platform_supported(root: str, dirpath: str, platforms_cache: Dict[str, bool]) -> bool:
69
+ dirpath = os.path.abspath(dirpath)
70
+
71
+ if dirpath in platforms_cache:
72
+ return platforms_cache[dirpath]
73
+
74
+ platforms_file = os.path.join(dirpath, "__platforms__.py")
75
+ if not os.path.exists(platforms_file):
76
+ platforms_cache[dirpath] = True
77
+ return True
78
+
79
+ modname = _build_platforms_module_name(root, dirpath)
80
+
81
+ try:
82
+ import_file(modname, platforms_file)
83
+ except UnSupportedPlatformError:
84
+ platforms_cache[dirpath] = False
85
+ return False
86
+ # If the exception is unexpected, just let it bubble
87
+
88
+ platforms_cache[dirpath] = True
89
+
90
+ return True
91
+
92
+ def collect_python_modules_for_tests(search_dir: str, root: str, platforms_cache: Dict[str, bool], max_depth=None):
93
+ """
94
+ Walks a directory tree of python modules and collects the names
95
+ of all of the python module files or .py files. This method allows
96
+ for python namespaces by not forcing the root folder to contain a
97
+ __init__.py file. The search will skip any directory whose
98
+ __platforms__.py file raises UnSupportedPlatformError.
99
+
100
+ :params searchdir: The root directory to search when collecting python modules.
101
+ :params root: The root directory used to calculate module names for __platforms__.py files.
102
+ :params platforms_cache: A cache of directory paths to platform support decisions.
103
+ :params max_depth: The maximum depth to search for python modules. If this is None
104
+ then the entire directory tree will be searched. If this is
105
+ an integer then the search will be limited to that depth.
106
+
107
+ :returns: A list of the full paths to the python module files.
108
+ """
109
+ pyfiles = []
110
+
111
+ search_dir = os.path.abspath(search_dir)
112
+ root = os.path.abspath(root)
113
+ search_dir_len = len(search_dir)
114
+
115
+ if not _is_platform_supported(root, search_dir, platforms_cache):
116
+ return pyfiles
117
+
118
+ for root_dir, dirnames, files in os.walk(search_dir, topdown=True):
119
+
120
+ if not _is_platform_supported(root, root_dir, platforms_cache):
121
+ dirnames[:] = []
122
+ continue
123
+
124
+ if max_depth is not None:
125
+ dir_leaf = root_dir[search_dir_len:].strip(os.path.sep)
126
+ depth = 0
127
+ if dir_leaf != '':
128
+ dir_leaf_parts = dir_leaf.split(os.path.sep)
129
+ depth = len(dir_leaf_parts)
130
+ if depth > max_depth:
131
+ dirnames[:] = []
132
+ continue
133
+
134
+ if len(dirnames) > 0:
135
+ supported_dirnames = []
136
+ for dname in dirnames:
137
+ dpath = os.path.join(root_dir, dname)
138
+ if _is_platform_supported(root, dpath, platforms_cache):
139
+ supported_dirnames.append(dname)
140
+ dirnames[:] = supported_dirnames
141
+
142
+ for fname in files:
143
+ fbase, fext = os.path.splitext(fname)
144
+ if fext == '.py' and fbase not in ("__init__", "__platforms__"):
145
+ ffull = os.path.join(root_dir, fname)
146
+ pyfiles.append(ffull)
147
+
148
+ return pyfiles
149
+
150
+ def find_included_modules_under_root(root: str, package: Union[str, None], module: str, excluded_path_prefixes: list = []):
151
+ """
152
+ Walks through a directory tree starting at a root directory and finds all of the files that corresponded to
153
+ the package, module expressions specified.
154
+
155
+ :param root: The root directory to start from when performing the tree walk to look
156
+ for included tests.
157
+ :param package: The package name component if there is one. The package components are the directories
158
+ with __init__.py files up to the file where the module file itself is found. It could be
159
+ that there is only a module name.
160
+ :param module: The module name component. There must be a module because that is the file where the tests
161
+ are found.
162
+ """
163
+
164
+ root_pkg = os.path.basename(root)
165
+
166
+ included_file_candidates = set()
167
+ platforms_cache: Dict[str, bool] = {}
168
+
169
+ if not _is_platform_supported(root, root, platforms_cache):
170
+ return [], []
171
+
172
+ if package is None:
173
+ # If package is None, then we had a single item expression, this means
174
+ # we can look for a single file, or a directory with lots of files.
175
+ filenames = os.listdir(root)
176
+ for fname in filenames:
177
+ pkg_name = "{}.{}".format(root_pkg, fname)
178
+ if pkg_name.startswith(module) or fnmatch.fnmatch(pkg_name, module):
179
+ ffull = os.path.join(root, fname)
180
+ if os.path.isfile(ffull):
181
+ fbase, fext = os.path.splitext(fname)
182
+ if fext == ".py" and fbase not in ("__init__", "__platforms__"):
183
+ included_file_candidates.add(ffull)
184
+ elif os.path.isdir(ffull):
185
+ module_list = collect_python_modules_for_tests(ffull, root, platforms_cache)
186
+ for mod in module_list:
187
+ included_file_candidates.add(mod)
188
+ else:
189
+ pkgpathpfx = package.replace(".", "/")
190
+ fullpathpfx = pkgpathpfx + "/" + module
191
+ for dirpath, dirnames, filenames in os.walk(root, topdown=True):
192
+ if not _is_platform_supported(root, dirpath, platforms_cache):
193
+ dirnames[:] = []
194
+ continue
195
+
196
+ if len(dirnames) > 0:
197
+ supported_dirnames = []
198
+ for dname in dirnames:
199
+ dpath = os.path.join(dirpath, dname)
200
+ if _is_platform_supported(root, dpath, platforms_cache):
201
+ supported_dirnames.append(dname)
202
+ dirnames[:] = supported_dirnames
203
+
204
+ # Normalise to "/" so the prefix comparison below works on Windows too.
205
+ dirleaf = root_pkg + "/" + dirpath[len(root):].lstrip(os.sep).replace(os.sep, "/")
206
+ dirleaf = dirleaf.rstrip("/")
207
+
208
+ if dirleaf.startswith(fullpathpfx) or fnmatch.fnmatch(dirleaf, fullpathpfx):
209
+ collected_modules = collect_python_modules_for_tests(dirpath, root, platforms_cache)
210
+ for cm in collected_modules:
211
+ included_file_candidates.add(cm)
212
+ elif dirleaf.startswith(pkgpathpfx) or fnmatch.fnmatch(dirleaf, pkgpathpfx):
213
+ for fname in filenames:
214
+ fbase, fext = os.path.splitext(fname)
215
+ if fext == ".py" and fbase not in ("__init__", "__platforms__") and \
216
+ (fbase.startswith(module) or fnmatch.fnmatch(fbase, module)):
217
+ ffull = os.path.join(dirpath, fname)
218
+ included_file_candidates.add(ffull)
219
+
220
+ included_files = []
221
+ excluded_files = []
222
+
223
+ while len(included_file_candidates) > 0:
224
+ candidate_file: str = included_file_candidates.pop()
225
+
226
+ keep_file = True
227
+ for expfx in excluded_path_prefixes:
228
+ if candidate_file.startswith(expfx):
229
+ keep_file = False
230
+ break
231
+
232
+ if keep_file:
233
+ included_files.append(candidate_file)
234
+ else:
235
+ excluded_files.append(candidate_file)
236
+
237
+ return included_files, excluded_files
238
+
239
+ def find_testmodule_root(module) -> str:
240
+ """
241
+ Discovers the test root directory for a given test module.
242
+
243
+ This function walks up the directory tree from the module's location until it finds
244
+ a directory containing a ``__testroot__.py`` marker file. The test root directory
245
+ defines the boundary of the test package namespace and is essential for proper
246
+ module name resolution.
247
+
248
+ :param module: The test module object (typically ``sys.modules["__main__"]``) for which
249
+ to find the test root directory. The module must have a ``__file__`` attribute
250
+ pointing to its source file location.
251
+ :type module: ModuleType
252
+
253
+ :returns: The absolute path to the test root directory containing the
254
+ ``__testroot__.py`` marker file.
255
+ :rtype: str
256
+
257
+ :raises ConfigurationError: If no ``__testroot__.py`` marker file is found when
258
+ walking up the directory tree to the filesystem root. The error message indicates
259
+ that test files must exist inside a test root directory marked with a
260
+ ``__testroot__.py`` file.
261
+
262
+ Algorithm:
263
+ 1. Start from the directory containing the module's source file
264
+ 2. Check if ``__testroot__.py`` exists in the current directory
265
+ 3. If found, return the current directory path
266
+ 4. If not found, move to the parent directory
267
+ 5. Repeat until found or filesystem root is reached
268
+ 6. If filesystem root is reached without finding the marker, raise ConfigurationError
269
+
270
+ Example:
271
+ Given a test file structure::
272
+
273
+ tests/
274
+ ├── __testroot__.py # Marker file
275
+ ├── __init__.py
276
+ └── package/
277
+ ├── __init__.py
278
+ └── test_module.py
279
+
280
+ When called with the test_module module::
281
+
282
+ import sys
283
+ test_module = sys.modules["__main__"]
284
+ root = find_testmodule_root(test_module)
285
+ # Returns: "/path/to/tests"
286
+
287
+ .. note::
288
+ The ``__testroot__.py`` marker file can be empty or contain test root configuration.
289
+ Its presence alone is sufficient to mark the test root boundary.
290
+
291
+ .. seealso::
292
+ :func:`find_testmodule_fullname` : Uses the test root to compute the full module name
293
+ """
294
+ # =========================================================================
295
+ # TEST ROOT DISCOVERY ALGORITHM
296
+ # =========================================================================
297
+ # The test root is the directory that contains the __testroot__.py marker
298
+ # file. This marker defines the boundary of the test package namespace.
299
+ #
300
+ # Why we need this:
301
+ # - Python modules are identified by their dotted path from a root
302
+ # - Without a marker, we wouldn't know where the module namespace begins
303
+ # - The marker allows test files to be organized in any directory structure
304
+ #
305
+ # Algorithm: Walk up the directory tree until we find __testroot__.py
306
+ # 1. Start at the directory containing the test module file
307
+ # 2. Check if __testroot__.py exists in current directory
308
+ # 3. If found, return this directory as the test root
309
+ # 4. If not found, move to parent directory and repeat
310
+ # 5. If we reach filesystem root without finding marker, raise error
311
+ #
312
+ # Example directory structure:
313
+ # /project/tests/__testroot__.py <- Test root marker
314
+ # /project/tests/unit/test_auth.py <- Test module
315
+ #
316
+ # Walking up from test_auth.py:
317
+ # /project/tests/unit/ -> no __testroot__.py, continue
318
+ # /project/tests/ -> found __testroot__.py, return this path
319
+ # =========================================================================
320
+
321
+ # Get the directory containing the module's source file
322
+ # This is our starting point for the upward directory walk
323
+ mod_dir = os.path.dirname(module.__file__)
324
+
325
+ while True:
326
+ # Construct the path to the potential marker file in current directory
327
+ pkg_dir_file = os.path.join(mod_dir, "__testroot__.py")
328
+
329
+ if not os.path.exists(pkg_dir_file):
330
+ # Marker not found in current directory, move to parent
331
+ parent_dir = os.path.dirname(mod_dir)
332
+
333
+ # Check if we've reached the filesystem root
334
+ # At root, dirname returns the same path (e.g., "/" on Unix)
335
+ if parent_dir == mod_dir:
336
+ # We've walked all the way to root without finding the marker
337
+ # This is a configuration error - test files must be in a test root
338
+ errmsg = "TestBase test files must exist inside a test root directory marked with a __testroot__.py file."
339
+ raise ConfigurationError(errmsg)
340
+
341
+ # Continue walking up the directory tree
342
+ mod_dir = parent_dir
343
+ else:
344
+ # Found the __testroot__.py marker file
345
+ # This directory is the test root
346
+ break
347
+
348
+ return mod_dir
349
+
350
+ def find_testmodule_fullname(module, testroot=None) -> str:
351
+ """
352
+ Computes the fully qualified dotted module name for a test module.
353
+
354
+ This function determines the full module name by computing the relative path from
355
+ the test root's parent directory to the module file, then converting path separators
356
+ to dots. This is essential for proper module registration in ``sys.modules`` and
357
+ for correct identification of test classes and functions.
358
+
359
+ :param module: The test module object (typically ``sys.modules["__main__"]``) for which
360
+ to compute the full module name. The module must have a ``__file__`` attribute
361
+ pointing to its source file location.
362
+ :type module: ModuleType
363
+
364
+ :param testroot: The path to the test root directory. If not provided, the function
365
+ will call :func:`find_testmodule_root` to discover it automatically.
366
+ :type testroot: Optional[str]
367
+
368
+ :returns: The fully qualified dotted module name (e.g., ``"tests.package.test_module"``).
369
+ :rtype: str
370
+
371
+ :raises ConfigurationError: If ``testroot`` is not provided and no ``__testroot__.py``
372
+ marker file is found when discovering the test root.
373
+
374
+ Algorithm:
375
+ 1. If testroot is not provided, discover it using :func:`find_testmodule_root`
376
+ 2. Get the absolute path to the module file (without extension)
377
+ 3. Get the parent directory of the test root
378
+ 4. Compute the relative path from the test root parent to the module file
379
+ 5. Convert path separators (``/``) to dots (``.``) to form the dotted module name
380
+
381
+ Example:
382
+ Given a test file structure::
383
+
384
+ /home/user/project/
385
+ └── tests/
386
+ ├── __testroot__.py
387
+ ├── __init__.py
388
+ └── package/
389
+ ├── __init__.py
390
+ └── test_module.py
391
+
392
+ When called with the test_module module::
393
+
394
+ import sys
395
+ test_module = sys.modules["__main__"]
396
+ fullname = find_testmodule_fullname(test_module)
397
+ # Returns: "tests.package.test_module"
398
+
399
+ With explicit testroot::
400
+
401
+ fullname = find_testmodule_fullname(test_module, testroot="/home/user/project/tests")
402
+ # Returns: "tests.package.test_module"
403
+
404
+ .. note::
405
+ The full module name is computed relative to the test root's parent directory,
406
+ which means the test root directory name itself becomes the first component
407
+ of the module name.
408
+
409
+ .. seealso::
410
+ :func:`find_testmodule_root` : Discovers the test root directory
411
+ :func:`generic_test_entrypoint` : Uses this function for module registration
412
+ """
413
+ # =========================================================================
414
+ # MODULE FULL NAME COMPUTATION ALGORITHM
415
+ # =========================================================================
416
+ # This function converts a file system path to a Python dotted module name.
417
+ # The module name is computed relative to the test root's PARENT directory,
418
+ # so the test root directory name becomes the first component of the module name.
419
+ #
420
+ # Why relative to parent?
421
+ # - The test root directory (e.g., "tests") is itself a Python package
422
+ # - We want module names like "tests.unit.test_auth", not "unit.test_auth"
423
+ # - This matches how Python would import the module if it were on sys.path
424
+ #
425
+ # Algorithm:
426
+ # 1. Get absolute path to module file without .py extension
427
+ # 2. Get the parent directory of the test root
428
+ # 3. Strip the parent path from the module path to get relative path
429
+ # 4. Convert path separators to dots for dotted module name
430
+ #
431
+ # Example:
432
+ # Module file: /project/tests/unit/test_auth.py
433
+ # Test root: /project/tests/
434
+ # Parent: /project/
435
+ #
436
+ # Relative path: tests/unit/test_auth
437
+ # Module name: tests.unit.test_auth
438
+ # =========================================================================
439
+
440
+ # If testroot not provided, discover it by walking up the directory tree
441
+ if testroot is None:
442
+ testroot = find_testmodule_root(module)
443
+
444
+ # Get the absolute path to the module file without the .py extension
445
+ # Example: /project/tests/unit/test_auth.py -> /project/tests/unit/test_auth
446
+ mod_filebase, _ = os.path.splitext(os.path.abspath(module.__file__))
447
+
448
+ # Get the parent directory of the test root
449
+ # This is the directory from which we compute the relative module path
450
+ # Example: /project/tests/ -> /project/
451
+ testroot_parent = os.path.dirname(testroot)
452
+
453
+ # Compute the relative path from testroot_parent to the module file
454
+ # Then convert path separators to dots for the dotted module name
455
+ #
456
+ # Steps:
457
+ # 1. Strip testroot_parent prefix from mod_filebase
458
+ # /project/tests/unit/test_auth -> tests/unit/test_auth
459
+ # 2. Strip leading slashes (in case of edge cases)
460
+ # 3. Replace "/" with "." to get dotted module name
461
+ # tests/unit/test_auth -> tests.unit.test_auth
462
+ # The path uses the native separator, so normalise it to "/" first (on
463
+ # Windows the separator is "\\" and the name would otherwise keep it).
464
+ testmodule_relpath = mod_filebase[len(testroot_parent):].replace(os.sep, "/").strip("/")
465
+ testmodule_fullname = testmodule_relpath.replace("/", ".")
466
+
467
+ return testmodule_fullname
468
+
469
+
470
+
471
+
472
+