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,998 @@
1
+ """
2
+ .. module:: ccai.testbase.constraints
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module for constraints management with priority-based resolution.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+
8
+ Constraints System
9
+ ==================
10
+
11
+ The Constraints System provides a mechanism for passing configuration parameters
12
+ and feature requirements from external sources to test execution. It enables
13
+ defining constraint sets as dictionary-like objects, storing constraints from
14
+ multiple origins, and looking up constraints with priority-based resolution.
15
+
16
+ Constraint Hierarchy Patterns
17
+ -----------------------------
18
+
19
+ The constraints system follows a hierarchical pattern with two priority levels:
20
+
21
+ **Priority Levels (highest to lowest):**
22
+
23
+ 1. **Override Parameters** (``ConstraintsOrigin.OVERRIDE_PARAMETER``):
24
+ Runtime overrides that take precedence over all other constraints.
25
+ Use these for temporary configuration changes during test execution.
26
+
27
+ 2. **Site Parameters** (``ConstraintsOrigin.SITE_PARAMETER``):
28
+ Default constraints from site configuration. These provide baseline
29
+ configuration values that can be overridden at runtime.
30
+
31
+ **Scope Hierarchy:**
32
+
33
+ Constraints are organized by scope, following the test execution hierarchy::
34
+
35
+ <session> (root)
36
+ ├── package_a
37
+ │ ├── module_1
38
+ │ │ └── test_function_1
39
+ │ └── module_2
40
+ └── package_b
41
+ └── module_3
42
+
43
+ Each scope can have its own constraints, identified by a unique key in the
44
+ format ``{scope}:{identifier}``. For example::
45
+
46
+ tests.integration:db_config
47
+ tests.unit#test_login:device_config
48
+
49
+ **Resolution Order:**
50
+
51
+ When looking up constraints, the system checks:
52
+
53
+ 1. Override constraints table first (higher priority)
54
+ 2. Site constraints table second (lower priority)
55
+ 3. Returns ``None`` if not found in either table
56
+
57
+ Integration with Dependency Injection
58
+ -------------------------------------
59
+
60
+ The Constraints System integrates with the Dependency Injection System to
61
+ pass configuration parameters to resource factories:
62
+
63
+ **Registration Flow:**
64
+
65
+ 1. Constraints are registered with the :class:`ConstraintsCatalog` using
66
+ :meth:`ConstraintsCatalog.add_constraints`.
67
+ 2. A constraint key is generated and stored with the ``ResourceOrigin``.
68
+ 3. During resource instantiation, the injection system looks up constraints
69
+ using the stored key.
70
+
71
+ **Usage in Source Functions:**
72
+
73
+ Source functions can receive constraints by declaring a ``constraints``
74
+ parameter::
75
+
76
+ def create_database_connection(constraints: Constraints = None):
77
+ host = constraints.get("host", "localhost") if constraints else "localhost"
78
+ port = constraints.get("port", 5432) if constraints else 5432
79
+ return DatabaseConnection(host=host, port=port)
80
+
81
+ **Constraint Passing:**
82
+
83
+ The injection system automatically:
84
+
85
+ 1. Retrieves the ``constraints_key`` from the ``ResourceOrigin``
86
+ 2. Looks up constraints via :meth:`ConstraintsCatalog.lookup_constraints`
87
+ 3. Passes resolved constraints to source functions with a ``constraints`` parameter
88
+ 4. Allows source functions to use default values when constraints are not provided
89
+
90
+ Best Practices for Constraint Organization
91
+ ------------------------------------------
92
+
93
+ **1. Use Meaningful Identifiers:**
94
+
95
+ Choose descriptive identifiers that indicate the purpose of the constraints::
96
+
97
+ # Good: Clear purpose
98
+ catalog.add_constraints(
99
+ origin=ConstraintsOrigin.SITE_PARAMETER,
100
+ originating_scope="tests.integration",
101
+ identifier="database_config",
102
+ constraints=Constraints(host="localhost", port=5432)
103
+ )
104
+
105
+ # Avoid: Vague identifiers
106
+ catalog.add_constraints(
107
+ origin=ConstraintsOrigin.SITE_PARAMETER,
108
+ originating_scope="tests.integration",
109
+ identifier="config1", # Not descriptive
110
+ constraints=Constraints(host="localhost", port=5432)
111
+ )
112
+
113
+ **2. Separate Concerns:**
114
+
115
+ Create separate constraint sets for different configuration aspects::
116
+
117
+ # Database constraints
118
+ db_constraints = Constraints(host="localhost", port=5432, timeout=30)
119
+
120
+ # Feature constraints
121
+ feature_constraints = FeatureConstraints(
122
+ required_features=[DeviceFeatures.Bluetooth],
123
+ checkout=True
124
+ )
125
+
126
+ **3. Use Override Constraints Sparingly:**
127
+
128
+ Reserve override constraints for runtime configuration changes::
129
+
130
+ # Site-level defaults (use for most configurations)
131
+ catalog.add_constraints(
132
+ origin=ConstraintsOrigin.SITE_PARAMETER,
133
+ originating_scope="tests.integration",
134
+ identifier="db_config",
135
+ constraints=Constraints(timeout=30)
136
+ )
137
+
138
+ # Override only when needed (e.g., debugging, special test runs)
139
+ catalog.add_constraints(
140
+ origin=ConstraintsOrigin.OVERRIDE_PARAMETER,
141
+ originating_scope="tests.integration",
142
+ identifier="db_config",
143
+ constraints=Constraints(timeout=120) # Extended timeout for debugging
144
+ )
145
+
146
+ **4. Merge Constraints for Composition:**
147
+
148
+ Use :func:`merge_constraints` to combine base configurations with
149
+ environment-specific or test-specific values::
150
+
151
+ base_constraints = Constraints(timeout=30, retries=3)
152
+ env_constraints = Constraints(host="test-server.local")
153
+ test_constraints = Constraints(debug=True)
154
+
155
+ combined = merge_constraints(base_constraints, env_constraints, test_constraints)
156
+ # Result: {'timeout': 30, 'retries': 3, 'host': 'test-server.local', 'debug': True}
157
+
158
+ **5. Prune Constraints for Performance:**
159
+
160
+ For large test suites, prune constraints to relevant scopes before execution::
161
+
162
+ # Keep only constraints needed for current test run
163
+ catalog.prune_constraints([
164
+ "tests.integration:db_config",
165
+ "tests.integration:api_config"
166
+ ])
167
+
168
+ **6. Use FeatureConstraints for Resource Filtering:**
169
+
170
+ When filtering resources based on capabilities, use :class:`FeatureConstraints`::
171
+
172
+ device_constraints = FeatureConstraints(
173
+ required_features=[DeviceFeatures.Bluetooth, DeviceFeatures.WiFi],
174
+ excluded_features=[DeviceFeatures.Legacy],
175
+ checkout=True # Reserve the device during test
176
+ )
177
+
178
+ **7. Document Constraint Dependencies:**
179
+
180
+ When constraints are required by source functions, document the expected keys::
181
+
182
+ def create_api_client(constraints: Constraints = None):
183
+ '''
184
+ Create an API client with configuration from constraints.
185
+
186
+ Expected constraint keys:
187
+ - api_url (str): Base URL for the API
188
+ - api_key (str): Authentication key
189
+ - timeout (int, optional): Request timeout in seconds (default: 30)
190
+ '''
191
+ if constraints is None:
192
+ constraints = Constraints()
193
+
194
+ return APIClient(
195
+ url=constraints.get("api_url", "http://localhost:8080"),
196
+ key=constraints.get("api_key", ""),
197
+ timeout=constraints.get("timeout", 30)
198
+ )
199
+
200
+ Module Components
201
+ -----------------
202
+
203
+ - :class:`Constraints`: Dictionary wrapper for key-value constraint pairs
204
+ - :class:`ConstraintsOrigin`: Enumeration of constraint origin types
205
+ - :class:`ConstraintsCatalog`: Singleton registry for constraint management
206
+ - :class:`ConstraintsRef`: Reference object associating constraints with metadata
207
+ - :class:`FeatureConstraintKeys`: Standard keys for feature constraints
208
+ - :class:`FeatureConstraints`: Feature-based constraint definitions
209
+ - :func:`create_constraint_key`: Generate unique constraint keys
210
+ - :func:`merge_constraints`: Combine multiple constraint sets
211
+ """
212
+
213
+
214
+ __author__ = "Myron Walker"
215
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
216
+ __credits__ = []
217
+
218
+
219
+ from typing import Any, Dict, List, Union
220
+
221
+ from enum import Enum
222
+
223
+ from ccai.testbase.features import FeatureMask, FeatureTag
224
+
225
+
226
+ class ConstraintsOrigin(str, Enum):
227
+ """
228
+ Enumeration of the origins from which constraints may be provided.
229
+
230
+ This enumeration inherits from both ``str`` and ``Enum`` to allow
231
+ string comparison with enum values.
232
+
233
+ :cvar SITE_PARAMETER: Represents constraints from site configuration
234
+ (lower priority). String value: ``"site-parameter"``.
235
+ :cvar OVERRIDE_PARAMETER: Represents runtime override constraints
236
+ (higher priority). String value: ``"override-parameter"``.
237
+
238
+ Example::
239
+
240
+ >>> origin = ConstraintsOrigin.SITE_PARAMETER
241
+ >>> origin == "site-parameter"
242
+ True
243
+ >>> origin == ConstraintsOrigin.SITE_PARAMETER
244
+ True
245
+ """
246
+
247
+ SITE_PARAMETER = "site-parameter"
248
+ OVERRIDE_PARAMETER = "override-parameter"
249
+
250
+
251
+ class Constraints(dict):
252
+ """
253
+ Dictionary wrapper representing a set of key-value constraint pairs.
254
+
255
+ The :class:`Constraints` class inherits from Python's built-in ``dict``
256
+ class and supports all standard dictionary operations. It provides a
257
+ callable interface to create derived constraint sets with updated values.
258
+
259
+ Example::
260
+
261
+ >>> constraints = Constraints(timeout=30, retries=3)
262
+ >>> constraints["timeout"]
263
+ 30
264
+ >>> derived = constraints(timeout=60)
265
+ >>> derived
266
+ {'timeout': 60, 'retries': 3}
267
+ >>> constraints["timeout"] # Original unchanged
268
+ 30
269
+ """
270
+
271
+ def __init__(self, **kwargs):
272
+ """
273
+ Initialize a new Constraints object with keyword arguments.
274
+
275
+ All keyword arguments are stored as dictionary key-value pairs.
276
+
277
+ :param kwargs: Arbitrary keyword arguments to store as constraints.
278
+ :type kwargs: Any
279
+
280
+ Example::
281
+
282
+ >>> constraints = Constraints(host="localhost", port=5432)
283
+ >>> constraints
284
+ {'host': 'localhost', 'port': 5432}
285
+ """
286
+ for key, value in kwargs.items():
287
+ if not isinstance(value, (int, float, str, bool, list, dict, type(None))):
288
+ raise TypeError(f"Constraint value for '{key}' must be a primitive type, not {type(value).__name__}")
289
+ super().__init__(**kwargs)
290
+ return
291
+
292
+ def __call__(self, **kwargs: Any):
293
+ """
294
+ Create a new dictionary with original values updated by provided arguments.
295
+
296
+ This method implements a prototype pattern, creating a copy of the
297
+ current constraints with additional or overridden values. The original
298
+ :class:`Constraints` object is not modified.
299
+
300
+ :param kwargs: Keyword arguments to add or override in the copy.
301
+ :type kwargs: Any
302
+
303
+ :returns: A new dictionary containing merged key-value pairs.
304
+ :rtype: dict
305
+
306
+ Example::
307
+
308
+ >>> base = Constraints(timeout=30, retries=3)
309
+ >>> derived = base(timeout=60, debug=True)
310
+ >>> derived
311
+ {'timeout': 60, 'retries': 3, 'debug': True}
312
+ >>> base # Original unchanged
313
+ {'timeout': 30, 'retries': 3}
314
+ """
315
+ for key, value in kwargs.items():
316
+ if not isinstance(value, (int, float, str, bool, list, dict, type(None))):
317
+ raise TypeError(f"Constraint value for '{key}' must be a primitive type, not {type(value).__name__}")
318
+ inst = dict(self)
319
+ inst.update(kwargs)
320
+ return inst
321
+
322
+
323
+ class ConstraintsCatalog:
324
+ """
325
+ Singleton registry that manages all registered constraints and provides
326
+ lookup functionality with priority-based resolution.
327
+
328
+ The :class:`ConstraintsCatalog` stores constraints from multiple origins
329
+ (site parameters and override parameters) and provides lookup with
330
+ priority-based resolution where override constraints take precedence
331
+ over site constraints.
332
+
333
+ The catalog maintains two separate storage tables:
334
+
335
+ - ``_site_constraints``: Lower priority constraints from site configuration
336
+ - ``_override_constraints``: Higher priority runtime override constraints
337
+
338
+ Example::
339
+
340
+ >>> catalog = ConstraintsCatalog()
341
+ >>> # Register site-level constraints
342
+ >>> key = catalog.add_constraints(
343
+ ... origin=ConstraintsOrigin.SITE_PARAMETER,
344
+ ... originating_scope="tests.integration",
345
+ ... identifier="db_config",
346
+ ... constraints=Constraints(host="localhost", port=5432)
347
+ ... )
348
+ >>> # Register override constraints (higher priority)
349
+ >>> catalog.add_constraints(
350
+ ... origin=ConstraintsOrigin.OVERRIDE_PARAMETER,
351
+ ... originating_scope="tests.integration",
352
+ ... identifier="db_config",
353
+ ... constraints=Constraints(port=5433)
354
+ ... )
355
+ >>> # Lookup returns override constraints when both exist
356
+ >>> constraints = catalog.lookup_constraints(key)
357
+ >>> constraints["port"]
358
+ 5433
359
+
360
+ .. note::
361
+ Multiple calls to ``ConstraintsCatalog()`` return the same instance
362
+ due to the singleton pattern implementation.
363
+ """
364
+
365
+ _instance = None
366
+ _initialized = False
367
+
368
+
369
+ def __new__(cls):
370
+ """
371
+ Create or return the singleton instance of ConstraintsCatalog.
372
+
373
+ This method implements the singleton pattern by checking if an
374
+ instance already exists. If not, it creates one; otherwise, it
375
+ returns the existing instance.
376
+
377
+ :returns: The singleton ConstraintsCatalog instance.
378
+ :rtype: ConstraintsCatalog
379
+
380
+ Example::
381
+
382
+ >>> catalog1 = ConstraintsCatalog()
383
+ >>> catalog2 = ConstraintsCatalog()
384
+ >>> catalog1 is catalog2
385
+ True
386
+ """
387
+ if cls._instance is None:
388
+ cls._instance = super(ConstraintsCatalog, cls).__new__(cls)
389
+
390
+ return cls._instance
391
+
392
+
393
+ def __init__(self):
394
+ """
395
+ Initialize the ConstraintsCatalog storage tables.
396
+
397
+ This method initializes the internal storage dictionaries only
398
+ on the first instantiation. Subsequent calls to ``__init__``
399
+ (from repeated ``ConstraintsCatalog()`` calls) are no-ops due
400
+ to the ``_initialized`` flag.
401
+
402
+ The following storage tables are created:
403
+
404
+ - ``_site_constraints``: Dictionary mapping constraint keys to
405
+ :class:`ConstraintsRef` objects for site-level constraints.
406
+ - ``_override_constraints``: Dictionary mapping constraint keys to
407
+ :class:`ConstraintsRef` objects for override constraints.
408
+
409
+ Example::
410
+
411
+ >>> catalog = ConstraintsCatalog()
412
+ >>> # Storage tables are initialized internally
413
+ >>> # catalog._site_constraints = {}
414
+ >>> # catalog._override_constraints = {}
415
+ """
416
+ thisType = type(self)
417
+
418
+ if not thisType._initialized:
419
+ thisType._initialized = True
420
+
421
+ self._site_constraints: Dict[str, ConstraintsRef] = {}
422
+ self._override_constraints: Dict[str, ConstraintsRef] = {}
423
+
424
+ return
425
+
426
+
427
+ def add_constraints(self, origin: ConstraintsOrigin, originating_scope: str, identifier: str, constraints: Union[Constraints, "FeatureConstraints", Dict[str, Any]]) -> str:
428
+ """
429
+ Register constraints with the catalog and return the generated key.
430
+
431
+ This method stores the provided constraints in the appropriate
432
+ storage table based on the origin parameter. A unique constraint
433
+ key is generated from the scope and identifier.
434
+
435
+ :param origin: The origin type for the constraints, determining
436
+ which storage table to use.
437
+ :type origin: ConstraintsOrigin
438
+ :param originating_scope: The scope path to which the constraints
439
+ apply (e.g., ``"tests.integration"``).
440
+ :type originating_scope: str
441
+ :param identifier: A unique identifier for this constraint set
442
+ within the scope (e.g., ``"db_config"``).
443
+ :type identifier: str
444
+ :param constraints: The constraint set to store. Can be a
445
+ :class:`Constraints`, :class:`FeatureConstraints`, or dict.
446
+ :type constraints: Union[Constraints, FeatureConstraints, Dict[str, Any]]
447
+
448
+ :returns: The generated constraint key in format
449
+ ``"{originating_scope}:{identifier}"``.
450
+ :rtype: str
451
+
452
+ :raises ValueError: If the origin is not a recognized
453
+ :class:`ConstraintsOrigin` value. The error message includes
454
+ the origin, scope, and identifier for debugging.
455
+
456
+ Example::
457
+
458
+ >>> catalog = ConstraintsCatalog()
459
+ >>> key = catalog.add_constraints(
460
+ ... origin=ConstraintsOrigin.SITE_PARAMETER,
461
+ ... originating_scope="tests.integration",
462
+ ... identifier="db_config",
463
+ ... constraints=Constraints(host="localhost", port=5432)
464
+ ... )
465
+ >>> key
466
+ 'tests.integration:db_config'
467
+
468
+ Example with override constraints::
469
+
470
+ >>> catalog.add_constraints(
471
+ ... origin=ConstraintsOrigin.OVERRIDE_PARAMETER,
472
+ ... originating_scope="tests.integration",
473
+ ... identifier="db_config",
474
+ ... constraints=Constraints(timeout=60)
475
+ ... )
476
+ 'tests.integration:db_config'
477
+ """
478
+ ckey = create_constraint_key(originating_scope, identifier)
479
+
480
+ cref = ConstraintsRef(origin, originating_scope, identifier, constraints)
481
+
482
+ if origin == ConstraintsOrigin.SITE_PARAMETER:
483
+ self._site_constraints[ckey] = cref
484
+ elif origin == ConstraintsOrigin.OVERRIDE_PARAMETER:
485
+ self._override_constraints[ckey] = cref
486
+ else:
487
+ raise ValueError(f"Unknown constraint origin='{origin}' scope='{originating_scope}' identifier={identifier}")
488
+
489
+ return ckey
490
+
491
+
492
+ def lookup_constraints(self, constraints_key: str) -> Union[Constraints, "FeatureConstraints", Dict[str, Any]]:
493
+ """
494
+ Look up constraints by key with priority-based resolution.
495
+
496
+ This method implements priority-based constraint resolution:
497
+
498
+ 1. First checks the override constraints table (higher priority)
499
+ 2. Falls back to site constraints table (lower priority)
500
+ 3. Returns ``None`` if the key is not found in either table
501
+
502
+ :param constraints_key: The constraint key to look up, in format
503
+ ``"{scope}:{identifier}"``.
504
+ :type constraints_key: str
505
+
506
+ :returns: The resolved constraints object if found, or ``None``
507
+ if the key does not exist in either storage table.
508
+ :rtype: Union[Constraints, FeatureConstraints, Dict[str, Any], None]
509
+
510
+ Example::
511
+
512
+ >>> catalog = ConstraintsCatalog()
513
+ >>> # Add site constraints
514
+ >>> catalog.add_constraints(
515
+ ... origin=ConstraintsOrigin.SITE_PARAMETER,
516
+ ... originating_scope="tests.unit",
517
+ ... identifier="config",
518
+ ... constraints=Constraints(timeout=30)
519
+ ... )
520
+ >>> # Lookup returns site constraints
521
+ >>> constraints = catalog.lookup_constraints("tests.unit:config")
522
+ >>> constraints["timeout"]
523
+ 30
524
+
525
+ Example with override priority::
526
+
527
+ >>> # Add override constraints for same key
528
+ >>> catalog.add_constraints(
529
+ ... origin=ConstraintsOrigin.OVERRIDE_PARAMETER,
530
+ ... originating_scope="tests.unit",
531
+ ... identifier="config",
532
+ ... constraints=Constraints(timeout=60)
533
+ ... )
534
+ >>> # Lookup now returns override constraints
535
+ >>> constraints = catalog.lookup_constraints("tests.unit:config")
536
+ >>> constraints["timeout"]
537
+ 60
538
+
539
+ Example with non-existent key::
540
+
541
+ >>> result = catalog.lookup_constraints("nonexistent:key")
542
+ >>> result is None
543
+ True
544
+ """
545
+
546
+ rtnval = None
547
+
548
+ if constraints_key in self._override_constraints:
549
+ cref = self._override_constraints[constraints_key]
550
+ rtnval = cref.constraints
551
+ elif constraints_key in self._site_constraints:
552
+ cref = self._site_constraints[constraints_key]
553
+ rtnval = cref.constraints
554
+
555
+ return rtnval
556
+
557
+
558
+ def prune_constraints(self, keep_keys: List[str]):
559
+ """
560
+ Remove constraints not in the specified scopes from both storage tables.
561
+
562
+ This method optimizes memory usage and lookup performance by removing
563
+ constraints that are not relevant to the current execution context.
564
+ It modifies the catalog in place, affecting both site and override
565
+ constraint tables.
566
+
567
+ :param keep_keys: List of constraint keys to retain. Constraints with
568
+ keys not matching these will be removed.
569
+ :type keep_keys: List[str]
570
+
571
+ :returns: None. The catalog is modified in place.
572
+ :rtype: None
573
+
574
+ Example::
575
+
576
+ >>> catalog = ConstraintsCatalog()
577
+ >>> # Add constraints for multiple scopes
578
+ >>> catalog.add_constraints(
579
+ ... origin=ConstraintsOrigin.SITE_PARAMETER,
580
+ ... originating_scope="tests.integration",
581
+ ... identifier="config",
582
+ ... constraints=Constraints(timeout=30)
583
+ ... )
584
+ >>> catalog.add_constraints(
585
+ ... origin=ConstraintsOrigin.SITE_PARAMETER,
586
+ ... originating_scope="tests.unit",
587
+ ... identifier="config",
588
+ ... constraints=Constraints(timeout=10)
589
+ ... )
590
+ >>> # Prune to keep only integration tests
591
+ >>> catalog.prune_constraints(["tests.integration:config"])
592
+ >>> # Unit test constraints are now removed
593
+ >>> catalog.lookup_constraints("tests.unit:config") is None
594
+ True
595
+ >>> # Integration test constraints are retained
596
+ >>> catalog.lookup_constraints("tests.integration:config") is not None
597
+ True
598
+
599
+ .. note::
600
+ The ``keep_keys`` parameter should contain full constraint keys
601
+ (``"{scope}:{identifier}"`` format), not just scope names.
602
+ """
603
+
604
+ pruned_constraints = {}
605
+ for key in keep_keys:
606
+ if key in self._site_constraints:
607
+ pruned_constraints[key] = self._site_constraints[key]
608
+
609
+ self._site_constraints = pruned_constraints
610
+
611
+ pruned_constraints = {}
612
+ for key in keep_keys:
613
+ if key in self._override_constraints:
614
+ pruned_constraints[key] = self._override_constraints[key]
615
+
616
+ self._override_constraints = pruned_constraints
617
+
618
+ return
619
+
620
+
621
+ class ConstraintsRef:
622
+ """
623
+ Reference object that associates constraints with their origin metadata.
624
+
625
+ The :class:`ConstraintsRef` class stores a reference to a constraints
626
+ object along with metadata about its origin, scope, and identifier.
627
+ This allows tracking where constraints came from and their applicable
628
+ scope during constraint resolution.
629
+
630
+ All stored values are exposed via read-only properties.
631
+
632
+ :ivar _origin: The origin type of the constraints.
633
+ :ivar _originating_scope: The scope to which constraints apply.
634
+ :ivar _identifier: Unique identifier for the constraint set.
635
+ :ivar _constraints: Reference to the actual constraints object.
636
+
637
+ Example::
638
+
639
+ >>> constraints = Constraints(timeout=30)
640
+ >>> ref = ConstraintsRef(
641
+ ... origin=ConstraintsOrigin.SITE_PARAMETER,
642
+ ... originating_scope="tests.integration",
643
+ ... identifier="db_config",
644
+ ... constraints=constraints
645
+ ... )
646
+ >>> ref.origin
647
+ <ConstraintsOrigin.SITE_PARAMETER: 'site-parameter'>
648
+ >>> ref.originating_scope
649
+ 'tests.integration'
650
+ >>> ref.identifier
651
+ 'db_config'
652
+ >>> ref.constraints["timeout"]
653
+ 30
654
+ """
655
+
656
+ def __init__(self, origin: ConstraintsOrigin, originating_scope: str, identifier: str, constraints: Constraints):
657
+ """
658
+ Initialize a ConstraintsRef with origin metadata and constraints.
659
+
660
+ :param origin: The origin type indicating where the constraints
661
+ came from (site parameter or override parameter).
662
+ :type origin: ConstraintsOrigin
663
+ :param originating_scope: The scope path to which these constraints
664
+ apply (e.g., ``"tests.integration"``).
665
+ :type originating_scope: str
666
+ :param identifier: A unique identifier for this constraint set
667
+ within the scope.
668
+ :type identifier: str
669
+ :param constraints: The actual constraints object to reference.
670
+ :type constraints: Union[Constraints, FeatureConstraints, Dict[str, Any]]
671
+
672
+ Example::
673
+
674
+ >>> ref = ConstraintsRef(
675
+ ... origin=ConstraintsOrigin.OVERRIDE_PARAMETER,
676
+ ... originating_scope="tests.unit",
677
+ ... identifier="config",
678
+ ... constraints=Constraints(debug=True)
679
+ ... )
680
+ """
681
+ self._origin = origin
682
+ self._originating_scope = originating_scope
683
+ self._identifier = identifier
684
+ self._constraints = constraints
685
+ return
686
+
687
+ @property
688
+ def constraints(self) -> Union[Constraints, "FeatureConstraints", Dict[str, Any]]:
689
+ """
690
+ The constraint object referenced by this instance.
691
+
692
+ :returns: The stored :class:`Constraints`, :class:`FeatureConstraints`,
693
+ or dict object.
694
+ :rtype: Union[Constraints, FeatureConstraints, Dict[str, Any]]
695
+
696
+ Example::
697
+
698
+ >>> ref = ConstraintsRef(
699
+ ... ConstraintsOrigin.SITE_PARAMETER,
700
+ ... "scope", "id",
701
+ ... Constraints(key="value")
702
+ ... )
703
+ >>> ref.constraints
704
+ {'key': 'value'}
705
+ """
706
+ return self._constraints
707
+
708
+ @property
709
+ def identifier(self) -> str:
710
+ """
711
+ The identifier for the constraint set.
712
+
713
+ :returns: A unique identifier string for this constraint set
714
+ within its scope.
715
+ :rtype: str
716
+
717
+ Example::
718
+
719
+ >>> ref = ConstraintsRef(
720
+ ... ConstraintsOrigin.SITE_PARAMETER,
721
+ ... "tests.unit", "db_config",
722
+ ... Constraints()
723
+ ... )
724
+ >>> ref.identifier
725
+ 'db_config'
726
+ """
727
+ return self._identifier
728
+
729
+ @property
730
+ def origin(self) -> ConstraintsOrigin:
731
+ """
732
+ The origin that supplied the constraints.
733
+
734
+ :returns: A :class:`ConstraintsOrigin` enumeration value indicating
735
+ whether this is a site parameter or override parameter.
736
+ :rtype: ConstraintsOrigin
737
+
738
+ Example::
739
+
740
+ >>> ref = ConstraintsRef(
741
+ ... ConstraintsOrigin.OVERRIDE_PARAMETER,
742
+ ... "scope", "id",
743
+ ... Constraints()
744
+ ... )
745
+ >>> ref.origin
746
+ <ConstraintsOrigin.OVERRIDE_PARAMETER: 'override-parameter'>
747
+ >>> ref.origin == "override-parameter"
748
+ True
749
+ """
750
+ return self._origin
751
+
752
+ @property
753
+ def originating_scope(self) -> str:
754
+ """
755
+ The scope to which the constraints apply.
756
+
757
+ :returns: The scope name string associated with these constraints.
758
+ :rtype: str
759
+
760
+ Example::
761
+
762
+ >>> ref = ConstraintsRef(
763
+ ... ConstraintsOrigin.SITE_PARAMETER,
764
+ ... "tests.integration.api",
765
+ ... "config",
766
+ ... Constraints()
767
+ ... )
768
+ >>> ref.originating_scope
769
+ 'tests.integration.api'
770
+ """
771
+ return self._originating_scope
772
+
773
+
774
+ class FeatureConstraintKeys(str, Enum):
775
+ """
776
+ Enumeration of standard keys used when defining feature constraints.
777
+
778
+ This enumeration inherits from both ``str`` and ``Enum`` to allow
779
+ string comparison with enum values. These keys are used in
780
+ :class:`FeatureConstraints` to specify required and excluded features.
781
+
782
+ :cvar REQUIRED_FEATURES: Key for specifying features that must be
783
+ present. String value: ``"required_features"``.
784
+ :cvar EXCLUDED_FEATURES: Key for specifying features that must not
785
+ be present. String value: ``"excluded_features"``.
786
+
787
+ Example::
788
+
789
+ >>> key = FeatureConstraintKeys.REQUIRED_FEATURES
790
+ >>> key == "required_features"
791
+ True
792
+ >>> constraints = {
793
+ ... FeatureConstraintKeys.REQUIRED_FEATURES: ["bluetooth"],
794
+ ... FeatureConstraintKeys.EXCLUDED_FEATURES: ["legacy"]
795
+ ... }
796
+ """
797
+
798
+ REQUIRED_FEATURES = "required_features"
799
+ EXCLUDED_FEATURES = "excluded_features"
800
+
801
+
802
+ class FeatureConstraints(FeatureMask):
803
+ """
804
+ Specialized :class:`FeatureMask` subclass for feature-based constraints.
805
+
806
+ The :class:`FeatureConstraints` class extends :class:`FeatureMask` to
807
+ provide feature-based constraint definitions with an additional
808
+ ``checkout`` capability. It supports specifying required and excluded
809
+ features for resource filtering.
810
+
811
+ Like :class:`Constraints`, this class provides a callable interface
812
+ to create derived constraint sets with updated values.
813
+
814
+ :ivar checkout: Whether to checkout/reserve the resource.
815
+
816
+ Example::
817
+
818
+ >>> from ccai.testbase.features import FeatureTag
819
+ >>> # Define feature constraints
820
+ >>> constraints = FeatureConstraints(
821
+ ... required_features=[FeatureTag("bluetooth")],
822
+ ... excluded_features=[FeatureTag("legacy")],
823
+ ... checkout=True
824
+ ... )
825
+ >>> # Create derived constraints
826
+ >>> derived = constraints(timeout=30)
827
+ >>> derived["checkout"]
828
+ True
829
+ >>> derived["timeout"]
830
+ 30
831
+ """
832
+
833
+ def __init__(self, *, required_features: List[FeatureTag]=None,
834
+ excluded_features: List[FeatureTag]=None,
835
+ checkout: bool=False, **kwargs):
836
+ """
837
+ Initialize a FeatureConstraints object with feature requirements.
838
+
839
+ :param required_features: List of feature tags that must be present
840
+ for a resource to match. Defaults to ``None`` (no requirements).
841
+ :type required_features: List[FeatureTag], optional
842
+ :param excluded_features: List of feature tags that must not be
843
+ present for a resource to match. Defaults to ``None`` (no exclusions).
844
+ :type excluded_features: List[FeatureTag], optional
845
+ :param checkout: Whether to checkout/reserve the matching resource.
846
+ Defaults to ``False``.
847
+ :type checkout: bool, optional
848
+ :param kwargs: Additional keyword arguments passed to the parent
849
+ :class:`FeatureMask` class.
850
+
851
+ Example::
852
+
853
+ >>> constraints = FeatureConstraints(
854
+ ... required_features=[FeatureTag("wifi")],
855
+ ... checkout=True
856
+ ... )
857
+
858
+ Example with additional kwargs::
859
+
860
+ >>> constraints = FeatureConstraints(
861
+ ... required_features=[FeatureTag("bluetooth")],
862
+ ... excluded_features=[FeatureTag("legacy")],
863
+ ... checkout=False,
864
+ ... custom_param="value"
865
+ ... )
866
+ """
867
+ super().__init__(required_features=required_features,
868
+ excluded_features=excluded_features,
869
+ checkout=checkout, **kwargs)
870
+ return
871
+
872
+ def __call__(self, **kwargs: Any):
873
+ """
874
+ Create a new dictionary with original values updated by provided arguments.
875
+
876
+ This method implements a prototype pattern, creating a copy of the
877
+ current feature constraints with additional or overridden values.
878
+ The original :class:`FeatureConstraints` object is not modified.
879
+
880
+ :param kwargs: Keyword arguments to add or override in the copy.
881
+ :type kwargs: Any
882
+
883
+ :returns: A new dictionary containing merged key-value pairs.
884
+ :rtype: dict
885
+
886
+ Example::
887
+
888
+ >>> base = FeatureConstraints(checkout=True)
889
+ >>> derived = base(timeout=60, debug=True)
890
+ >>> derived["checkout"]
891
+ True
892
+ >>> derived["timeout"]
893
+ 60
894
+ >>> derived["debug"]
895
+ True
896
+ >>> # Original unchanged
897
+ >>> "timeout" in base
898
+ False
899
+ """
900
+ inst = dict(self)
901
+ inst.update(kwargs)
902
+ return inst
903
+
904
+
905
+ def create_constraint_key(source: str, identifier: str) -> str:
906
+ """
907
+ Generate a unique constraint key from source and identifier.
908
+
909
+ This function creates a standardized key format used for both
910
+ registration and lookup operations in the :class:`ConstraintsCatalog`.
911
+
912
+ :param source: The originating scope path (e.g., ``"tests.integration"``).
913
+ :type source: str
914
+ :param identifier: A unique identifier for the constraint set within
915
+ the scope (e.g., ``"db_config"``).
916
+ :type identifier: str
917
+
918
+ :returns: A constraint key in the format ``"{source}:{identifier}"``.
919
+ :rtype: str
920
+
921
+ Example::
922
+
923
+ >>> key = create_constraint_key("tests.integration", "db_config")
924
+ >>> key
925
+ 'tests.integration:db_config'
926
+
927
+ Example with complex scope::
928
+
929
+ >>> key = create_constraint_key(
930
+ ... "tests.integration#test_login",
931
+ ... "device_config"
932
+ ... )
933
+ >>> key
934
+ 'tests.integration#test_login:device_config'
935
+ """
936
+ return f"{source}:{identifier}"
937
+
938
+
939
+ def merge_constraints(*args: Union[Constraints, dict]) -> Constraints:
940
+ """
941
+ Merge multiple constraint sets into a single Constraints object.
942
+
943
+ This function takes a variable number of :class:`Constraints` or dict
944
+ objects and combines them into a new :class:`Constraints` object.
945
+ When multiple constraints have the same key, the value from the last
946
+ constraint in the argument list wins (last-wins semantics).
947
+
948
+ The input constraint objects are not modified.
949
+
950
+ :param args: Variable number of :class:`Constraints` or dict objects
951
+ to merge.
952
+ :type args: Union[Constraints, dict]
953
+
954
+ :returns: A new :class:`Constraints` object containing all merged
955
+ key-value pairs.
956
+ :rtype: Constraints
957
+
958
+ Example::
959
+
960
+ >>> base = Constraints(timeout=30, retries=3)
961
+ >>> override = Constraints(timeout=60)
962
+ >>> merged = merge_constraints(base, override)
963
+ >>> merged
964
+ {'timeout': 60, 'retries': 3}
965
+ >>> # Original unchanged
966
+ >>> base["timeout"]
967
+ 30
968
+
969
+ Example with multiple constraints::
970
+
971
+ >>> env = Constraints(host="localhost", port=5432)
972
+ >>> test = Constraints(port=5433, debug=True)
973
+ >>> runtime = {"timeout": 60}
974
+ >>> merged = merge_constraints(env, test, runtime)
975
+ >>> merged
976
+ {'host': 'localhost', 'port': 5433, 'debug': True, 'timeout': 60}
977
+
978
+ Example with no arguments::
979
+
980
+ >>> empty = merge_constraints()
981
+ >>> empty
982
+ {}
983
+ >>> isinstance(empty, Constraints)
984
+ True
985
+
986
+ .. note::
987
+ In cases where this method is provided with constraints with
988
+ overlapping values, the last constraint with a given key
989
+ overwrites earlier values.
990
+ """
991
+
992
+ combined: Constraints = Constraints()
993
+
994
+ for av in args:
995
+ combined.update(av)
996
+
997
+ return combined
998
+