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,1472 @@
1
+ """
2
+ .. module:: ccai.testbase.results.recorders.resultrecorder
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module for resultrecorder.
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 List, Optional
17
+
18
+ from types import TracebackType
19
+
20
+ import collections
21
+ import copy
22
+ import os
23
+ import threading
24
+ import time
25
+
26
+ from datetime import datetime
27
+
28
+ from ccai.errors.exceptions import AbstractMethodError
29
+
30
+ from ccai.testbase.results.exceptions import ResultRecordingError
31
+ from ccai.testbase.results.model.buildinfo import BuildInfo
32
+ from ccai.testbase.results.model.jobinfo import JobInfo
33
+ from ccai.testbase.results.model.pipelineinfo import PipelineInfo
34
+ from ccai.testbase.results.model.renderinfo import RenderInfo
35
+
36
+ from ccai.testbase.results.model.resultnode import ResultNode
37
+ from ccai.testbase.results.model.resulttype import ResultType
38
+
39
+ from ccai.testbase.results.utilities import (
40
+ catalog_tree,
41
+ DEFAULT_DO_NOT_CATALOG_DIRS,
42
+ DEFAULT_DO_NOT_DESCEND_DIRS
43
+ )
44
+
45
+ from ccai.testbase.results.model.progresscode import ProgressCode
46
+ from ccai.testbase.results.model.progressinfo import ProgressInfo
47
+ from ccai.testbase.results.model.forwardinginfo import ForwardingInfo
48
+ from ccai.testbase.results.model.nestedprogressinfo import NestedProgressInfo
49
+ from ccai.testbase.results.model.progressaggregator import ProgressAggregator
50
+
51
+
52
+ class ResultRecorder:
53
+ """
54
+ The :class:`ResultRecorder` object is the base class that establishes the API patterns
55
+ for recorders of different formats to use when implementing a test result recorder.
56
+
57
+ This class provides the foundation for recording test execution results, managing
58
+ the test run lifecycle, tracking result counts, and generating summaries. Derived
59
+ classes (such as :class:`JsonResultRecorder`) implement format-specific serialization.
60
+
61
+ Context Manager Lifecycle
62
+ -------------------------
63
+ The ResultRecorder is designed to be used as a context manager to ensure proper
64
+ resource management and lifecycle handling:
65
+
66
+ 1. **Entry (__enter__)**: Initializes the recording environment by:
67
+ - Calling initialize_report() to set up output directories and static resources
68
+ - Calling update_summary() to write the initial summary file
69
+ - Opening the stream results file for writing
70
+
71
+ 2. **Active Recording**: While the context is active:
72
+ - Call preview() to write result previews before test execution
73
+ - Call record() to write final results after test completion
74
+ - Call post_task_progress() to update progress from remote workers
75
+
76
+ 3. **Exit (__exit__)**: Finalizes the recording by:
77
+ - Calling finalize() if not already finalized
78
+ - Updating final counts and result status
79
+ - Closing the stream results file
80
+ - Writing the final summary
81
+
82
+ Thread Safety Considerations
83
+ ----------------------------
84
+ The ResultRecorder is designed for concurrent access from multiple threads:
85
+
86
+ - **Lock Protection**: A threading.Lock (_lock) protects all shared state mutations
87
+ - **Copy-on-Read**: The summary property returns a deep copy to prevent external
88
+ modification and ensure consistent snapshots for concurrent readers
89
+ - **Atomic Updates**: Counter increments and progress updates are performed
90
+ atomically within lock-protected sections
91
+ - **Safe Finalization**: The finalize() method is lock-protected to prevent
92
+ race conditions during shutdown
93
+
94
+ Thread-safe methods:
95
+ - summary (property): Returns a deep copy of the current summary
96
+ - post_task_progress(): Updates running tasks dictionary
97
+ - clear_task_progress(): Removes completed tasks
98
+ - finalize(): Finalizes counts and closes resources
99
+ - record(): Updates result counters (in derived classes)
100
+
101
+ Usage Example
102
+ -------------
103
+ Basic usage with context manager::
104
+
105
+ from datetime import datetime
106
+ from ccai.testbase.results.recorders.jsonresultrecorder import JsonResultRecorder
107
+ from ccai.testbase.results.model.renderinfo import RenderInfo
108
+ from ccai.testbase.results.model.buildinfo import BuildInfo
109
+ from ccai.testbase.results.model.pipelineinfo import PipelineInfo
110
+ from ccai.testbase.results.model.jobinfo import JobInfo
111
+
112
+ # Configure render info
113
+ render_info = RenderInfo(
114
+ title="My Test Run",
115
+ summary_filename="/output/testsummary.json",
116
+ summary_template="/templates/testsummary.html",
117
+ stream_results_filename="/output/testresults_stream.jsos",
118
+ consolidated_results_filename="/output/testresults.json",
119
+ static_resource_source="/templates/static",
120
+ static_resource_destination="/output/static"
121
+ )
122
+
123
+ # Configure metadata
124
+ build_info = BuildInfo(branch="main", build="123", flavor="release",
125
+ release="1.0.0", url="https://builds.example.com/123")
126
+ pipeline_info = PipelineInfo(id="pipe-1", name="CI Pipeline", instance="run-456")
127
+ job_info = JobInfo(id="job-1", name="Test Job", type="integration",
128
+ owner="team@example.com")
129
+
130
+ # Use as context manager
131
+ with JsonResultRecorder(
132
+ runid="run-uuid-123",
133
+ start=datetime.now(),
134
+ render_info=render_info,
135
+ build_info=build_info,
136
+ pipeline_info=pipeline_info,
137
+ job_info=job_info
138
+ ) as recorder:
139
+ # Record test results
140
+ for test_result in test_results:
141
+ recorder.preview(test_result)
142
+ # ... execute test ...
143
+ recorder.record(test_result)
144
+
145
+ # After context exits, results are finalized and files are closed
146
+
147
+ Multi-threaded usage with progress tracking::
148
+
149
+ import threading
150
+ from ccai.testbase.results.model.progressinfo import ProgressInfo
151
+ from ccai.testbase.results.model.progresscode import ProgressCode
152
+
153
+ def worker_thread(recorder, task_id):
154
+ # Report progress from worker thread
155
+ progress = ProgressInfo(
156
+ id=task_id,
157
+ category="worker",
158
+ moniker=f"Task {task_id}",
159
+ ptype="Sequential",
160
+ range_min="0",
161
+ range_max="100",
162
+ position="50",
163
+ status=ProgressCode.Running,
164
+ when=datetime.now()
165
+ )
166
+ recorder.post_task_progress([progress])
167
+
168
+ with JsonResultRecorder(...) as recorder:
169
+ threads = []
170
+ for i in range(5):
171
+ t = threading.Thread(target=worker_thread, args=(recorder, f"task-{i}"))
172
+ threads.append(t)
173
+ t.start()
174
+
175
+ for t in threads:
176
+ t.join()
177
+
178
+ See Also
179
+ --------
180
+ :class:`JsonResultRecorder` : Concrete implementation for JSON output format
181
+ :class:`ProgressConcentratorServer` : HTTP server for receiving remote progress updates
182
+ """
183
+ def __init__(self, *, runid: str, start: datetime, render_info: RenderInfo,
184
+ apod: Optional[str] = None, build_info: Optional[BuildInfo] = None,
185
+ pipeline_info: Optional[PipelineInfo] = None, job_info: Optional[JobInfo] = None,
186
+ forwarding_info: Optional[ForwardingInfo] = None):
187
+ """
188
+ Initializes an instance of a ResultRecorder with the information about a test run.
189
+
190
+ This constructor sets up all internal state required for result recording,
191
+ including counters, summary data structures, and thread synchronization
192
+ primitives. The recorder is not active until used as a context manager.
193
+
194
+ :param runid: The uuid string that identifies a set of test results. This ID
195
+ is used to correlate results across different output files and
196
+ external systems.
197
+ :param start: The date and time of the start of the test run. Used for timing
198
+ calculations and included in the summary output.
199
+ :param render_info: A :class:`RenderInfo` instance containing output file paths
200
+ and rendering configuration. This determines where results
201
+ are written and what templates are used.
202
+ :param apod: Optional name of an automation pod that the automation run is
203
+ running on. Useful for distributed test execution environments.
204
+ :param build_info: Optional :class:`BuildInfo` instance containing build metadata
205
+ (branch, build number, flavor, release, URL) to associate
206
+ with the test run.
207
+ :param pipeline_info: Optional :class:`PipelineInfo` instance containing CI/CD
208
+ pipeline metadata (id, name, instance) to associate with
209
+ the test run.
210
+ :param job_info: Optional :class:`JobInfo` instance containing job execution
211
+ metadata (id, name, type, owner, etc.) to associate with
212
+ the test run.
213
+ :param forwarding_info: Optional :class:`ForwardingInfo` instance containing
214
+ configuration for forwarding progress updates to
215
+ external monitoring services.
216
+
217
+ :returns: None
218
+
219
+ Thread Safety:
220
+ The constructor initializes a threading.Lock that is used by all
221
+ thread-safe methods. The lock is not acquired during construction
222
+ as the object is not yet shared between threads.
223
+ """
224
+
225
+ self._runid = runid
226
+ self._start = start
227
+ self._apod = apod
228
+
229
+ self._render_info = render_info
230
+ self._build_info = build_info
231
+ self._pipeline_info = pipeline_info
232
+ self._job_info = job_info
233
+ self._forwarding_info = forwarding_info
234
+
235
+ self._output_dir = os.path.dirname(self._render_info.summary_filename)
236
+
237
+ self._rout = None
238
+
239
+ self._running_tasks = {}
240
+
241
+ # Progress aggregator for nested progress tracking and aggregation
242
+ self._progress_aggregator = ProgressAggregator()
243
+
244
+ self._error_count = 0
245
+ self._failure_count = 0
246
+ self._pass_count = 0
247
+ self._skip_count = 0
248
+ self._unknown_count = 0
249
+
250
+ self._total_count = 0
251
+
252
+ self._finalized = False
253
+
254
+ def _get_val(obj, attr_name):
255
+ if obj is None:
256
+ return "(unknown)"
257
+ val = getattr(obj, attr_name, None)
258
+ if val is None or val == "" or type(val).__name__ == "DefaultValue":
259
+ return "(unknown)"
260
+ return val
261
+
262
+ build_info = collections.OrderedDict((
263
+ ("release", _get_val(self._build_info, "release")),
264
+ ("branch", _get_val(self._build_info, "branch")),
265
+ ("build", _get_val(self._build_info, "build")),
266
+ ("flavor", _get_val(self._build_info, "flavor")),
267
+ ("url", _get_val(self._build_info, "url"))
268
+ ))
269
+
270
+ pipeline_info = collections.OrderedDict((
271
+ ("id", _get_val(self._pipeline_info, "id")),
272
+ ("name", _get_val(self._pipeline_info, "name")),
273
+ ("instance", _get_val(self._pipeline_info, "instance"))
274
+ ))
275
+
276
+ job_info = collections.OrderedDict((
277
+ ("id", _get_val(self._job_info, "id")),
278
+ ("initiator", _get_val(self._job_info, "initiator")),
279
+ ("label", _get_val(self._job_info, "label")),
280
+ ("name", _get_val(self._job_info, "name")),
281
+ ("owner", _get_val(self._job_info, "owner")),
282
+ ("type", _get_val(self._job_info, "type")),
283
+ ("venue", _get_val(self._job_info, "venue")),
284
+ ("seed", _get_val(self._job_info, "seed")),
285
+ ("tag", _get_val(self._job_info, "tag"))
286
+ ))
287
+
288
+ self._summary = collections.OrderedDict((
289
+ ("version", "2"),
290
+ ("title", self._render_info.title),
291
+ ("runid", self._runid),
292
+ ("build", build_info),
293
+ ("pipeline", pipeline_info),
294
+ ("job", job_info),
295
+ ("start", self._start),
296
+ ("stop", None),
297
+ ("result", "RUNNING"),
298
+ ("apod", self._apod),
299
+ ("totals", None),
300
+ ("running", self._running_tasks)
301
+ ))
302
+
303
+ self._lock = threading.Lock()
304
+ self._next_forward_at = None
305
+
306
+ return
307
+
308
+
309
+ def __enter__(self):
310
+ """
311
+ Starts up the recording process of test results.
312
+
313
+ This method is called when entering the context manager (the 'with' statement).
314
+ It performs all necessary initialization to prepare the recorder for accepting
315
+ test results.
316
+
317
+ Initialization Steps:
318
+ 1. **initialize_report()**: Sets up the output environment by copying
319
+ static resources and the HTML template to the output directory
320
+ 2. **update_summary()**: Writes the initial summary file with run metadata
321
+ 3. **Open stream file**: Opens the stream results file for writing result
322
+ records as they are generated
323
+
324
+ Context Manager Pattern:
325
+ The ResultRecorder implements the context manager protocol to ensure
326
+ proper resource management. Using the 'with' statement guarantees that
327
+ finalize() will be called even if an exception occurs during test execution.
328
+
329
+ Example::
330
+
331
+ with JsonResultRecorder(runid="123", start=datetime.now(), ...) as recorder:
332
+ # recorder.__enter__() has been called
333
+ # Stream file is open and ready for writing
334
+ recorder.preview(test_result)
335
+ recorder.record(test_result)
336
+ # recorder.__exit__() is called automatically
337
+
338
+ :returns: self - The recorder instance for use within the context block.
339
+
340
+ :raises: ResultRecordingError if the stream results file cannot be opened
341
+ for writing. The error includes the file path, operation description,
342
+ and underlying exception details.
343
+ """
344
+ self.initialize_report()
345
+
346
+ self.update_summary()
347
+
348
+ stream_filename = self._render_info.stream_results_filename
349
+ try:
350
+ # newline='' leaves line endings to the recorder (the csv module
351
+ # writes its own), so Windows does not turn them into \r\r\n.
352
+ self._rout = open(stream_filename, 'w', newline='')
353
+ except OSError as err:
354
+ errmsg = f"Failed to open stream results file '{stream_filename}' for writing."
355
+ raise ResultRecordingError(
356
+ errmsg,
357
+ file_path=stream_filename,
358
+ operation="opening stream results file",
359
+ original_error=err
360
+ ) from err
361
+ return self
362
+
363
+
364
+ def __exit__(self, ex_type: type, ex_inst: Exception, ex_tb: TracebackType) -> bool:
365
+ """
366
+ Finalizes the recording process when exiting the context manager.
367
+
368
+ This method is called when exiting the context manager (leaving the 'with'
369
+ block), whether normally or due to an exception. It ensures that all results
370
+ are properly finalized and resources are released.
371
+
372
+ Finalization Steps:
373
+ 1. Check if already finalized (prevents duplicate finalization)
374
+ 2. Call finalize() to:
375
+ - Set the stop timestamp
376
+ - Update final result counts in the summary
377
+ - Determine overall pass/fail status
378
+ - Close the stream results file
379
+ - Write the final summary
380
+
381
+ Exception Handling:
382
+ This method does not suppress exceptions. If an exception occurred within
383
+ the context block, it will propagate after __exit__ completes. The
384
+ finalization is performed regardless of whether an exception occurred,
385
+ ensuring results are always properly closed.
386
+
387
+ Thread Safety:
388
+ The finalize() method called by __exit__ is thread-safe and uses locking
389
+ to ensure atomic updates to shared state. However, __exit__ itself should
390
+ only be called once (by the context manager machinery).
391
+
392
+ :param ex_type: The type associated with the exception being raised, or None
393
+ if no exception occurred.
394
+ :param ex_inst: The exception instance of the exception being raised, or None
395
+ if no exception occurred.
396
+ :param ex_tb: The traceback associated with the exception being raised, or None
397
+ if no exception occurred.
398
+
399
+ :returns: None (does not suppress exceptions). Returning None or False allows
400
+ any exception to propagate; returning True would suppress it.
401
+ """
402
+ if not self._finalized:
403
+ self.finalize()
404
+ return
405
+
406
+
407
+ @property
408
+ def summary(self):
409
+ """
410
+ Get a thread-safe copy of the result summary.
411
+
412
+ This property returns a deep copy of the internal summary dictionary,
413
+ ensuring that callers cannot modify the recorder's internal state and
414
+ that the returned data remains consistent even if other threads update
415
+ the summary after this call returns.
416
+
417
+ Thread Safety Implementation:
418
+ The property uses a lock-protected copy-on-read pattern:
419
+
420
+ 1. Acquire the lock to prevent concurrent modifications
421
+ 2. Create a deep copy of the summary dictionary
422
+ 3. Release the lock
423
+ 4. Return the copy
424
+
425
+ This pattern is critical for the forwarding thread, which may be
426
+ serializing the summary while other threads update progress.
427
+
428
+ Summary Contents:
429
+ The returned dictionary contains:
430
+
431
+ - **version**: Summary format version (currently "2")
432
+ - **title**: Test run title from render_info
433
+ - **runid**: Unique identifier for this test run
434
+ - **build**: Build metadata (release, branch, build, flavor, url)
435
+ - **pipeline**: Pipeline metadata (id, name, instance)
436
+ - **job**: Job metadata (id, name, type, owner, etc.)
437
+ - **start**: Test run start timestamp
438
+ - **stop**: Test run stop timestamp (None until finalized)
439
+ - **result**: Current result status ("RUNNING", "PASSED", or "FAILED")
440
+ - **apod**: Automation pod identifier
441
+ - **totals**: Reserved for future use
442
+ - **running**: Dictionary of currently running tasks
443
+ - **detail**: Final counts (only present after finalization)
444
+
445
+ Example::
446
+
447
+ with JsonResultRecorder(...) as recorder:
448
+ # Get current summary for monitoring
449
+ current_summary = recorder.summary
450
+ print(f"Status: {current_summary['result']}")
451
+ print(f"Running tasks: {len(current_summary['running'])}")
452
+
453
+ :returns: A deep copy of the summary dictionary. Modifications to the
454
+ returned dictionary do not affect the recorder's internal state.
455
+
456
+ :rtype: dict
457
+ """
458
+ rtnval = None
459
+
460
+ # THREAD-SAFE STATE PATTERN - COPY ON READ:
461
+ # Acquire the lock before accessing shared state (_summary).
462
+ # We return a deep copy to prevent callers from modifying the
463
+ # internal state and to ensure the returned data remains consistent
464
+ # even if other threads update the summary after we release the lock.
465
+ self._lock.acquire()
466
+ try:
467
+ # Deep copy ensures the caller gets an immutable snapshot.
468
+ # This is critical for the forwarding thread which may be
469
+ # serializing the summary while other threads update progress.
470
+ rtnval = copy.deepcopy(self._summary)
471
+ finally:
472
+ # Always release the lock in finally block to prevent deadlocks
473
+ # even if an exception occurs during the copy operation.
474
+ self._lock.release()
475
+
476
+ return rtnval
477
+
478
+
479
+ CATALOG_MIN_INTERVAL_SECONDS = 5.0
480
+
481
+ def catalog_output_directory(self, force: bool = False):
482
+ """
483
+ Triggers catalog generation for the results output directory.
484
+
485
+ This method creates catalog.json files in each directory of the output
486
+ tree, enabling HTML report navigation. The catalog files contain lists
487
+ of files and subdirectories, allowing the HTML report to dynamically
488
+ build navigation menus.
489
+
490
+ Catalog Generation Rules:
491
+ - Creates catalog.json in each directory
492
+ - Skips directories in DEFAULT_DO_NOT_CATALOG_DIRS (e.g., "__pycache__")
493
+ - Does not descend into directories in DEFAULT_DO_NOT_DESCEND_DIRS
494
+ (e.g., "diagnostics")
495
+
496
+ This method is called automatically by:
497
+ - initialize_report() during context entry
498
+ - preview() after writing a preview record
499
+ - record() after writing a final result record
500
+ - update_summary() after updating the summary file
501
+ - write_consolidated_results() after writing consolidated results
502
+
503
+ :returns: None
504
+ """
505
+ # Cataloguing walks the whole results tree and rewrites a catalog.json in every directory. Doing that
506
+ # after every record made the cost quadratic in the number of tests, which stalled large suites for
507
+ # hours. Per-record calls are throttled; the final write of a run passes force=True so the report is
508
+ # complete.
509
+ now = time.monotonic()
510
+ last = getattr(self, "_catalog_last_at", 0.0)
511
+ if not force and (now - last) < self.CATALOG_MIN_INTERVAL_SECONDS:
512
+ return
513
+ catalog_tree(self._output_dir, dont_catalog_dirs=DEFAULT_DO_NOT_CATALOG_DIRS,
514
+ dont_descend_dirs=DEFAULT_DO_NOT_DESCEND_DIRS)
515
+ self._catalog_last_at = time.monotonic()
516
+ return
517
+
518
+
519
+ def clear_task_progress(self, task_ids: List[str]):
520
+ """
521
+ Clears progress entries for the specified task IDs from the running tasks dictionary.
522
+
523
+ This method removes completed or cancelled tasks from the running_tasks
524
+ dictionary, which is included in the summary for real-time monitoring.
525
+ It is typically called when tasks complete or are explicitly cancelled.
526
+
527
+ Thread Safety:
528
+ This method is thread-safe. It acquires the internal lock before
529
+ modifying the running_tasks dictionary, ensuring atomic removal
530
+ of multiple task IDs without interference from concurrent progress
531
+ updates or summary reads.
532
+
533
+ Example::
534
+
535
+ # Clear completed tasks
536
+ completed_task_ids = ["task-1", "task-2", "task-3"]
537
+ recorder.clear_task_progress(completed_task_ids)
538
+
539
+ :param task_ids: A list of task ID strings to remove from running_tasks.
540
+ Task IDs that don't exist in the dictionary are silently
541
+ ignored (no KeyError is raised).
542
+
543
+ :returns: None
544
+ """
545
+
546
+ # THREAD-SAFE STATE PATTERN - LOCK PROTECTED MUTATION:
547
+ # Acquire the lock before modifying shared state (_running_tasks).
548
+ # This ensures atomic removal of multiple task IDs without interference
549
+ # from concurrent progress updates or summary reads.
550
+ self._lock.acquire()
551
+ try:
552
+ for tid in task_ids:
553
+ # Check existence before deletion to avoid KeyError
554
+ if tid in self._running_tasks:
555
+ del self._running_tasks[tid]
556
+ finally:
557
+ # Always release the lock in finally block to prevent deadlocks
558
+ self._lock.release()
559
+
560
+ return
561
+
562
+
563
+ def consolidate_results(self):
564
+ """
565
+ Process the results stream and roll it up into a consolidated test results document.
566
+
567
+ This method reads the streaming results file (JSOS format) and builds a
568
+ hierarchical tree structure that mirrors the test execution hierarchy.
569
+ The consolidated results are then written to a single JSON file for
570
+ easier consumption by reporting tools.
571
+
572
+ RESULT CONSOLIDATION ALGORITHM:
573
+ ================================
574
+ The algorithm processes a flat stream of result records and reconstructs
575
+ the hierarchical test execution tree. It uses a node lookup dictionary
576
+ to efficiently find parent nodes when building the tree.
577
+
578
+ Algorithm Steps:
579
+ 1. Initialize empty node_lookup dictionary and root_node reference
580
+ 2. Load all records from the stream results file
581
+ 3. For each record, determine its type and process accordingly:
582
+ - JOB: Set as root node (only one allowed)
583
+ - TEST_CONTAINER: Add to parent's items list
584
+ - TEST: Add to parent's items list, initialize tasking_groups
585
+ - TASKING_GROUP: Add to parent's tasking_groups list
586
+ - TASKING: Add to parent's taskings list
587
+ 4. Handle preview/final record merging for TEST, TASKING_GROUP, TASKING
588
+ 5. Write the complete tree to the consolidated results file
589
+
590
+ Data Structures:
591
+ - node_lookup: Dict[str, dict] - Maps instance IDs to node dictionaries
592
+ for O(1) parent lookup during tree construction
593
+ - root_node: dict - The JobContainer that serves as the tree root
594
+
595
+ Preview/Final Record Merging:
596
+ The stream contains both preview records (written before test execution)
597
+ and final records (written after execution). When a final record arrives,
598
+ we check if a preview exists in node_lookup and merge the final data
599
+ into the preview record. This preserves the tree structure while updating
600
+ with final results.
601
+
602
+ Result Tree Structure::
603
+
604
+ JobContainer (root)
605
+ ├── items: [
606
+ │ TestContainer
607
+ │ ├── items: [
608
+ │ │ TestResult
609
+ │ │ ├── tasking_groups: [
610
+ │ │ │ TaskingGroup
611
+ │ │ │ ├── taskings: [TaskingResult, ...]
612
+ │ │ │ ]
613
+ │ │ ]
614
+ │ ]
615
+ ]
616
+
617
+ Error Handling:
618
+ - Raises Exception if more than one JOB record is found
619
+ - Raises Exception if a non-JOB record has no parent in the lookup
620
+
621
+ :returns: None
622
+
623
+ :raises: Exception if the stream contains invalid hierarchy (multiple roots
624
+ or orphaned nodes).
625
+ """
626
+
627
+ # INITIALIZATION:
628
+ # ---------------
629
+ # node_lookup: Dictionary mapping instance IDs to node dictionaries.
630
+ # This enables O(1) lookup when finding parent nodes during tree construction.
631
+ # root_node: Reference to the JobContainer that serves as the tree root.
632
+ node_lookup = {}
633
+ root_node = None
634
+
635
+ # STEP 1: LOAD RESULT STREAM
636
+ # --------------------------
637
+ # Load all records from the JSOS (JSON Separated Object Stream) file.
638
+ # Records are returned in the order they were written during test execution.
639
+ result_stream = self.load_result_stream()
640
+
641
+ # STEP 2: PROCESS EACH RECORD AND BUILD TREE
642
+ # ------------------------------------------
643
+ # Iterate through records in order, building the hierarchical tree structure.
644
+ # Each record is classified by type and added to the appropriate parent node.
645
+ for ritem in result_stream:
646
+
647
+ # Extract key fields for processing
648
+ ritem_inst = ritem["instance"] # Unique identifier for this node
649
+ ritem_type = ritem["type"] # ResultType name (JOB, TEST, etc.)
650
+
651
+ # CASE: JOB RECORD (ROOT NODE)
652
+ # ----------------------------
653
+ # The JOB record represents the root of the result tree.
654
+ # There should be exactly one JOB record in the stream.
655
+ if ritem_type == ResultType.JOB.name:
656
+ # VALIDATION: Ensure only one root node exists
657
+ if root_node is not None:
658
+ raise Exception("More than one job node found in results file.")
659
+ root_node = ritem
660
+
661
+ # Initialize the items list for child containers (TestContainers)
662
+ root_node["items"] = []
663
+ else:
664
+ # CASE: NON-ROOT RECORD
665
+ # ---------------------
666
+ # All non-JOB records must have a parent in the lookup.
667
+ # This validates the stream contains a valid hierarchy.
668
+
669
+ ritem_parent_id = ritem["parent"]
670
+
671
+ # VALIDATION: Parent must exist in lookup
672
+ # This catches orphaned nodes that would break the tree structure.
673
+ if ritem_parent_id not in node_lookup:
674
+ errmsg = f"We should never encounter a non-job node that does not have a parent. Id={ritem_inst} Parent={ritem_parent_id}"
675
+ raise Exception(errmsg)
676
+
677
+ # Retrieve parent node for attaching this record
678
+ parent_node = node_lookup[ritem_parent_id]
679
+
680
+ # CASE: TEST_CONTAINER RECORD
681
+ # ---------------------------
682
+ # TestContainers represent module-level groupings of tests.
683
+ # They are added to their parent's items list and can contain
684
+ # other TestContainers or TestResults.
685
+ if ritem_type == ResultType.TEST_CONTAINER.name:
686
+
687
+ # Add to parent's items list (parent is JobContainer or TestContainer)
688
+ parent_node_items: list = parent_node["items"]
689
+ parent_node_items.append(ritem)
690
+
691
+ # Initialize items list for child nodes
692
+ ritem["items"] = []
693
+
694
+ # Register in lookup for child nodes to find this parent
695
+ node_lookup[ritem_inst] = ritem
696
+
697
+ # CASE: TEST RECORD
698
+ # -----------------
699
+ # TestResults represent individual test execution outcomes.
700
+ # They may have associated TaskingGroups for distributed execution.
701
+ elif ritem_type == ResultType.TEST.name:
702
+
703
+ # Add to parent's items list (parent is TestContainer)
704
+ parent_node_items: list = parent_node["items"]
705
+ parent_node_items.append(ritem)
706
+
707
+ # Initialize tasking_groups and checks lists if not present
708
+ # (may already exist from preview record)
709
+ if "tasking_groups" not in ritem:
710
+ ritem["tasking_groups"] = []
711
+ if "checks" not in ritem:
712
+ ritem["checks"] = []
713
+
714
+ # PREVIEW/FINAL RECORD MERGING:
715
+ # If a preview record exists in the lookup, merge the final
716
+ # record data into it. This preserves tree references while
717
+ # updating with final results (result_code, errors, etc.).
718
+ if ritem_inst in node_lookup:
719
+ preview_info: dict = node_lookup[ritem_inst]
720
+ preview_info.update(ritem)
721
+
722
+ else:
723
+ # This must be an injected failure that does not have a preview
724
+ # (e.g., a test that failed during collection/setup)
725
+ node_lookup[ritem_inst] = ritem
726
+
727
+ # CASE: TASKING_GROUP RECORD
728
+ # --------------------------
729
+ # TaskingGroups contain related TaskingResults from distributed
730
+ # task execution within a single test.
731
+ elif ritem_type == ResultType.TASKING_GROUP.name:
732
+ # Add to parent's tasking_groups list (parent is TestResult)
733
+ parent_node_taskinggroups: list = parent_node["tasking_groups"]
734
+ parent_node_taskinggroups.append(ritem)
735
+
736
+ # Initialize taskings list if not present
737
+ if "taskings" not in ritem:
738
+ ritem["taskings"] = []
739
+
740
+ # PREVIEW/FINAL RECORD MERGING (same pattern as TEST)
741
+ if ritem_inst in node_lookup:
742
+ preview_info: dict = node_lookup[ritem_inst]
743
+ preview_info.update(ritem)
744
+
745
+ else:
746
+ # This must be an injected failure that does not have a preview
747
+ node_lookup[ritem_inst] = ritem
748
+
749
+ # CASE: TASKING RECORD
750
+ # --------------------
751
+ # TaskingResults represent individual distributed task outcomes
752
+ # with worker information and return values.
753
+ elif ritem_type == ResultType.TASKING.name:
754
+ # Add to parent's taskings list (parent is TaskingGroup)
755
+ parent_node_taskings: list = parent_node["taskings"]
756
+ parent_node_taskings.append(ritem)
757
+
758
+ # PREVIEW/FINAL RECORD MERGING (same pattern as TEST)
759
+ if ritem_inst in node_lookup:
760
+ preview_info: dict = node_lookup[ritem_inst]
761
+ preview_info.update(ritem)
762
+
763
+ else:
764
+ # This must be an injected failure that does not have a preview
765
+ node_lookup[ritem_inst] = ritem
766
+
767
+ # CASE: CHECK RECORD
768
+ # --------------------
769
+ # CheckResults represent individual property test check outcomes
770
+ # with generated values, example index, and seed.
771
+ elif ritem_type == ResultType.CHECK.name:
772
+ # Add to parent's checks list (parent is TestResult)
773
+ if "checks" not in parent_node:
774
+ parent_node["checks"] = []
775
+ parent_node_checks: list = parent_node["checks"]
776
+ parent_node_checks.append(ritem)
777
+
778
+ # PREVIEW/FINAL RECORD MERGING (same pattern as TEST)
779
+ if ritem_inst in node_lookup:
780
+ preview_info: dict = node_lookup[ritem_inst]
781
+ preview_info.update(ritem)
782
+
783
+ else:
784
+ node_lookup[ritem_inst] = ritem
785
+
786
+ # STEP 3: WRITE CONSOLIDATED RESULTS
787
+ # ----------------------------------
788
+ # Write the complete hierarchical tree to the consolidated results file.
789
+ # The root_node now contains the entire tree structure with all nested
790
+ # containers and results.
791
+ self.write_consolidated_results(root_node)
792
+
793
+ return
794
+
795
+
796
+ def finalize(self):
797
+ """
798
+ Finalizes the test results counters and status of the test run.
799
+
800
+ This method completes the test run by setting the stop timestamp,
801
+ calculating final result counts, determining the overall pass/fail
802
+ status, and closing all output resources. It is automatically called
803
+ by __exit__ when leaving the context manager.
804
+
805
+ Finalization Steps:
806
+ 1. Acquire the lock for thread-safe state updates
807
+ 2. Set the finalized flag to prevent duplicate finalization
808
+ 3. Record the stop timestamp
809
+ 4. Update the summary with final timing and result details
810
+ 5. Determine overall result (PASSED if no errors/failures, else FAILED)
811
+ 6. Close the stream results file
812
+ 7. Write the final summary to disk
813
+ 8. Release the lock
814
+
815
+ Thread Safety:
816
+ This method is fully thread-safe. It acquires the internal lock
817
+ before modifying any shared state, ensuring that concurrent calls
818
+ to record(), post_task_progress(), or summary access do not
819
+ interfere with finalization.
820
+
821
+ Idempotency:
822
+ The method checks the _finalized flag and only performs finalization
823
+ once. Subsequent calls are no-ops. This prevents issues if finalize()
824
+ is called explicitly and then again by __exit__.
825
+
826
+ Result Determination:
827
+ - If error_count > 0 OR failure_count > 0: result = "FAILED"
828
+ - Otherwise: result = "PASSED"
829
+
830
+ Example::
831
+
832
+ with JsonResultRecorder(...) as recorder:
833
+ # Record tests...
834
+ pass
835
+ # finalize() is called automatically here
836
+
837
+ # Or call explicitly (not recommended):
838
+ recorder.finalize() # No-op if already finalized
839
+
840
+ :returns: None
841
+ """
842
+
843
+ # THREAD-SAFE FINALIZATION:
844
+ # Acquire the lock before modifying shared state during finalization.
845
+ # This ensures the summary is updated atomically and prevents race
846
+ # conditions with concurrent progress updates or summary reads.
847
+ self._lock.acquire()
848
+ try:
849
+
850
+ # Idempotency guard: if finalization already ran, subsequent calls are
851
+ # no-ops, as documented. The finally block still releases the lock.
852
+ if self._finalized:
853
+ return
854
+
855
+ # Mark as finalized to prevent duplicate finalization
856
+ self._finalized = True
857
+
858
+ self._stop = datetime.now()
859
+
860
+ # Update summary with final timing and result details
861
+ self._summary["stop"] = str(self._stop)
862
+
863
+ # Populate the detail section with final test counts
864
+ self._summary["detail"] = {
865
+ "errors": self._error_count,
866
+ "failed": self._failure_count,
867
+ "skipped": self._skip_count,
868
+ "passed": self._pass_count,
869
+ "total": self._total_count
870
+ }
871
+
872
+ # Determine final result based on error/failure counts
873
+ if self._error_count > 0 or self._failure_count > 0:
874
+ self._summary["result"] = "FAILED"
875
+ else:
876
+ self._summary["result"] = "PASSED"
877
+
878
+ # Close the results output stream
879
+ self._rout.close()
880
+
881
+ # Write final summary to disk
882
+ self.update_summary()
883
+
884
+ finally:
885
+ # Always release the lock in finally block to prevent deadlocks
886
+ self._lock.release()
887
+
888
+ return
889
+
890
+
891
+ def format_lines(self):
892
+ """
893
+ Generates a list of formatted summary lines for console output.
894
+
895
+ This method creates a human-readable summary of the test run that can
896
+ be printed to the console or logged. The output includes metadata,
897
+ timing information, result counts, and the overall status.
898
+
899
+ Output Format::
900
+
901
+ ============== Test Summary ==============
902
+ Title: My Test Run
903
+ Release: 1.0.0
904
+ Branch: main
905
+ Build: 123
906
+ Flavor: release
907
+ Owner: team@example.com
908
+ RunId: run-uuid-123
909
+ Start: 2025-02-20 10:00:00
910
+ Stop: 2025-02-20 10:30:00
911
+ ----------------- Detail -----------------
912
+ Errors: 0
913
+ Failed: 2
914
+ Skipped: 1
915
+ Passed: 97
916
+ Total: 100
917
+ ==========================================
918
+ FAILED
919
+ ==========================================
920
+
921
+ OUTPUT PATH: /path/to/output
922
+ SUMMARY URL: https://results.example.com/run-123
923
+
924
+ Environment Variables:
925
+ - AM_SUMMARY_URL: If set, the summary URL is included in the output
926
+
927
+ Example::
928
+
929
+ with JsonResultRecorder(...) as recorder:
930
+ # ... record tests ...
931
+ pass
932
+
933
+ # Print summary to console
934
+ for line in recorder.format_lines():
935
+ print(line)
936
+
937
+ :returns: A list of strings, each representing one line of the formatted
938
+ summary. Lines do not include trailing newlines.
939
+
940
+ :rtype: List[str]
941
+ """
942
+ lines = [
943
+ " ============== Test Summary ============== ",
944
+ ]
945
+
946
+ if self._render_info.title:
947
+ lines.append(" Title: {}".format(self._render_info.title))
948
+
949
+ if self._build_info is not None:
950
+ if self._build_info.release:
951
+ lines.append(" Release: {}".format(self._build_info.release))
952
+ if self._build_info.branch:
953
+ lines.append(" Branch: {}".format(self._build_info.branch))
954
+ if self._build_info.build:
955
+ lines.append(" Build: {}".format(self._build_info.build))
956
+ if self._build_info.flavor:
957
+ lines.append(" Flavor: {}".format(self._build_info.flavor))
958
+
959
+ if self._job_info is not None:
960
+ if self._job_info.owner:
961
+ lines.append(" Owner: {}".format(self._job_info.owner))
962
+
963
+ lines.extend([
964
+ " RunId: {}".format(self._runid),
965
+ " Start: {}".format(self._start),
966
+ " Stop: {}".format(self._stop),
967
+ " ----------------- Detail ----------------- ",
968
+ " Errors: {}".format(self._error_count),
969
+ " Failed: {}".format(self._failure_count),
970
+ " Skipped: {}".format(self._skip_count),
971
+ " Passed: {}".format(self._pass_count),
972
+ " Total: {}".format(self._total_count),
973
+ " ========================================== ",
974
+ " {}".format(self._summary["result"]),
975
+ " ========================================== ",
976
+ "",
977
+ "OUTPUT PATH: {}".format(self._output_dir)
978
+ ])
979
+
980
+ if "AM_SUMMARY_URL" in os.environ:
981
+ summary_url = os.environ["AM_SUMMARY_URL"]
982
+ lines.append("SUMMARY URL: {}".format(summary_url))
983
+
984
+ return lines
985
+
986
+
987
+ def forward_summary_update(self, summary):
988
+ """
989
+ Forwards a summary update to an external monitoring service.
990
+
991
+ This method is called by post_task_progress() when forwarding is configured
992
+ and the forwarding interval has elapsed. The base implementation is a no-op;
993
+ derived classes or the ProgressConcentratorServer handle actual forwarding.
994
+
995
+ :param summary: A dictionary containing the current summary state to forward.
996
+
997
+ :returns: None
998
+ """
999
+ return
1000
+
1001
+
1002
+ def get_summary_render_file_basename(self):
1003
+ """
1004
+ Returns the base filename for the HTML summary render file.
1005
+
1006
+ This method provides the filename used when copying the HTML template
1007
+ to the output directory. Override this method in derived classes to
1008
+ use a different filename.
1009
+
1010
+ :returns: The base filename for the HTML summary file.
1011
+
1012
+ :rtype: str
1013
+ """
1014
+ return "testsummary.html"
1015
+
1016
+
1017
+ def initialize_report(self):
1018
+ """
1019
+ Initializes the report output environment.
1020
+
1021
+ This method is called by __enter__ before recording begins. In the near-standalone
1022
+ testbase framework it only generates the initial output-directory catalog. Publishing
1023
+ the HTML presentation resources (static CSS/JavaScript/images and the HTML summary
1024
+ template) is an integration-tier concern: codecraftai-integration-runtime's
1025
+ ``IntegrationJsonResultRecorder`` overrides this method (and update_render_environment)
1026
+ to add that behaviour before delegating here for the catalog.
1027
+
1028
+ :returns: None
1029
+ """
1030
+
1031
+ self.catalog_output_directory()
1032
+
1033
+ return
1034
+
1035
+
1036
+ def load_result_stream(self) -> List[dict]:
1037
+ """
1038
+ Loads and parses the result stream file.
1039
+
1040
+ This method reads the streaming results file (JSOS format) and returns
1041
+ a list of result dictionaries. The base implementation returns an empty
1042
+ list; derived classes should override to provide actual loading.
1043
+
1044
+ :returns: A list of result dictionaries parsed from the stream file.
1045
+
1046
+ :rtype: List[dict]
1047
+ """
1048
+ return
1049
+
1050
+
1051
+ def preview(self, result: ResultNode):
1052
+ """
1053
+ Writes a preview of a result to the result stream.
1054
+
1055
+ This abstract method must be implemented by derived classes to write
1056
+ a preview record to the stream file. A preview is written before test
1057
+ execution begins and contains metadata about the test without final
1058
+ results. Previews are not included in result totals.
1059
+
1060
+ Preview vs Record:
1061
+ - **preview()**: Called before test execution, result_code is UNSET,
1062
+ no detail section, not counted in totals
1063
+ - **record()**: Called after test execution, result_code is final,
1064
+ includes detail section with errors/failures, counted in totals
1065
+
1066
+ The preview allows monitoring tools to see which tests are about to run
1067
+ and track their progress in real-time.
1068
+
1069
+ :param result: A :class:`ResultNode` object to be previewed. The result's
1070
+ to_json(is_preview=True) method is typically called to
1071
+ generate the preview content.
1072
+
1073
+ :returns: None
1074
+
1075
+ :raises: AbstractMethodError if called on the base ResultRecorder class.
1076
+ """
1077
+ raise AbstractMethodError("The 'preview' method must be overridden by derived 'ResultRecorder' objects.") from None
1078
+
1079
+
1080
+ def post_task_progress(self, progress_list: List[ProgressInfo]):
1081
+ """
1082
+ Posts task progress updates to the running tasks dictionary.
1083
+
1084
+ This method is called by the :class:`ProgressConcentratorServer` when progress
1085
+ updates are received from remote workers. It handles thread-safe updates
1086
+ to the running_tasks dictionary and optionally triggers summary forwarding.
1087
+
1088
+ Progress Status Handling:
1089
+ - **Completed**: Task is removed from running_tasks (task is done)
1090
+ - **All other statuses**: Task is added/updated in running_tasks
1091
+
1092
+ Thread Safety:
1093
+ This method is fully thread-safe. It acquires the internal lock before
1094
+ modifying the running_tasks dictionary, ensuring atomic updates when
1095
+ multiple request handler threads submit progress updates concurrently.
1096
+
1097
+ Forwarding Behavior:
1098
+ If forwarding_info is configured, this method checks whether the
1099
+ forwarding interval has elapsed. If so, it prepares a summary snapshot
1100
+ while holding the lock, then forwards it outside the lock to minimize
1101
+ lock hold time (network I/O can be slow).
1102
+
1103
+ Example::
1104
+
1105
+ from ccai.testbase.results.model.progressinfo import ProgressInfo
1106
+ from ccai.testbase.results.model.progresscode import ProgressCode
1107
+
1108
+ # Create progress update
1109
+ progress = ProgressInfo(
1110
+ id="task-123",
1111
+ category="worker",
1112
+ moniker="Processing batch 5",
1113
+ ptype="NumericRange",
1114
+ range_min="0",
1115
+ range_max="100",
1116
+ position="50",
1117
+ status=ProgressCode.Running,
1118
+ when=datetime.now()
1119
+ )
1120
+
1121
+ # Post to recorder (thread-safe)
1122
+ recorder.post_task_progress([progress])
1123
+
1124
+ :param progress_list: A list of :class:`ProgressInfo` objects to process.
1125
+ Each object represents a progress update from a
1126
+ remote worker.
1127
+
1128
+ :returns: None
1129
+ """
1130
+
1131
+ fwd_summary = None
1132
+
1133
+ # THREAD-SAFE STATE PATTERN - LOCK PROTECTED MUTATION:
1134
+ # Acquire the lock before modifying shared state (_running_tasks).
1135
+ # This ensures atomic updates when multiple request handler threads
1136
+ # submit progress updates concurrently.
1137
+ self._lock.acquire()
1138
+ try:
1139
+
1140
+ # PROGRESS STATUS TRACKING:
1141
+ # Process each progress update and update the running_tasks dictionary.
1142
+ # The status field determines whether to add/update or remove the task.
1143
+ for progress in progress_list:
1144
+
1145
+ if hasattr(progress, "status"):
1146
+ # STATUS-BASED STATE MANAGEMENT:
1147
+ # - Completed: Remove task from running_tasks (task is done)
1148
+ # - All other statuses: Update/add task in running_tasks
1149
+ # This maintains an accurate view of currently active tasks.
1150
+ if progress.status == ProgressCode.Completed:
1151
+ # Task completed - remove from running tasks dictionary
1152
+ del self._running_tasks[progress.id]
1153
+ else:
1154
+ # Task still active - update its progress in the dictionary
1155
+ # as_dict() serializes the ProgressInfo for storage
1156
+ self._running_tasks[progress.id] = progress.as_dict()
1157
+
1158
+ # CONDITIONAL FORWARDING CHECK:
1159
+ # If forwarding is configured, check if it's time to forward a summary.
1160
+ # We prepare the summary while holding the lock to get a consistent snapshot.
1161
+ if self._forwarding_info is not None:
1162
+ now_time = datetime.now()
1163
+ # Forward if this is the first forward or if the interval has elapsed
1164
+ if self._next_forward_at is None or now_time > self._next_forward_at:
1165
+ # Deep copy while holding lock ensures consistent snapshot
1166
+ fwd_summary = copy.deepcopy(self._summary)
1167
+
1168
+ finally:
1169
+ # Always release the lock in finally block to prevent deadlocks
1170
+ self._lock.release()
1171
+
1172
+ # FORWARDING OUTSIDE LOCK:
1173
+ # Perform the actual forwarding outside the lock to minimize lock hold time.
1174
+ # Network I/O can be slow, so we don't want to block other threads.
1175
+ if fwd_summary is not None:
1176
+ self.forward_summary_update(fwd_summary)
1177
+
1178
+ return
1179
+
1180
+
1181
+ def post_nested_progress(self, progress: NestedProgressInfo) -> NestedProgressInfo:
1182
+ """
1183
+ Posts a nested progress update to the progress aggregator.
1184
+
1185
+ This method registers or updates a nested progress indicator in the
1186
+ progress aggregator, which maintains the hierarchical relationship
1187
+ between progress indicators. It also updates the running_tasks
1188
+ dictionary for backward compatibility.
1189
+
1190
+ Nested Progress Features:
1191
+ - Parent-child relationships between progress indicators
1192
+ - Automatic aggregation of child progress into parent metrics
1193
+ - Hierarchical progress tree visualization
1194
+
1195
+ Thread Safety:
1196
+ This method is thread-safe. The progress aggregator uses internal
1197
+ locking, and the running_tasks update is protected by the recorder's
1198
+ lock.
1199
+
1200
+ Example::
1201
+
1202
+ # Create a parent progress indicator
1203
+ parent_progress = NestedProgressInfo(
1204
+ id="suite-123",
1205
+ category="test-suite",
1206
+ moniker="Integration Tests",
1207
+ ptype=ProgressType.NumericRange,
1208
+ range_min="0",
1209
+ range_max="100",
1210
+ position="0",
1211
+ status=ProgressCode.Running,
1212
+ when=datetime.now(),
1213
+ parent_id=None,
1214
+ depth=0
1215
+ )
1216
+ recorder.post_nested_progress(parent_progress)
1217
+
1218
+ # Create a child progress indicator
1219
+ child_progress = NestedProgressInfo(
1220
+ id="test-456",
1221
+ category="test",
1222
+ moniker="test_login",
1223
+ ptype=ProgressType.Sequential,
1224
+ range_min="0",
1225
+ range_max="1",
1226
+ position="0",
1227
+ status=ProgressCode.Running,
1228
+ when=datetime.now(),
1229
+ parent_id="suite-123",
1230
+ depth=1
1231
+ )
1232
+ recorder.post_nested_progress(child_progress)
1233
+
1234
+ :param progress: A :class:`NestedProgressInfo` object containing the
1235
+ nested progress update data.
1236
+
1237
+ :returns: The registered NestedProgressInfo instance.
1238
+
1239
+ :rtype: NestedProgressInfo
1240
+ """
1241
+ # Register with the progress aggregator (handles its own locking)
1242
+ registered_progress = self._progress_aggregator.register_progress(progress)
1243
+
1244
+ # Also update running_tasks for backward compatibility
1245
+ self._lock.acquire()
1246
+ try:
1247
+ if progress.status == ProgressCode.Completed:
1248
+ if progress.id in self._running_tasks:
1249
+ del self._running_tasks[progress.id]
1250
+ else:
1251
+ self._running_tasks[progress.id] = progress.as_dict()
1252
+ finally:
1253
+ self._lock.release()
1254
+
1255
+ return registered_progress
1256
+
1257
+
1258
+ def get_aggregated_progress(self, progress_id: str) -> Optional[dict]:
1259
+ """
1260
+ Retrieves aggregated progress metrics for a progress indicator and
1261
+ all its descendants.
1262
+
1263
+ This method delegates to the progress aggregator to compute aggregate
1264
+ metrics including completion percentage, status counts, and overall
1265
+ aggregate status.
1266
+
1267
+ Aggregated Metrics:
1268
+ - total_children: Total number of descendant progress indicators
1269
+ - completed_count: Number of descendants with Completed status
1270
+ - running_count: Number of descendants with Running status
1271
+ - pending_count: Number of descendants with NotStarted status
1272
+ - errored_count: Number of descendants with Errored status
1273
+ - failed_count: Number of descendants with Failed status
1274
+ - paused_count: Number of descendants with Paused status
1275
+ - completion_percentage: Percentage of completed descendants
1276
+ - aggregate_status: Overall status based on child statuses
1277
+
1278
+ Example::
1279
+
1280
+ # Get aggregated progress for a test suite
1281
+ aggregated = recorder.get_aggregated_progress("suite-123")
1282
+ print(f"Completion: {aggregated['completion_percentage']:.1f}%")
1283
+ print(f"Status: {aggregated['aggregate_status']}")
1284
+
1285
+ :param progress_id: The ID of the progress indicator to aggregate.
1286
+
1287
+ :returns: A dictionary containing aggregated metrics, or None if
1288
+ the progress indicator is not found.
1289
+
1290
+ :rtype: Optional[dict]
1291
+ """
1292
+ return self._progress_aggregator.get_aggregated_progress(progress_id)
1293
+
1294
+
1295
+ def get_progress_tree(self) -> dict:
1296
+ """
1297
+ Retrieves the complete progress tree as a nested dictionary structure.
1298
+
1299
+ The returned structure contains root-level progress indicators with
1300
+ their children nested recursively. This is useful for visualizing
1301
+ the hierarchical progress of distributed tasks.
1302
+
1303
+ Example::
1304
+
1305
+ tree = recorder.get_progress_tree()
1306
+ for root in tree["roots"]:
1307
+ print(f"Root: {root['moniker']}")
1308
+ for child in root.get("children", []):
1309
+ print(f" Child: {child['moniker']}")
1310
+
1311
+ :returns: A dictionary containing the hierarchical progress tree with
1312
+ 'roots' (list of root progress nodes) and 'total_count'.
1313
+
1314
+ :rtype: dict
1315
+ """
1316
+ return self._progress_aggregator.get_progress_tree()
1317
+
1318
+
1319
+ def get_nested_progress(self, progress_id: str) -> Optional[NestedProgressInfo]:
1320
+ """
1321
+ Retrieves a nested progress indicator by ID.
1322
+
1323
+ :param progress_id: The ID of the progress indicator to retrieve.
1324
+
1325
+ :returns: The NestedProgressInfo, or None if not found.
1326
+
1327
+ :rtype: Optional[NestedProgressInfo]
1328
+ """
1329
+ return self._progress_aggregator.get_progress(progress_id)
1330
+
1331
+
1332
+ def get_child_progress(self, parent_id: str) -> List[NestedProgressInfo]:
1333
+ """
1334
+ Retrieves all child progress indicators for a given parent.
1335
+
1336
+ :param parent_id: The ID of the parent progress indicator.
1337
+
1338
+ :returns: A list of child NestedProgressInfo objects.
1339
+
1340
+ :rtype: List[NestedProgressInfo]
1341
+ """
1342
+ return self._progress_aggregator.get_children(parent_id)
1343
+
1344
+
1345
+ def get_root_progress(self) -> List[NestedProgressInfo]:
1346
+ """
1347
+ Retrieves all root-level progress indicators (those without parents).
1348
+
1349
+ :returns: A list of root-level NestedProgressInfo objects.
1350
+
1351
+ :rtype: List[NestedProgressInfo]
1352
+ """
1353
+ return self._progress_aggregator.get_root_progress()
1354
+
1355
+
1356
+ def clear_nested_progress(self, progress_id: str) -> Optional[NestedProgressInfo]:
1357
+ """
1358
+ Removes a nested progress indicator and all its descendants.
1359
+
1360
+ This method removes the specified progress indicator from the
1361
+ aggregator, along with all its child progress indicators. It also
1362
+ removes the progress from the running_tasks dictionary.
1363
+
1364
+ :param progress_id: The ID of the progress indicator to remove.
1365
+
1366
+ :returns: The removed NestedProgressInfo, or None if not found.
1367
+
1368
+ :rtype: Optional[NestedProgressInfo]
1369
+ """
1370
+ # Remove from aggregator (handles recursive child removal)
1371
+ removed = self._progress_aggregator.remove_progress(progress_id)
1372
+
1373
+ # Also remove from running_tasks
1374
+ if removed is not None:
1375
+ self._lock.acquire()
1376
+ try:
1377
+ if progress_id in self._running_tasks:
1378
+ del self._running_tasks[progress_id]
1379
+ finally:
1380
+ self._lock.release()
1381
+
1382
+ return removed
1383
+
1384
+
1385
+ def record(self, result: ResultNode):
1386
+ """
1387
+ Records a final result entry for the result object.
1388
+
1389
+ This abstract method must be implemented by derived classes to write
1390
+ a final result record to the stream file. A record is written after
1391
+ test execution completes and contains the final result code, timing,
1392
+ and any errors or failures.
1393
+
1394
+ Record vs Preview:
1395
+ - **preview()**: Called before test execution, result_code is UNSET,
1396
+ no detail section, not counted in totals
1397
+ - **record()**: Called after test execution, result_code is final,
1398
+ includes detail section with errors/failures, counted in totals
1399
+
1400
+ Thread Safety:
1401
+ Derived implementations should use the _lock when updating counters
1402
+ to ensure thread-safe operation when multiple tests complete
1403
+ concurrently.
1404
+
1405
+ :param result: A :class:`ResultNode` object to be recorded. The result's
1406
+ to_json(is_preview=False) method is typically called to
1407
+ generate the record content.
1408
+
1409
+ :returns: None
1410
+
1411
+ :raises: AbstractMethodError if called on the base ResultRecorder class.
1412
+ """
1413
+ raise AbstractMethodError("The 'record' method must be overridden by derived 'ResultRecorder' objects.") from None
1414
+
1415
+
1416
+ def update_render_environment(self):
1417
+ """
1418
+ Publishes the static render resources required by the HTML presentation.
1419
+
1420
+ In the near-standalone testbase framework this is a no-op: publishing the
1421
+ CSS/JavaScript/image resources for the HTML summary is an integration-tier concern.
1422
+ codecraftai-integration-runtime's ``IntegrationJsonResultRecorder`` overrides this method to
1423
+ copy the resources referenced by ``render_info.static_resource_source`` into the results
1424
+ directory.
1425
+
1426
+ :returns: None
1427
+ """
1428
+
1429
+ return
1430
+
1431
+
1432
+ def update_summary(self): # pylint: disable=no-self-use
1433
+ """
1434
+ Writes an update to the test run summary file.
1435
+
1436
+ This abstract method must be implemented by derived classes to persist
1437
+ the current summary state to the summary file. It is called:
1438
+
1439
+ - During __enter__ to write the initial summary
1440
+ - During finalize() to write the final summary
1441
+ - Optionally during the test run to provide real-time updates
1442
+
1443
+ The summary file format depends on the derived class implementation
1444
+ (e.g., JSON for JsonResultRecorder).
1445
+
1446
+ :returns: None
1447
+
1448
+ :raises: AbstractMethodError if called on the base ResultRecorder class.
1449
+ """
1450
+ raise AbstractMethodError("The 'update_summary' method must be overridden by derived 'ResultRecorder' objects.") from None
1451
+
1452
+
1453
+ def write_consolidated_results(self, root_node: dict):
1454
+ """
1455
+ Writes the consolidated results tree to the output file.
1456
+
1457
+ This abstract method must be implemented by derived classes to persist
1458
+ the consolidated result tree to the consolidated results file. It is
1459
+ called by consolidate_results() after building the hierarchical tree
1460
+ from the stream records.
1461
+
1462
+ :param root_node: A dictionary representing the root of the consolidated
1463
+ result tree (typically a JobContainer with nested
1464
+ TestContainers, TestResults, TaskingGroups, and
1465
+ TaskingResults).
1466
+
1467
+ :returns: None
1468
+
1469
+ :raises: AbstractMethodError if called on the base ResultRecorder class.
1470
+ """
1471
+ raise AbstractMethodError("The 'write_consolidated_results' method must be overridden by derived 'ResultRecorder' objects.") from None
1472
+