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,768 @@
1
+ """
2
+ .. module:: ccai.testbase.verification
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module for verification.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+
10
+ __author__ = "Myron Walker"
11
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
12
+ __credits__ = []
13
+
14
+
15
+ from typing import Any, List, Optional, Union, Type
16
+
17
+ import os
18
+ import re
19
+
20
+ from pprint import pformat
21
+
22
+ from ccai.xmodules.xformatting import indent_lines, indent_lines_list
23
+
24
+ from ccai.errors.exceptions import SemanticError
25
+ from ccai.errors.xtraceback import TracebackFormatPolicy
26
+
27
+
28
+ __traceback_format_policy__ = TracebackFormatPolicy.Hide
29
+
30
+
31
+ PREFIX_STD = "Result"
32
+ PREFIX_API = "'{}' API result"
33
+
34
+
35
+ def assert_dict_response_has_keys(to_inspect: dict, expected_keys: List[str], api: Optional[str] = None):
36
+ """
37
+ Verifies that the specified return result from the specified API has the specified expected keys. If the
38
+ verification fails then an :class:`AssertionError` is created and return, otherwise None is returned. It
39
+ is the resposibility of the calling test to raise the returned error.
40
+
41
+ :param to_inspect: The dictionary being inspected
42
+ :param expected_keys: The list of expected keys
43
+ :param api: The optional name of the API that returned the result being inspected.
44
+
45
+ :returns: None
46
+ :raises: :class:`AssertionError` if the verification fails.
47
+ """
48
+
49
+ template = " '{}' key not found."
50
+
51
+ content_errors = verify_dict_has_keys(to_inspect, expected_keys, template)
52
+ if len(content_errors) > 0:
53
+
54
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
55
+
56
+ err_msg_lines = [
57
+ "{} verification failed with the following errors:".format(msg_prefix)
58
+ ]
59
+
60
+ for nxtce in content_errors:
61
+ err_msg_lines.append(nxtce)
62
+
63
+ errmsg = os.linesep.join(err_msg_lines)
64
+ raise AssertionError(errmsg)
65
+
66
+ return
67
+
68
+
69
+ def assert_dict_response_has_paths(to_inspect: dict, expected_paths: List[str], api: Optional[str] = None):
70
+ """
71
+ Verifies that the specified return result from the specified API has the specified expected paths. If the
72
+ verification fails then an :class:`AssertionError` is created and return, otherwise None is returned. It
73
+ is the resposibility of the calling test to raise the returned error.
74
+
75
+ :param to_inspect: The dictionary being inspected
76
+ :param expected_paths: The list of expected slash-separated paths, see :func:`verify_dict_has_paths`
77
+ :param api: The name of the API that returned the result being inspected.
78
+
79
+ :returns: None
80
+ :raises: :class:`AssertionError` if the verification fails.
81
+ """
82
+
83
+ template = " '{}' path not found."
84
+
85
+ content_errors = verify_dict_has_paths(to_inspect, expected_paths, template)
86
+ if len(content_errors) > 0:
87
+
88
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
89
+
90
+ err_msg_lines = [
91
+ "{} verification failed with the following errors:".format(msg_prefix)
92
+ ]
93
+
94
+ for nxtce in content_errors:
95
+ err_msg_lines.append(nxtce)
96
+
97
+ errmsg = os.linesep.join(err_msg_lines)
98
+ raise AssertionError(errmsg)
99
+
100
+ return
101
+
102
+
103
+ def assert_equal(found: Any, expected: Any, api: Optional[str] = None):
104
+ """
105
+ Verifies that the specified return result from the specified API has the specified expected value.
106
+ If the verification fails then an :class:`AssertionError` is created and returned, otherwise None
107
+ is returned. It is the resposibility of the calling test to raise the returned error.
108
+
109
+ :param found: The value to be compared
110
+ :param expected: The expected value
111
+ :param api: The name of the API that returned the result being inspected.
112
+
113
+ :returns: None
114
+ :raises: :class:`AssertionError` if the verification fails.
115
+ """
116
+
117
+ if found != expected:
118
+
119
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
120
+
121
+ err_msg_lines = [
122
+ "{} verification failed because the found value did not match expected value:".format(msg_prefix)
123
+ ]
124
+
125
+ exp_format_lines = pformat(expected, indent=4).strip().splitlines()
126
+ if len(exp_format_lines) == 1:
127
+ err_msg_lines.append("EXPECTED: {}".format(exp_format_lines[0]))
128
+ elif len(exp_format_lines) > 1:
129
+ err_msg_lines.append("EXPECTED:")
130
+ exp_format_lines = indent_lines_list(exp_format_lines, 1)
131
+ err_msg_lines.extend(exp_format_lines)
132
+
133
+ found_format_lines = pformat(found, indent=4).splitlines()
134
+ if len(found_format_lines) == 1:
135
+ err_msg_lines.append("FOUND: {}".format(found_format_lines[0]))
136
+ elif len(found_format_lines) > 1:
137
+ err_msg_lines.append("FOUND:")
138
+ found_format_lines = indent_lines_list(found_format_lines, 1)
139
+ err_msg_lines.extend(found_format_lines)
140
+
141
+ errmsg = os.linesep.join(err_msg_lines)
142
+ raise AssertionError(errmsg)
143
+
144
+ return
145
+
146
+
147
+ def assert_expression(found: str, expr: Union[str, re.Pattern], api: Optional[str] = None):
148
+ """
149
+ Verifies that the specified return result from the specified API has the specified expected value.
150
+ If the verification fails then an :class:`AssertionError` is created and returned, otherwise None
151
+ is returned. It is the resposibility of the calling test to raise the returned error.
152
+
153
+ :param found: The value to be compared
154
+ :param expr: An expression to match with the found value.
155
+ :param api: The name of the API that returned the result being inspected.
156
+
157
+ :returns: None
158
+ :raises: :class:`AssertionError` if the verification fails.
159
+ """
160
+
161
+ if not isinstance(expr, re.Pattern):
162
+ expr = re.compile(expr)
163
+
164
+ mobj = expr.match(found)
165
+ if mobj is None:
166
+
167
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
168
+
169
+ err_msg_lines = [
170
+ "{} verification failed because the found value did not match expression provided.".format(msg_prefix),
171
+ "FOUND: {}".format(found),
172
+ "EXPR: {}".format(expr)
173
+ ]
174
+
175
+ errmsg = os.linesep.join(err_msg_lines)
176
+ raise AssertionError(errmsg)
177
+
178
+ return
179
+
180
+
181
+ def assert_true(found: Any, api: Optional[str] = None):
182
+ """
183
+ Verifies that the specified return result from the specified API is true.
184
+ If the verification fails then an :class:`AssertionError` is created and returned, otherwise None
185
+ is returned. It is the resposibility of the calling test to raise the returned error.
186
+
187
+ :param found: The value to be evaluated
188
+ :param api: The name of the API that returned the result being inspected.
189
+
190
+ :returns: None
191
+ :raises: :class:`AssertionError` if the verification fails.
192
+ """
193
+
194
+ if not found:
195
+
196
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
197
+
198
+ err_msg_lines = [
199
+ "{} verification failed because the found value evaluated to False.".format(msg_prefix)
200
+ ]
201
+
202
+ found_format_lines = pformat(found, indent=4).splitlines()
203
+ if len(found_format_lines) == 1:
204
+ err_msg_lines.append("FOUND: {}".format(found_format_lines[0]))
205
+ elif len(found_format_lines) > 1:
206
+ err_msg_lines.append("FOUND:")
207
+ found_format_lines = indent_lines_list(found_format_lines, 1)
208
+ err_msg_lines.extend(found_format_lines)
209
+
210
+ errmsg = os.linesep.join(err_msg_lines)
211
+ raise AssertionError(errmsg)
212
+
213
+ return
214
+
215
+
216
+ def assert_false(found: Any, api: Optional[str] = None):
217
+ """
218
+ Verifies that the specified return result from the specified API is false.
219
+ If the verification fails then an :class:`AssertionError` is created and returned, otherwise None
220
+ is returned. It is the resposibility of the calling test to raise the returned error.
221
+
222
+ :param found: The value to be evaluated
223
+ :param api: The name of the API that returned the result being inspected.
224
+
225
+ :returns: None
226
+ :raises: :class:`AssertionError` if the verification fails.
227
+ """
228
+
229
+ if found:
230
+
231
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
232
+
233
+ err_msg_lines = [
234
+ "{} verification failed because the found value evaluated to True.".format(msg_prefix)
235
+ ]
236
+
237
+ found_format_lines = pformat(found, indent=4).splitlines()
238
+ if len(found_format_lines) == 1:
239
+ err_msg_lines.append("FOUND: {}".format(found_format_lines[0]))
240
+ elif len(found_format_lines) > 1:
241
+ err_msg_lines.append("FOUND:")
242
+ found_format_lines = indent_lines_list(found_format_lines, 1)
243
+ err_msg_lines.extend(found_format_lines)
244
+
245
+ errmsg = os.linesep.join(err_msg_lines)
246
+ raise AssertionError(errmsg)
247
+
248
+ return
249
+
250
+
251
+ def assert_greater(found: Any, boundary: Any, api: Optional[str] = None):
252
+ """
253
+ Verifies that the specified return result from the specified API has a value greater than the
254
+ boundary specified. If the verification fails then an :class:`AssertionError` is created
255
+ and returned, otherwise None is returned. It is the resposibility of the calling test to raise
256
+ the returned error.
257
+
258
+ :param found: The value being compared
259
+ :param boundary: The boundary value being compared against
260
+ :param api: The name of the API that returned the result being inspected.
261
+
262
+ :returns: None
263
+ :raises: :class:`AssertionError` if the verification fails.
264
+ """
265
+
266
+ if not found > boundary:
267
+
268
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
269
+
270
+ err_msg_lines = [
271
+ "{} verification failed because the found value was not greater than the boundary value:".format(msg_prefix)
272
+ ]
273
+
274
+ bndry_format_lines = pformat(boundary, indent=4).strip().splitlines()
275
+ if len(bndry_format_lines) == 1:
276
+ err_msg_lines.append("BOUNDARY: {}".format(bndry_format_lines[0]))
277
+ elif len(bndry_format_lines) > 1:
278
+ err_msg_lines.append("BOUNDARY:")
279
+ bndry_format_lines = indent_lines_list(bndry_format_lines, 1)
280
+ err_msg_lines.extend(bndry_format_lines)
281
+
282
+ found_format_lines = pformat(found, indent=4).splitlines()
283
+ if len(found_format_lines) == 1:
284
+ err_msg_lines.append("FOUND: {}".format(found_format_lines[0]))
285
+ elif len(found_format_lines) > 1:
286
+ err_msg_lines.append("FOUND:")
287
+ found_format_lines = indent_lines_list(found_format_lines, 1)
288
+ err_msg_lines.extend(found_format_lines)
289
+
290
+ errmsg = os.linesep.join(err_msg_lines)
291
+ raise AssertionError(errmsg)
292
+
293
+ return
294
+
295
+
296
+ def assert_lessthan(found: Any, boundary: Any, api: Optional[str] = None):
297
+ """
298
+ Verifies that the specified return result from the specified API has a value less than the
299
+ boundary specified. If the verification fails then an :class:`AssertionError` is created
300
+ and returned, otherwise None is returned. It is the resposibility of the calling test to raise
301
+ the returned error.
302
+
303
+ :param found: The value being compared
304
+ :param boundary: The boundary value being compared against
305
+ :param api: The name of the API that returned the result being inspected.
306
+
307
+ :returns: None
308
+ :raises: :class:`AssertionError` if the verification fails.
309
+ """
310
+
311
+ if not found < boundary:
312
+
313
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
314
+
315
+ err_msg_lines = [
316
+ "{} verification failed because the found value was not less than the boundary value:".format(msg_prefix)
317
+ ]
318
+
319
+ bndry_format_lines = pformat(boundary, indent=4).strip().splitlines()
320
+ if len(bndry_format_lines) == 1:
321
+ err_msg_lines.append("BOUNDARY: {}".format(bndry_format_lines[0]))
322
+ elif len(bndry_format_lines) > 1:
323
+ err_msg_lines.append("BOUNDARY:")
324
+ bndry_format_lines = indent_lines_list(bndry_format_lines, 1)
325
+ err_msg_lines.extend(bndry_format_lines)
326
+
327
+ found_format_lines = pformat(found, indent=4).splitlines()
328
+ if len(found_format_lines) == 1:
329
+ err_msg_lines.append("FOUND: {}".format(found_format_lines[0]))
330
+ elif len(found_format_lines) > 1:
331
+ err_msg_lines.append("FOUND:")
332
+ found_format_lines = indent_lines_list(found_format_lines, 1)
333
+ err_msg_lines.extend(found_format_lines)
334
+
335
+ errmsg = os.linesep.join(err_msg_lines)
336
+ raise AssertionError(errmsg)
337
+
338
+ return
339
+
340
+
341
+ def assert_list_length(to_inspect: List, expected_len: int, api: Optional[str] = None):
342
+ """
343
+ Verifies that the specified return result from the specified API has the specified expected number of items.
344
+ If the verification fails then an :class:`AssertionError` is created and returned, otherwise None
345
+ is returned. It is the resposibility of the calling test to raise the returned error.
346
+
347
+ :param to_inspect: The list being inspected
348
+ :param expected_len: The expected length of the list
349
+ :param api: The name of the API that returned the result being inspected.
350
+
351
+ :returns: None
352
+ :raises: :class:`AssertionError` if the verification fails.
353
+ """
354
+
355
+ found_len = len(to_inspect)
356
+ if found_len != expected_len:
357
+
358
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
359
+
360
+ err_msg_lines = [
361
+ "{} verification failed because the actual length ({}) did not match expected length ({}):".format(
362
+ msg_prefix, found_len, expected_len),
363
+ "ITEMS:"
364
+ ]
365
+
366
+ for fitem in to_inspect:
367
+ err_msg_lines.append(" {}".format(fitem))
368
+ err_msg_lines.append("")
369
+
370
+ errmsg = os.linesep.join(err_msg_lines)
371
+ raise AssertionError(errmsg)
372
+
373
+ return
374
+
375
+
376
+ def assert_list_length_greater(to_inspect: List, boundary_len: int, api: Optional[str] = None):
377
+ """
378
+ Verifies that the specified return result from the specified API has more items than the specified expected
379
+ number of items. If the verification fails then an :class:`AssertionError` is created and returned,
380
+ otherwise None is returned. It is the resposibility of the calling test to raise the returned error.
381
+
382
+ :param to_inspect: The list being inspected
383
+ :param boundary_len: The boundary that the list length should exceed.
384
+ :param api: The name of the API that returned the result being inspected.
385
+
386
+ :returns: None
387
+ :raises: :class:`AssertionError` if the verification fails.
388
+ """
389
+
390
+ found_len = len(to_inspect)
391
+ if not found_len > boundary_len:
392
+
393
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
394
+
395
+ err_msg_lines = [
396
+ "{} verification failed because the actual length ({}) was not greater than the boundary length ({}):".format(
397
+ msg_prefix, found_len, boundary_len),
398
+ "ITEMS:"
399
+ ]
400
+
401
+ for fitem in to_inspect:
402
+ err_msg_lines.append(" {}".format(fitem))
403
+ err_msg_lines.append("")
404
+
405
+ errmsg = os.linesep.join(err_msg_lines)
406
+ raise AssertionError(errmsg)
407
+
408
+ return
409
+
410
+
411
+ def assert_list_length_less(to_inspect: List, boundary_len: int, api: Optional[str] = None):
412
+ """
413
+ Verifies that the specified return result from the specified API has less items than the specified expected
414
+ number of items. If the verification fails then an :class:`AssertionError` is created and returned,
415
+ otherwise None is returned. It is the resposibility of the calling test to raise the returned error.
416
+
417
+ :param to_inspect: The list being inspected
418
+ :param boundary_len: The boundary the list length should not exceed
419
+ :param api: The name of the API that returned the result being inspected.
420
+
421
+ :returns: None
422
+ :raises: :class:`AssertionError` if the verification fails.
423
+ """
424
+
425
+ found_len = len(to_inspect)
426
+ if not found_len < boundary_len:
427
+
428
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
429
+
430
+ err_msg_lines = [
431
+ "{} result verification failed because the actual length ({}) was not less than the boundary length ({}):".format(
432
+ msg_prefix, found_len, boundary_len),
433
+ "ITEMS:"
434
+ ]
435
+
436
+ for fitem in to_inspect:
437
+ err_msg_lines.append(" {}".format(fitem))
438
+ err_msg_lines.append("")
439
+
440
+ errmsg = os.linesep.join(err_msg_lines)
441
+ raise AssertionError(errmsg)
442
+
443
+ return
444
+
445
+
446
+ def assert_not_equal(found: Any, not_expected: Any, api: Optional[str] = None):
447
+ """
448
+ Verifies that the specified return result from the specified API does not have the specified not
449
+ expected value. If the verification fails then an :class:`AssertionError` is created and returned,
450
+ otherwise None is returned. It is the resposibility of the calling test to raise the returned error.
451
+
452
+ :param found: The value to be compared
453
+ :param not_expected: The value that is not expected to be found
454
+ :param api: The name of the API that returned the result being inspected.
455
+
456
+ :returns: None
457
+ :raises: :class:`AssertionError` if the verification fails.
458
+ """
459
+
460
+ if found == not_expected:
461
+
462
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
463
+
464
+ err_msg_lines = [
465
+ "{} verification failed because the found value matched the not_expected value:".format(msg_prefix)
466
+ ]
467
+
468
+ exp_format_lines = pformat(not_expected, indent=4).strip().splitlines()
469
+ if len(exp_format_lines) == 1:
470
+ err_msg_lines.append("NOT EXPECTED: {}".format(exp_format_lines[0]))
471
+ elif len(exp_format_lines) > 1:
472
+ err_msg_lines.append("NOT EXPECTED:")
473
+ exp_format_lines = indent_lines_list(exp_format_lines, 1)
474
+ err_msg_lines.extend(exp_format_lines)
475
+
476
+ found_format_lines = pformat(found, indent=4).splitlines()
477
+ if len(found_format_lines) == 1:
478
+ err_msg_lines.append("FOUND: {}".format(found_format_lines[0]))
479
+ elif len(found_format_lines) > 1:
480
+ err_msg_lines.append("FOUND:")
481
+ found_format_lines = indent_lines_list(found_format_lines, 1)
482
+ err_msg_lines.extend(found_format_lines)
483
+
484
+ errmsg = os.linesep.join(err_msg_lines)
485
+ raise AssertionError(errmsg)
486
+
487
+ return
488
+
489
+ def assert_type(found: Any, exp_type: Type, api: Optional[str] = None):
490
+ """
491
+ Verifies that the specified return result from the specified API has the specified expected value type.
492
+ If the verification fails then an :class:`AssertionError` is created and returned, otherwise None
493
+ is returned. It is the resposibility of the calling test to raise the returned error.
494
+
495
+ :param found: The value to check the type of
496
+ :param exp_type: The expected value type
497
+ :param api: The name of the API that returned the result being inspected.
498
+
499
+ :returns: None
500
+ :raises: :class:`AssertionError` if the verification fails.
501
+ """
502
+
503
+ found_type = type(found)
504
+ if found_type != exp_type:
505
+
506
+ msg_prefix = PREFIX_STD if api is None else PREFIX_API.format(api)
507
+
508
+ err_msg_lines = [
509
+ "{} verification failed because the found value did not the expected type={}.".format(msg_prefix, exp_type),
510
+ "FOUND_TYPE: {}".format(found_type)
511
+ ]
512
+
513
+ errmsg = os.linesep.join(err_msg_lines)
514
+ raise AssertionError(errmsg)
515
+
516
+ return
517
+
518
+
519
+ def verify_dict_has_keys(to_inspect: dict, expected_keys: List[str], template: Optional[str]=None) -> List[str]:
520
+ """
521
+ Verifies that the expected keys are found in the dictionary provided. Returns a list of
522
+ any keys that are missing.
523
+
524
+ :param to_inspect: The dictionary being inspected
525
+ :param expected_keys: The list of expected keys
526
+ :param template: Optional template used with missing key names to produce error messages.
527
+
528
+ :returns: None
529
+ :raises: :class:`AssertionError` if the verification fails.
530
+ """
531
+
532
+ missing_list = []
533
+
534
+ if template is not None:
535
+ for exkey in expected_keys:
536
+ if exkey not in to_inspect:
537
+ missing_list.append(template.format(exkey))
538
+ else:
539
+ for exkey in expected_keys:
540
+ if exkey not in to_inspect:
541
+ missing_list.append(exkey)
542
+
543
+ return missing_list
544
+
545
+ def verify_dict_has_paths(to_inspect: dict, expected_paths: List[str], template: Optional[str]=None) -> List[str]:
546
+ """
547
+ Verifies that the expected paths are found in the dictionary provided. Returns a list of
548
+ any paths that are missing.
549
+
550
+ A path is a slash-separated list of keys, such as ``"spec/template/metadata"``, that is
551
+ followed down through nested dictionaries. Leading and trailing slashes are ignored. The
552
+ path is found when the key named by its last segment exists, whatever the value of that
553
+ key is.
554
+
555
+ :param to_inspect: The dictionary being inspected
556
+ :param expected_paths: The list of expected paths to leafs in a dictionary
557
+ :param template: Optional template used with missing paths to produce error messages.
558
+
559
+ :returns: A list of the missing paths, formatted with the template when one is provided.
560
+ """
561
+
562
+ missing_list = []
563
+
564
+ for next_exp_path in expected_paths:
565
+ search_path = next_exp_path.strip("/")
566
+
567
+ leaf_parts = []
568
+ found = _verify_dict_has_paths_descend(search_path, to_inspect, leaf_parts)
569
+
570
+ if not found:
571
+ if template is not None:
572
+ missing_list.append(template.format(next_exp_path))
573
+ else:
574
+ missing_list.append(next_exp_path)
575
+
576
+ return missing_list
577
+
578
+ def _verify_dict_has_paths_descend(search_path: str, cursor: dict, leaf_parts: List[str]) -> bool:
579
+ """
580
+ Searches the dictionary at ``cursor`` for ``search_path``, descending into nested dictionaries
581
+ whose accumulated path is a prefix of ``search_path``.
582
+
583
+ :param search_path: The slash-separated path being searched for, without leading or trailing slashes.
584
+ :param cursor: The dictionary at the current level of the descent.
585
+ :param leaf_parts: The keys that lead from the root dictionary to ``cursor``.
586
+
587
+ :returns: True if the path was found at or below ``cursor``, otherwise False.
588
+ """
589
+
590
+ found = False
591
+
592
+ cursor_path = "/".join(leaf_parts)
593
+
594
+ for nxt_key in cursor.keys():
595
+ nxt_key_str = str(nxt_key)
596
+
597
+ if len(leaf_parts) > 0:
598
+ nxt_path = cursor_path + "/" + nxt_key_str
599
+ else:
600
+ nxt_path = nxt_key_str
601
+
602
+ if nxt_path == search_path:
603
+ found = True
604
+ elif search_path.startswith(nxt_path + "/"):
605
+ nxt_val = cursor[nxt_key]
606
+ if isinstance(nxt_val, dict):
607
+ desc_leaf_parts = [lp for lp in leaf_parts]
608
+ desc_leaf_parts.append(nxt_key_str)
609
+ found = _verify_dict_has_paths_descend(search_path, nxt_val, desc_leaf_parts)
610
+
611
+ if found:
612
+ break
613
+
614
+ return found
615
+
616
+
617
+ class RaisesContext:
618
+ """
619
+ The object bound by :func:`raises`, carrying the caught exception.
620
+
621
+ The exception is available as :attr:`exception` only after the ``with``
622
+ block exits, since that is when it has been raised and caught. Reading it
623
+ inside the block is a mistake worth naming rather than returning ``None``
624
+ for, so it raises :class:`SemanticError`.
625
+ """
626
+
627
+ def __init__(self, expected: Union[Type[BaseException], tuple],
628
+ match: Optional[Union[str, re.Pattern]] = None) -> None:
629
+ """
630
+ :param expected: The exception type, or tuple of types, to expect.
631
+ :param match: Optional pattern the exception's text must contain.
632
+ """
633
+ self._expected = expected
634
+ self._match = match
635
+ self._exception = None
636
+ self._complete = False
637
+ return
638
+
639
+ @property
640
+ def exception(self) -> BaseException:
641
+ """
642
+ The exception that was caught.
643
+
644
+ :returns: The caught exception.
645
+
646
+ :raises SemanticError: If read before the ``with`` block has exited.
647
+ """
648
+ if self._complete is False:
649
+ raise SemanticError(
650
+ "The 'exception' of a 'raises' block is only available after "
651
+ "the block exits, because that is when the exception has been "
652
+ "raised and caught.")
653
+
654
+ return self._exception
655
+
656
+ @property
657
+ def value(self) -> BaseException:
658
+ """
659
+ Alias of :attr:`exception`.
660
+
661
+ :returns: The caught exception.
662
+ """
663
+ return self.exception
664
+
665
+ def __enter__(self) -> "RaisesContext":
666
+ """
667
+ :returns: This context, to be bound by the ``as`` clause.
668
+ """
669
+ return self
670
+
671
+ def __exit__(self, exc_type, exc_value, exc_traceback) -> bool:
672
+ """
673
+ Accept the expected exception; let anything else propagate.
674
+
675
+ :param exc_type: Type of the raised exception, or ``None``.
676
+ :param exc_value: The raised exception, or ``None``.
677
+ :param exc_traceback: The traceback, unused.
678
+
679
+ :returns: ``True`` to suppress the expected exception.
680
+
681
+ :raises AssertionError: If no exception was raised, or if one was
682
+ raised whose text does not match the requested pattern.
683
+ """
684
+ self._complete = True
685
+
686
+ if exc_type is None:
687
+ expected_name = _describe_exception_types(self._expected)
688
+ raise AssertionError(
689
+ "Expected {} to be raised, but the block completed "
690
+ "normally.".format(expected_name))
691
+
692
+ if not issubclass(exc_type, self._expected):
693
+ # Not what was asked for. Propagating beats reporting a failure
694
+ # here, because the real exception and its traceback are more
695
+ # useful than an assertion describing it second-hand.
696
+ return False
697
+
698
+ if self._match is not None:
699
+ found = str(exc_value)
700
+ if re.search(self._match, found) is None:
701
+ raise AssertionError(
702
+ "Expected {} matching {!r} to be raised. A {} was raised, "
703
+ "but its text does not match:{}{}".format(
704
+ _describe_exception_types(self._expected),
705
+ self._match if isinstance(self._match, str)
706
+ else self._match.pattern,
707
+ exc_type.__name__, os.linesep,
708
+ indent_lines(found, 1)))
709
+
710
+ self._exception = exc_value
711
+
712
+ return True
713
+
714
+
715
+ def raises(expected: Union[Type[BaseException], tuple],
716
+ match: Optional[Union[str, re.Pattern]] = None) -> RaisesContext:
717
+ """
718
+ Assert that the ``with`` block raises the expected exception.
719
+
720
+ Unlike ``expect_exception``, which marks a whole test as expected to
721
+ raise, this scopes the expectation to the statements in the block, so a
722
+ test can go on to make assertions about the exception it caught and about
723
+ anything else.
724
+
725
+ A different exception type is not caught. It propagates with its own
726
+ traceback intact, which says more than an assertion describing it
727
+ second-hand would.
728
+
729
+ Example::
730
+
731
+ from ccai import testbase
732
+
733
+ with testbase.raises(ValueError):
734
+ int("not a number")
735
+
736
+ with testbase.raises(SchemaSemanticError) as caught:
737
+ validate(spec=spec)
738
+
739
+ assert "inst-a" in str(caught.exception)
740
+
741
+ # Or match the text directly, without binding the exception.
742
+ with testbase.raises(ValueError, match="invalid literal"):
743
+ int("not a number")
744
+
745
+ :param expected: The exception type, or a tuple of types, to expect.
746
+ :param match: Optional pattern searched for in the exception's text,
747
+ as a string or compiled pattern.
748
+
749
+ :returns: A context manager binding the caught exception.
750
+
751
+ :raises AssertionError: If the block raises nothing, or raises an
752
+ expected type whose text does not match ``match``.
753
+ """
754
+ return RaisesContext(expected, match=match)
755
+
756
+
757
+ def _describe_exception_types(expected: Union[Type[BaseException], tuple]) -> str:
758
+ """
759
+ Name an exception type, or a tuple of them, for a failure message.
760
+
761
+ :param expected: The type or tuple of types.
762
+
763
+ :returns: A readable description.
764
+ """
765
+ if isinstance(expected, tuple):
766
+ return " or ".join([item.__name__ for item in expected])
767
+
768
+ return expected.__name__