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,842 @@
1
+ """
2
+ .. module:: ccai.testbase.coupling.integrationcoupling
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module containing the :class:`IntegrationCoupling` class and associated reflection
5
+ methods for integrating external automation resources into the test environment.
6
+
7
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
8
+
9
+ The IntegrationCoupling module provides the primary mechanism for integrating external automation
10
+ resources into the TestBase test execution framework. It defines a structured lifecycle for
11
+ resource discovery, connectivity establishment, and diagnostic collection.
12
+
13
+ The module includes:
14
+
15
+ * :class:`IntegrationCoupling` - Base class for external resource integration
16
+ * :func:`is_integration_coupling` - Helper to detect IntegrationCoupling subclasses
17
+ * :func:`sort_integration_couplings_by_precedence` - Orders couplings by precedence value
18
+
19
+ Example usage::
20
+
21
+ from ccai.testbase.coupling.integrationcoupling import IntegrationCoupling
22
+
23
+ class DeviceIntegration(IntegrationCoupling):
24
+ '''
25
+ Integration coupling for device automation.
26
+ '''
27
+
28
+ integration_root = "devices"
29
+ integration_section = "network"
30
+ integration_leaf = "router"
31
+ integration_class = "DeviceIntegration"
32
+
33
+ @classmethod
34
+ def declare_precedence(cls) -> int:
35
+ return 100
36
+
37
+ # ... implement other abstract methods
38
+
39
+ """
40
+
41
+ __author__ = "Myron Walker"
42
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
43
+ __credits__ = []
44
+
45
+
46
+ from typing import Any, Dict, List, Tuple, TypeVar
47
+
48
+ import inspect
49
+
50
+ from ccai.testbase.coupling.basecoupling import BaseCoupling
51
+ from ccai.errors.exceptions import AbstractMethodError
52
+
53
+
54
+ class IntegrationCoupling(BaseCoupling):
55
+ """
56
+ The :class:`IntegrationCoupling` class serves as the base class for declaring automation
57
+ integration requirements. It provides a structured lifecycle for integrating external
58
+ resources such as devices, services, and databases into the test environment.
59
+
60
+ The test sequencer queries the class hierarchies of tests included in an automation run
61
+ to identify required integration couplings. Each coupling type is uniquely identified by
62
+ its integration key, which follows a hierarchical naming scheme.
63
+
64
+ Integration Key Format::
65
+
66
+ {integration_root}:{integration_section}:{integration_leaf}:{integration_class}
67
+
68
+ Lifecycle Methods (in order of execution):
69
+
70
+ 1. :meth:`attach_to_framework` - Register with test framework
71
+ 2. :meth:`attach_to_environment` - Process configuration and validate environment
72
+ 3. :meth:`collect_resources` - Acquire resources from resource management system
73
+ 4. :meth:`establish_connectivity` - Establish connections to compute/storage resources
74
+ 5. :meth:`establish_presence` - Verify resource availability and readiness
75
+ 6. :meth:`diagnostic` - Generate diagnostic information at checkpoints
76
+
77
+ :cvar integration_root: Top-level category for the integration (e.g., "devices")
78
+ :cvar integration_section: Subcategory for the integration (e.g., "network")
79
+ :cvar integration_leaf: Specific type within the section (e.g., "router")
80
+ :cvar integration_class: Implementation class name (e.g., "CiscoRouter")
81
+ :cvar integration_activated: Class-level flag indicating if the integration is activated
82
+
83
+ :ivar _connectivity_establish: Internal flag tracking connectivity establishment status
84
+ :ivar _presence_establish: Internal flag tracking presence establishment status
85
+
86
+ Example usage::
87
+
88
+ from ccai.testbase.coupling.integrationcoupling import IntegrationCoupling
89
+
90
+ class DatabaseIntegration(IntegrationCoupling):
91
+ '''
92
+ Integration coupling for database resources.
93
+ '''
94
+
95
+ integration_root = "services"
96
+ integration_section = "database"
97
+ integration_leaf = "postgresql"
98
+ integration_class = "DatabaseIntegration"
99
+
100
+ @classmethod
101
+ def attach_to_framework(cls, **kwargs):
102
+ # Register with framework
103
+ return
104
+
105
+ @classmethod
106
+ def attach_to_environment(cls, **kwargs):
107
+ # Validate database configuration
108
+ return
109
+
110
+ @classmethod
111
+ def collect_resources(cls):
112
+ # Acquire database connection pool
113
+ return
114
+
115
+ @classmethod
116
+ def declare_precedence(cls) -> int:
117
+ return 50 # Lower values initialize first
118
+
119
+ @classmethod
120
+ def establish_connectivity(cls, allow_missing_devices=False):
121
+ errors = []
122
+ reports = {}
123
+ # Establish database connections
124
+ return (errors, reports)
125
+
126
+ @classmethod
127
+ def establish_presence(cls):
128
+ errors = []
129
+ reports = {}
130
+ # Verify database is accessible
131
+ return (errors, reports)
132
+
133
+ @classmethod
134
+ def diagnostic(cls, label, level, diag_folder):
135
+ # Generate database diagnostic information
136
+ return
137
+
138
+ @classmethod
139
+ def validate_item_configuration(cls, item_info):
140
+ errors = []
141
+ warnings = []
142
+ # Validate configuration items
143
+ return (errors, warnings)
144
+
145
+ .. seealso::
146
+ :class:`BaseCoupling` for the base coupling type
147
+ :class:`ConfigurationCoupling` for environment configuration
148
+ :func:`is_integration_coupling` for type detection
149
+ :func:`sort_integration_couplings_by_precedence` for ordering couplings
150
+ """
151
+
152
+ integration_root: str = None
153
+ integration_section: str = None
154
+ integration_leaf: str = None
155
+ integration_class: str = None
156
+
157
+ integration_activated: bool = False
158
+
159
+ def __init__(self, *args, **kwargs): # pylint: disable=unused-argument
160
+ """
161
+ Initializes a new :class:`IntegrationCoupling` instance.
162
+
163
+ The constructor initializes the internal state tracking flags for connectivity
164
+ and presence establishment to False. These flags are updated during the
165
+ lifecycle method execution.
166
+
167
+ :param args: Variable positional arguments (unused, for compatibility).
168
+ :param kwargs: Variable keyword arguments (unused, for compatibility).
169
+
170
+ Example usage::
171
+
172
+ integration = MyIntegrationCoupling()
173
+ print(integration.connectivity_establish) # False
174
+ print(integration.presence_establish) # False
175
+ """
176
+ super().__init__()
177
+
178
+ self._connectivity_establish = False
179
+ self._presence_establish = False
180
+
181
+ return
182
+
183
+ @property
184
+ def connectivity_establish(self) -> bool:
185
+ """
186
+ Read-only property indicating whether connectivity has been established.
187
+
188
+ This property returns the current state of the connectivity establishment
189
+ flag. The flag is set to True after the :meth:`establish_connectivity`
190
+ method successfully completes.
191
+
192
+ :returns: True if connectivity has been established, False otherwise.
193
+
194
+ Example usage::
195
+
196
+ integration = MyIntegrationCoupling()
197
+ if not integration.connectivity_establish:
198
+ # Connectivity not yet established
199
+ pass
200
+ """
201
+ return self._connectivity_establish
202
+
203
+ @property
204
+ def presence_establish(self) -> bool:
205
+ """
206
+ Read-only property indicating whether presence has been established.
207
+
208
+ This property returns the current state of the presence establishment
209
+ flag. The flag is set to True after the :meth:`establish_presence`
210
+ method successfully completes.
211
+
212
+ :returns: True if presence has been established, False otherwise.
213
+
214
+ Example usage::
215
+
216
+ integration = MyIntegrationCoupling()
217
+ if not integration.presence_establish:
218
+ # Presence not yet established
219
+ pass
220
+ """
221
+ return self._presence_establish
222
+
223
+ @classmethod
224
+ def attach_to_framework(cls, **kwargs):
225
+ """
226
+ Registers the integration coupling with the test framework for participation.
227
+
228
+ This is the first lifecycle method called during integration initialization.
229
+ It allows the coupling to register with the test framework and participate
230
+ in registration processes. This enables the framework to ignore couplings
231
+ that are not being included by any test.
232
+
233
+ The DEFAULT implementation is a no-op. Framework attachment is an
234
+ OPTIONAL phase: most couplings do their real work in
235
+ ``attach_to_environment``, and the near-standalone testbase framework
236
+ has no framework-level state a coupling must attach to. Integration
237
+ tiers that do (e.g. the landscape-backed coupling hierarchy) override
238
+ this hook in their own coupling base classes.
239
+
240
+ :param kwargs: Variable keyword arguments for framework-specific
241
+ registration parameters, forwarded by the sequencer.
242
+
243
+ :returns: None. This method does not return a value.
244
+ """
245
+ return
246
+
247
+ @classmethod
248
+ def attach_to_environment(cls, **kwargs):
249
+ """
250
+ Processes configuration information and validates the test environment.
251
+
252
+ This lifecycle method is called after :meth:`attach_to_framework` to allow
253
+ the coupling to process configuration information and verify that it has
254
+ a valid environment and configuration to run in.
255
+
256
+ :param kwargs: Variable keyword arguments for environment-specific configuration
257
+ parameters. The specific parameters accepted depend on the derived class
258
+ implementation.
259
+
260
+ :returns: None. This method does not return a value.
261
+
262
+ :raises ccai.errors.exceptions.AKitMissingConfigError: When required
263
+ configuration is missing.
264
+ :raises ccai.errors.exceptions.ConfigurationError: When configuration
265
+ validation fails.
266
+ :raises ccai.errors.exceptions.AbstractMethodError: When called on the base
267
+ :class:`IntegrationCoupling` class without being overloaded by a derived class.
268
+
269
+ Example usage::
270
+
271
+ class MyIntegration(IntegrationCoupling):
272
+ '''
273
+ Custom integration implementation.
274
+ '''
275
+
276
+ @classmethod
277
+ def attach_to_environment(cls, **kwargs):
278
+ config = kwargs.get('config')
279
+ if config is None:
280
+ raise AKitMissingConfigError("Configuration required")
281
+ # Validate configuration
282
+ return
283
+
284
+ .. note::
285
+ This method must be overloaded by derived classes. Calling this method on
286
+ the base :class:`IntegrationCoupling` class will raise an
287
+ :class:`AbstractMethodError`.
288
+ """
289
+ errmsg = "The 'attach_to_environment' method must be overloaded by derived integration coupling types."
290
+ raise AbstractMethodError(errmsg)
291
+
292
+ @classmethod
293
+ def collect_resources(cls):
294
+ """
295
+ Connects with a resource management system to acquire required resources.
296
+
297
+ This lifecycle method is called after :meth:`attach_to_environment` to allow
298
+ the coupling to connect with a resource management system and gain access
299
+ to the resources required for the automation run.
300
+
301
+ :returns: None. This method does not return a value.
302
+
303
+ :raises ccai.errors.exceptions.AKitResourceError: When resource acquisition
304
+ fails.
305
+ :raises ccai.errors.exceptions.AbstractMethodError: When called on the base
306
+ :class:`IntegrationCoupling` class without being overloaded by a derived class.
307
+
308
+ Example usage::
309
+
310
+ class MyIntegration(IntegrationCoupling):
311
+ '''
312
+ Custom integration implementation.
313
+ '''
314
+
315
+ @classmethod
316
+ def collect_resources(cls):
317
+ # Acquire resources from resource manager
318
+ resource_manager = get_resource_manager()
319
+ cls._resources = resource_manager.acquire('my_resources')
320
+ return
321
+
322
+ .. note::
323
+ This method must be overloaded by derived classes. Calling this method on
324
+ the base :class:`IntegrationCoupling` class will raise an
325
+ :class:`AbstractMethodError`.
326
+ """
327
+ errmsg = "The 'collect_resources' method must be overloaded by derived integration coupling types."
328
+ raise AbstractMethodError(errmsg)
329
+
330
+ @classmethod
331
+ def declare_precedence(cls) -> int:
332
+ """
333
+ Declares the ordinal precedence value for integration initialization order.
334
+
335
+ This method returns an integer precedence value that determines the order
336
+ in which integration couplings are initialized. Lower values are initialized
337
+ first, allowing couplings with dependencies to be initialized after their
338
+ dependencies.
339
+
340
+ :returns: An integer precedence value. Lower values indicate higher priority
341
+ (initialized first).
342
+
343
+ :raises ccai.errors.exceptions.AbstractMethodError: When called on the base
344
+ :class:`IntegrationCoupling` class without being overloaded by a derived class.
345
+
346
+ Example usage::
347
+
348
+ class DatabaseIntegration(IntegrationCoupling):
349
+ '''
350
+ Database integration with low precedence (initialized early).
351
+ '''
352
+
353
+ @classmethod
354
+ def declare_precedence(cls) -> int:
355
+ return 10 # Initialize early
356
+
357
+ class ServiceIntegration(IntegrationCoupling):
358
+ '''
359
+ Service integration that depends on database.
360
+ '''
361
+
362
+ @classmethod
363
+ def declare_precedence(cls) -> int:
364
+ return 100 # Initialize after database
365
+
366
+ .. note::
367
+ This method must be overloaded by derived classes. Calling this method on
368
+ the base :class:`IntegrationCoupling` class will raise an
369
+ :class:`AbstractMethodError`.
370
+
371
+ .. seealso::
372
+ :func:`sort_integration_couplings_by_precedence` for ordering couplings
373
+ """
374
+ errmsg = "The 'declare_precedence' method must be overloaded by derived integration coupling types."
375
+ raise AbstractMethodError(errmsg)
376
+
377
+ @classmethod
378
+ def diagnostic(cls, label: str, level: int, diag_folder: str): # pylint: disable=unused-argument
379
+ """
380
+ Generates diagnostic information at specified checkpoints during test execution.
381
+
382
+ This method is called by the sequencer when building a diagnostic package at
383
+ diagnostic points in the automation sequence. Each diagnostic package has its
384
+ own storage location, so derived classes can write diagnostic information to
385
+ their specified output folder.
386
+
387
+ Common diagnostic points include:
388
+
389
+ * ``pre-run`` - Before test execution begins
390
+ * ``post-run`` - After test execution completes
391
+
392
+ :param label: A string identifying the diagnostic point (e.g., "pre-run", "post-run").
393
+ :param level: An integer specifying the maximum diagnostic level to run diagnostics
394
+ for. Higher levels may include more detailed diagnostic information.
395
+ :param diag_folder: The output folder path where diagnostic information should be
396
+ written. Each coupling should write its diagnostics to this folder.
397
+
398
+ :returns: None. This method does not return a value.
399
+
400
+ :raises ccai.errors.exceptions.AbstractMethodError: When called on the base
401
+ :class:`IntegrationCoupling` class without being overloaded by a derived class.
402
+
403
+ Example usage::
404
+
405
+ class MyIntegration(IntegrationCoupling):
406
+ '''
407
+ Custom integration implementation.
408
+ '''
409
+
410
+ @classmethod
411
+ def diagnostic(cls, label, level, diag_folder):
412
+ import os
413
+ import json
414
+
415
+ # Collect diagnostic data
416
+ diag_data = {
417
+ 'label': label,
418
+ 'level': level,
419
+ 'status': cls.get_status()
420
+ }
421
+
422
+ # Write to diagnostic folder
423
+ diag_file = os.path.join(diag_folder, 'my_integration_diag.json')
424
+ with open(diag_file, 'w') as f:
425
+ json.dump(diag_data, f, indent=2)
426
+ return
427
+
428
+ .. note::
429
+ This method must be overloaded by derived classes. Calling this method on
430
+ the base :class:`IntegrationCoupling` class will raise an
431
+ :class:`AbstractMethodError`.
432
+ """
433
+ # ============================================================================
434
+ # DIAGNOSTIC FOLDER STRUCTURE - INTEGRATION IMPLEMENTATION GUIDE
435
+ # ============================================================================
436
+ # When implementing this method in a derived class, follow these guidelines
437
+ # for creating the diagnostic folder structure:
438
+ #
439
+ # 1. CREATE INTEGRATION-SPECIFIC SUBFOLDER:
440
+ # Each integration should create its own subfolder within diag_folder:
441
+ #
442
+ # integration_diag_folder = os.path.join(diag_folder, "my_integration")
443
+ # os.makedirs(integration_diag_folder, exist_ok=True)
444
+ #
445
+ # 2. RESPECT DIAGNOSTIC LEVEL:
446
+ # Use the level parameter to control verbosity:
447
+ # - Level 1-3: Basic diagnostics (quick status, minimal files)
448
+ # - Level 4-6: Standard diagnostics (logs, configuration)
449
+ # - Level 7-9: Detailed diagnostics (full dumps, traces)
450
+ #
451
+ # 3. HANDLE ERRORS INTERNALLY:
452
+ # Catch and handle errors within the diagnostic method to prevent
453
+ # propagation to the test framework. Log errors but don't raise.
454
+ #
455
+ # 4. RESULTING FOLDER STRUCTURE:
456
+ # <test_results_dir>/diagnostics/<label>/
457
+ # └── <integration_name>/ <- Created by this method
458
+ # ├── status.json <- Basic diagnostic file
459
+ # ├── logs.txt <- Standard diagnostic file
460
+ # └── full_dump.json <- Detailed diagnostic file
461
+ #
462
+ # Example implementation:
463
+ #
464
+ # @classmethod
465
+ # def diagnostic(cls, label, level, diag_folder):
466
+ # import os
467
+ # import json
468
+ #
469
+ # # Create integration-specific subfolder
470
+ # my_diag_folder = os.path.join(diag_folder, "myservice")
471
+ # os.makedirs(my_diag_folder, exist_ok=True)
472
+ #
473
+ # # Level 1+: Basic status
474
+ # if level >= 1:
475
+ # status = cls._get_status()
476
+ # with open(os.path.join(my_diag_folder, "status.json"), 'w') as f:
477
+ # json.dump(status, f, indent=2)
478
+ #
479
+ # # Level 5+: Logs
480
+ # if level >= 5:
481
+ # logs = cls._get_logs()
482
+ # with open(os.path.join(my_diag_folder, "logs.txt"), 'w') as f:
483
+ # f.write(logs)
484
+ #
485
+ # # Level 9: Full dump
486
+ # if level >= 9:
487
+ # dump = cls._get_full_dump()
488
+ # with open(os.path.join(my_diag_folder, "full_dump.json"), 'w') as f:
489
+ # json.dump(dump, f, indent=2)
490
+ # ============================================================================
491
+ errmsg = "The 'diagnostic' method must be overloaded by derived integration coupling types."
492
+ raise AbstractMethodError(errmsg)
493
+
494
+ @classmethod
495
+ def establish_connectivity(cls, allow_missing_devices: bool=False) -> Tuple[List[str], Dict]:
496
+ """
497
+ Establishes connections to compute or storage resources.
498
+
499
+ This lifecycle method is called after :meth:`collect_resources` to establish
500
+ actual connections to the resources. It handles connection setup and reports
501
+ any errors or connectivity status.
502
+
503
+ :param allow_missing_devices: A boolean indicating whether missing devices should
504
+ be allowed without raising errors. When True, missing devices are reported
505
+ but do not cause failures. When False (default), missing devices result in
506
+ error messages.
507
+
508
+ :returns: A tuple containing:
509
+
510
+ * ``errors`` (List[str]): A list of error messages for failed connections.
511
+ Empty list if all connections succeeded.
512
+ * ``reports`` (Dict): A dictionary of connectivity reports for devices,
513
+ keyed by device identifier. The structure of reports depends on the
514
+ derived class implementation.
515
+
516
+ :raises ccai.errors.exceptions.AbstractMethodError: When called on the base
517
+ :class:`IntegrationCoupling` class without being overloaded by a derived class.
518
+
519
+ Example usage::
520
+
521
+ class MyIntegration(IntegrationCoupling):
522
+ '''
523
+ Custom integration implementation.
524
+ '''
525
+
526
+ @classmethod
527
+ def establish_connectivity(cls, allow_missing_devices=False):
528
+ errors = []
529
+ reports = {}
530
+
531
+ for device in cls._devices:
532
+ try:
533
+ connection = device.connect()
534
+ reports[device.id] = {'status': 'connected'}
535
+ except ConnectionError as err:
536
+ if not allow_missing_devices:
537
+ errors.append(f"Failed to connect to {device.id}: {err}")
538
+ reports[device.id] = {'status': 'failed', 'error': str(err)}
539
+
540
+ return (errors, reports)
541
+
542
+ .. note::
543
+ This method must be overloaded by derived classes. Calling this method on
544
+ the base :class:`IntegrationCoupling` class will raise an
545
+ :class:`AbstractMethodError`.
546
+ """
547
+ errmsg = "The 'establish_connectivity' method must be overloaded by derived integration coupling types."
548
+ raise AbstractMethodError(errmsg)
549
+
550
+ @classmethod
551
+ def establish_presence(cls) -> Tuple[List[str], Dict]:
552
+ """
553
+ Verifies resource availability and readiness after connectivity is established.
554
+
555
+ This lifecycle method is called after :meth:`establish_connectivity` to verify
556
+ that resources are not only connected but also available and ready for use.
557
+ This may involve health checks, capability verification, or other readiness
558
+ assessments.
559
+
560
+ :returns: A tuple containing:
561
+
562
+ * ``errors`` (List[str]): A list of error messages for resources that
563
+ failed presence verification. Empty list if all resources are ready.
564
+ * ``reports`` (Dict): A dictionary of presence reports for resources,
565
+ keyed by resource identifier. The structure of reports depends on the
566
+ derived class implementation.
567
+
568
+ :raises ccai.errors.exceptions.AbstractMethodError: When called on the base
569
+ :class:`IntegrationCoupling` class without being overloaded by a derived class.
570
+
571
+ Example usage::
572
+
573
+ class MyIntegration(IntegrationCoupling):
574
+ '''
575
+ Custom integration implementation.
576
+ '''
577
+
578
+ @classmethod
579
+ def establish_presence(cls):
580
+ errors = []
581
+ reports = {}
582
+
583
+ for device in cls._devices:
584
+ try:
585
+ health = device.health_check()
586
+ reports[device.id] = {'status': 'ready', 'health': health}
587
+ except Exception as err:
588
+ errors.append(f"Device {device.id} not ready: {err}")
589
+ reports[device.id] = {'status': 'not_ready', 'error': str(err)}
590
+
591
+ return (errors, reports)
592
+
593
+ .. note::
594
+ This method must be overloaded by derived classes. Calling this method on
595
+ the base :class:`IntegrationCoupling` class will raise an
596
+ :class:`AbstractMethodError`.
597
+ """
598
+ errmsg = "The 'establish_presence' method must be overloaded by derived integration coupling types."
599
+ raise AbstractMethodError(errmsg)
600
+
601
+ @classmethod
602
+ def get_integration_key(cls) -> str:
603
+ """
604
+ Returns the unique hierarchical identifier string for this integration coupling.
605
+
606
+ The integration key uniquely identifies an integration coupling type using a
607
+ hierarchical naming scheme with four components separated by colons.
608
+
609
+ Key Format::
610
+
611
+ {integration_root}:{integration_section}:{integration_leaf}:{integration_class}
612
+
613
+ :returns: A string containing the integration key in the format
614
+ ``root:section:leaf:class``. If any component is None, the string "None"
615
+ is included in that position.
616
+
617
+ Example usage::
618
+
619
+ class DeviceIntegration(IntegrationCoupling):
620
+ integration_root = "devices"
621
+ integration_section = "network"
622
+ integration_leaf = "router"
623
+ integration_class = "DeviceIntegration"
624
+
625
+ key = DeviceIntegration.get_integration_key()
626
+ # Returns: "devices:network:router:DeviceIntegration"
627
+
628
+ .. seealso::
629
+ :meth:`get_integration_key_parts` for getting key components as a tuple
630
+ """
631
+ rtnval = f"{cls.integration_root}:{cls.integration_section}:{cls.integration_leaf}:{cls.integration_class}"
632
+ return rtnval
633
+
634
+ @classmethod
635
+ def get_integration_key_parts(cls) -> Tuple[str, str, str, str]:
636
+ """
637
+ Returns the integration key components as a tuple.
638
+
639
+ This method provides access to the individual components of the integration
640
+ key without string parsing. Useful when you need to work with specific
641
+ parts of the key hierarchy.
642
+
643
+ :returns: A tuple containing four elements:
644
+
645
+ * ``integration_root`` (str): Top-level category
646
+ * ``integration_section`` (str): Subcategory
647
+ * ``integration_leaf`` (str): Specific type
648
+ * ``integration_class`` (str): Implementation class name
649
+
650
+ Example usage::
651
+
652
+ class DeviceIntegration(IntegrationCoupling):
653
+ integration_root = "devices"
654
+ integration_section = "network"
655
+ integration_leaf = "router"
656
+ integration_class = "DeviceIntegration"
657
+
658
+ root, section, leaf, cls_name = DeviceIntegration.get_integration_key_parts()
659
+ # root = "devices"
660
+ # section = "network"
661
+ # leaf = "router"
662
+ # cls_name = "DeviceIntegration"
663
+
664
+ .. seealso::
665
+ :meth:`get_integration_key` for getting the key as a formatted string
666
+ """
667
+ rtnval = (cls.integration_root, cls.integration_section, cls.integration_leaf, cls.integration_class)
668
+ return rtnval
669
+
670
+ @classmethod
671
+ def validate_item_configuration(cls, item_info: Dict[str, Any]) -> Tuple[List[str], List[str]]:
672
+ """
673
+ Validates configuration items for this integration coupling.
674
+
675
+ This method is called to validate configuration items before test execution.
676
+ It checks the provided configuration dictionary for errors and warnings,
677
+ allowing early detection of configuration problems.
678
+
679
+ :param item_info: A dictionary containing configuration item information to
680
+ validate. The expected structure and keys depend on the derived class
681
+ implementation.
682
+
683
+ :returns: A tuple containing:
684
+
685
+ * ``errors`` (List[str]): A list of critical configuration error messages.
686
+ These indicate problems that will prevent the integration from functioning.
687
+ * ``warnings`` (List[str]): A list of non-critical warning messages.
688
+ These indicate potential issues that may not prevent operation but
689
+ should be addressed.
690
+
691
+ :raises ccai.errors.exceptions.AbstractMethodError: When called on the base
692
+ :class:`IntegrationCoupling` class without being overloaded by a derived class.
693
+
694
+ Example usage::
695
+
696
+ class MyIntegration(IntegrationCoupling):
697
+ '''
698
+ Custom integration implementation.
699
+ '''
700
+
701
+ @classmethod
702
+ def validate_item_configuration(cls, item_info):
703
+ errors = []
704
+ warnings = []
705
+
706
+ # Check required fields
707
+ if 'host' not in item_info:
708
+ errors.append("Missing required 'host' configuration")
709
+
710
+ # Check optional fields
711
+ if 'timeout' not in item_info:
712
+ warnings.append("No 'timeout' specified, using default")
713
+
714
+ # Validate values
715
+ if 'port' in item_info:
716
+ port = item_info['port']
717
+ if not isinstance(port, int) or port < 1 or port > 65535:
718
+ errors.append(f"Invalid port value: {port}")
719
+
720
+ return (errors, warnings)
721
+
722
+ .. note::
723
+ This method must be overloaded by derived classes. Calling this method on
724
+ the base :class:`IntegrationCoupling` class will raise an
725
+ :class:`AbstractMethodError`.
726
+ """
727
+ errmsg = "The 'validate_item_configuration' method must be overloaded by derived integration coupling types."
728
+ raise AbstractMethodError(errmsg)
729
+
730
+
731
+ IntegrationCouplingType = TypeVar('IntegrationCouplingType', bound=IntegrationCoupling)
732
+
733
+
734
+ def is_integration_coupling(cls) -> bool:
735
+ """
736
+ Determines if a type is an :class:`IntegrationCoupling` subclass.
737
+
738
+ This helper function is used to detect whether a given class is a valid
739
+ :class:`IntegrationCoupling` subclass (but not the base class itself).
740
+ It is useful for filtering and processing integration couplings during
741
+ dependency injection and test execution.
742
+
743
+ :param cls: The class to check. Can be any type.
744
+
745
+ :returns: True if the class is a subclass of :class:`IntegrationCoupling` but not
746
+ the :class:`IntegrationCoupling` base class itself. False otherwise.
747
+
748
+ Example usage::
749
+
750
+ from ccai.testbase.coupling.integrationcoupling import (
751
+ IntegrationCoupling,
752
+ is_integration_coupling
753
+ )
754
+
755
+ class MyIntegration(IntegrationCoupling):
756
+ pass
757
+
758
+ # Check various types
759
+ is_integration_coupling(MyIntegration) # True - valid subclass
760
+ is_integration_coupling(IntegrationCoupling) # False - base class
761
+ is_integration_coupling(str) # False - not a coupling
762
+ is_integration_coupling("not a class") # False - not a class
763
+
764
+ .. note::
765
+ This function returns False for the :class:`IntegrationCoupling` base class
766
+ itself, as the base class should not be used directly for integration.
767
+ """
768
+ is_integmi = False
769
+ if inspect.isclass(cls) and cls is not IntegrationCoupling and issubclass(cls, IntegrationCoupling):
770
+ is_integmi = True
771
+ return is_integmi
772
+
773
+
774
+ def sort_integration_couplings_by_precedence(coupling_list: List[IntegrationCoupling]) -> List[IntegrationCoupling]:
775
+ """
776
+ Orders integration couplings by their declared precedence values.
777
+
778
+ This function takes a list of :class:`IntegrationCoupling` classes and returns
779
+ a new list ordered by the precedence values declared by each coupling. Couplings
780
+ with lower precedence values appear first in the returned list.
781
+
782
+ Couplings with the same precedence value are grouped together in the output,
783
+ maintaining their relative order within the group.
784
+
785
+ :param coupling_list: A list of :class:`IntegrationCoupling` classes to sort.
786
+ Each class must implement the :meth:`declare_precedence` method.
787
+
788
+ :returns: A new list containing the same couplings ordered by precedence value
789
+ from lowest (first) to highest (last).
790
+
791
+ Example usage::
792
+
793
+ from ccai.testbase.coupling.integrationcoupling import (
794
+ IntegrationCoupling,
795
+ sort_integration_couplings_by_precedence
796
+ )
797
+
798
+ class DatabaseIntegration(IntegrationCoupling):
799
+ @classmethod
800
+ def declare_precedence(cls) -> int:
801
+ return 10
802
+
803
+ class ServiceIntegration(IntegrationCoupling):
804
+ @classmethod
805
+ def declare_precedence(cls) -> int:
806
+ return 50
807
+
808
+ class UIIntegration(IntegrationCoupling):
809
+ @classmethod
810
+ def declare_precedence(cls) -> int:
811
+ return 100
812
+
813
+ couplings = [UIIntegration, DatabaseIntegration, ServiceIntegration]
814
+ ordered = sort_integration_couplings_by_precedence(None, couplings)
815
+ # ordered = [DatabaseIntegration, ServiceIntegration, UIIntegration]
816
+
817
+ .. note::
818
+ This function has an incorrect signature with an unused ``self`` parameter.
819
+ When calling this function, pass ``None`` as the first argument.
820
+
821
+ .. seealso::
822
+ :meth:`IntegrationCoupling.declare_precedence` for declaring precedence values
823
+ """
824
+ precedence_table = {}
825
+
826
+ for coupling in coupling_list:
827
+ precedence = coupling.declare_precedence()
828
+ precedence_level_list = None
829
+ if precedence in precedence_table:
830
+ precedence_level_list = precedence_table[precedence]
831
+ else:
832
+ precedence_level_list = []
833
+ precedence_table[precedence] = precedence_level_list
834
+ precedence_level_list.append(coupling)
835
+
836
+ precedence_keys_sorted = sorted(precedence_table.keys())
837
+
838
+ ordered_couplings = []
839
+ for precedence in precedence_keys_sorted:
840
+ ordered_couplings.extend(precedence_table[precedence])
841
+
842
+ return ordered_couplings