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,56 @@
1
+ """
2
+ .. module:: ccai.testbase.properties.assumptions
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module for the assume() function and UnsatisfiedAssumption exception.
5
+
6
+ The ``assume()`` function allows test authors to express preconditions
7
+ on generated data within property tests. When a precondition is not met,
8
+ the current example is silently skipped without being counted as a failure.
9
+
10
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
11
+ """
12
+
13
+
14
+
15
+ __author__ = "Myron Walker"
16
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
17
+ __credits__ = []
18
+
19
+
20
+ class UnsatisfiedAssumption(Exception):
21
+ """
22
+ Sentinel exception raised when ``assume()`` receives a falsy condition.
23
+
24
+ This exception is caught by the ``PropertyRunner`` to skip the current
25
+ example without recording a failure. It is NOT a test failure — it
26
+ signals that the current set of generated inputs is invalid for the
27
+ property under test.
28
+ """
29
+ pass
30
+
31
+
32
+ def assume(condition) -> None:
33
+ """
34
+ Skip the current property test example if the condition is not met.
35
+
36
+ When called with a falsy value, raises ``UnsatisfiedAssumption``,
37
+ which the ``PropertyRunner`` catches and treats as "skip this example."
38
+ The example is not counted toward ``examples_run`` and no
39
+ ``CheckResult`` is created for it.
40
+
41
+ Example::
42
+
43
+ from ccai.testbase.properties import given, assume
44
+ from ccai.testbase.properties import strategies as st
45
+
46
+ @given(x=st.integers(), y=st.integers())
47
+ def test_division(x, y):
48
+ assume(y != 0)
49
+ result = x / y
50
+ assert result * y == x
51
+
52
+ :param condition: A value that is evaluated for truthiness.
53
+ :raises UnsatisfiedAssumption: When ``condition`` is falsy.
54
+ """
55
+ if not condition:
56
+ raise UnsatisfiedAssumption()
@@ -0,0 +1,173 @@
1
+ """
2
+ .. module:: ccai.testbase.properties.decorators
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module for property test decorators — @given and expect_exception.
5
+
6
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
7
+ """
8
+
9
+
10
+
11
+ __author__ = "Myron Walker"
12
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
13
+ __credits__ = []
14
+
15
+
16
+ import functools
17
+ import inspect
18
+
19
+ from ccai.testbase.properties.strategies import Strategy
20
+
21
+
22
+ def given(*args, **kwargs) -> callable:
23
+ """
24
+ Decorator that marks a test function as a property-based test.
25
+
26
+ Accepts keyword arguments mapping parameter names to ``Strategy``
27
+ instances. An optional ``constraints`` keyword provides a dictionary
28
+ of execution constraints for the property test runner.
29
+
30
+ The decorator stores a ``_property_`` attribute on the decorated
31
+ function containing the strategy mappings and constraints. This attribute
32
+ is detected by the test sequencer to invoke the ``PropertyRunner``
33
+ rather than the standard test execution path.
34
+
35
+ Parameters not listed in the ``@given`` kwargs are resolved through
36
+ the normal TestBase injection system.
37
+
38
+ The ``@given`` decorator is composable with existing TestBase
39
+ decorators (``@mark_categories``, ``@mark_priority``, ``@mark_keywords``).
40
+
41
+ Supported Constraint Keys:
42
+ - ``max_examples`` (int): Number of examples to generate. Default is 100.
43
+ - ``max_shrink_attempts`` (int): Maximum shrinking iterations. Default is 100.
44
+
45
+ .. note::
46
+ The property test seed is always derived from the job seed and fully
47
+ qualified test name. It cannot be overridden per-test. This ensures
48
+ that a given ``--job-seed`` always reproduces the same property test
49
+ results across all property tests in the job.
50
+
51
+ Example::
52
+
53
+ from ccai.testbase.properties import given
54
+ from ccai.testbase.properties import strategies as st
55
+
56
+ @given(x=st.integers(), y=st.integers())
57
+ def test_addition_commutative(x, y):
58
+ assert x + y == y + x
59
+
60
+ @given(x=st.integers(min_value=0, max_value=100),
61
+ constraints={"max_examples": 50})
62
+ def test_positive_square(x):
63
+ assert x * x >= 0
64
+
65
+ :param kwargs: Keyword arguments mapping parameter names to ``Strategy``
66
+ instances, plus an optional ``constraints`` keyword for execution
67
+ constraints dictionary.
68
+ :returns: A decorator function.
69
+ """
70
+ # Extract constraints if provided
71
+ prop_constraints = kwargs.pop("constraints", {})
72
+
73
+ # Positional strategies bind to the decorated function's parameters in
74
+ # order, which is how other property libraries allow @given(st.text()).
75
+ # They are resolved against the signature at decoration time so a
76
+ # mismatch is reported here rather than as a confusing call error.
77
+ positional = list(args)
78
+ for strategy in positional:
79
+ if not isinstance(strategy, Strategy):
80
+ raise TypeError(
81
+ "Expected a Strategy instance for a positional argument, "
82
+ f"got {type(strategy).__name__}"
83
+ )
84
+
85
+ # Validate that all remaining kwargs are Strategy instances
86
+ strategies = {}
87
+ for name, strategy in kwargs.items():
88
+ if not isinstance(strategy, Strategy):
89
+ raise TypeError(
90
+ f"Expected a Strategy instance for parameter '{name}', "
91
+ f"got {type(strategy).__name__}"
92
+ )
93
+ strategies[name] = strategy
94
+
95
+ def decorator(fn):
96
+ if positional:
97
+ names = list(inspect.signature(fn).parameters.keys())
98
+ # Positional strategies fill the LAST parameters, leaving any
99
+ # leading ones (self, injected fixtures) to testbase's own
100
+ # injection — matching how the keyword form composes.
101
+ if len(positional) > len(names):
102
+ raise TypeError(
103
+ f"@given received {len(positional)} positional "
104
+ f"strategies but {fn.__name__} takes {len(names)} "
105
+ "parameters."
106
+ )
107
+ targets = names[len(names) - len(positional):]
108
+ for name, strategy in zip(targets, positional):
109
+ if name in strategies:
110
+ raise TypeError(
111
+ f"@given got both a positional and a keyword "
112
+ f"strategy for parameter '{name}'."
113
+ )
114
+ strategies[name] = strategy
115
+
116
+ @functools.wraps(fn)
117
+ def wrapper(*args, **kw):
118
+ return fn(*args, **kw)
119
+
120
+ # Attach property metadata for discovery by the test sequencer
121
+ wrapper._property_ = {
122
+ "strategies": strategies,
123
+ "constraints": prop_constraints,
124
+ }
125
+
126
+ return wrapper
127
+
128
+ return decorator
129
+
130
+
131
+ def expect_exception(exception_type: type, reason: str = "") -> callable:
132
+ """
133
+ Decorator that marks a test as expected to raise a specific exception.
134
+
135
+ This decorator does NOT catch the exception itself. It sets an
136
+ ``_expect_exception_`` attribute on the function that the test
137
+ sequencer reads to determine how to handle the exception at
138
+ test scope exit time.
139
+
140
+ When the expected exception is raised:
141
+ - The test result is marked as **PASSED** (expected failure occurred).
142
+ - Any individual check results (e.g., from property testing)
143
+ are still recorded as they occurred.
144
+
145
+ When no exception is raised:
146
+ - The test result is marked as **FAILED** with a message
147
+ indicating the expected failure did not occur.
148
+
149
+ When a different exception type is raised:
150
+ - The test result is marked as **ERRORED** (unexpected exception).
151
+
152
+ Example::
153
+
154
+ from ccai.testbase.properties import expect_exception
155
+
156
+ @expect_exception(AssertionError, reason="Known URL encoding edge case")
157
+ @given(params=st.explicit([{'a': '1', 'b': '2'}]))
158
+ def test_known_failure(params):
159
+ assert params != params # Will raise AssertionError
160
+
161
+ :param exception_type: The exception class that is expected to be raised.
162
+ :param reason: An optional human-readable reason for the expected failure.
163
+ :returns: A decorator function.
164
+ """
165
+
166
+ def decorator(fn):
167
+ fn._expect_exception_ = {
168
+ "exception_type": exception_type,
169
+ "reason": reason,
170
+ }
171
+ return fn
172
+
173
+ return decorator
@@ -0,0 +1,449 @@
1
+ """
2
+ .. module:: ccai.testbase.properties.propertyrunner
3
+ :platform: Darwin, Linux, Unix, Windows
4
+ :synopsis: Module for property test execution — generation, shrinking, and result creation.
5
+
6
+ The :class:`PropertyRunner` orchestrates the execution of a single
7
+ property test function. It generates random inputs using declared
8
+ strategies, invokes the test function for each set of inputs, handles
9
+ failure detection with automatic counterexample shrinking, and creates
10
+ :class:`CheckResult` instances for each generated example.
11
+
12
+ .. moduleauthor:: Myron Walker <myron.walker@gmail.com>
13
+ """
14
+
15
+
16
+
17
+ __author__ = "Myron Walker"
18
+ __copyright__ = "Copyright 2025, Code Craft AI LLC"
19
+ __credits__ = []
20
+
21
+
22
+ from typing import Any, Callable, Dict, Optional
23
+
24
+ import hashlib
25
+ import json
26
+ import os
27
+ import random
28
+ import uuid
29
+
30
+ from ccai.errors.xtraceback import create_traceback_detail, format_traceback_detail
31
+
32
+ from ccai.xmodules.xformatting import indent_lines_list
33
+
34
+ from ccai.testbase.properties.assumptions import UnsatisfiedAssumption
35
+ from ccai.testbase.properties.strategies import Strategy
36
+
37
+ from ccai.testbase.results.model.checkresult import CheckResult
38
+ from ccai.testbase.results.model.resultcode import ResultCode
39
+ from ccai.testbase.results.model.testresult import TestResult
40
+
41
+
42
+ DEFAULT_MAX_EXAMPLES = 100
43
+ DEFAULT_MAX_SHRINK_ATTEMPTS = 100
44
+
45
+ # Environment variable name for the per-property max-examples cap. When set
46
+ # to a positive integer, ``PropertyRunner`` caps every property test's
47
+ # ``max_examples`` at this value, regardless of what the test specifies.
48
+ # This is intended for fast-CI runs where the full case sweep is too slow;
49
+ # nightly / release runs leave the variable unset and get full coverage.
50
+ ENV_MAX_EXAMPLES_CAP = "TESTBASE_MAX_EXAMPLES_CAP"
51
+
52
+
53
+ def _resolve_max_examples_cap() -> Optional[int]:
54
+ """
55
+ Read the ``TESTBASE_MAX_EXAMPLES_CAP`` environment variable and
56
+ return it as a positive integer, or ``None`` when the variable
57
+ is unset, empty, or not a positive integer.
58
+
59
+ :returns: The cap value, or ``None`` to indicate "no cap".
60
+ """
61
+ raw = os.environ.get(ENV_MAX_EXAMPLES_CAP)
62
+ if raw is None:
63
+ return None
64
+
65
+ raw_stripped = raw.strip()
66
+ if len(raw_stripped) == 0:
67
+ return None
68
+
69
+ try:
70
+ cap = int(raw_stripped)
71
+ except ValueError:
72
+ return None
73
+
74
+ if cap <= 0:
75
+ return None
76
+
77
+ return cap
78
+
79
+
80
+ def derive_test_seed(job_seed: str, test_name: str) -> int:
81
+ """
82
+ Derives a unique, deterministic seed for a specific test from the job seed.
83
+
84
+ Uses SHA-256 hashing of the combined job seed and fully qualified test
85
+ name to produce a reproducible per-test seed. The same inputs always
86
+ produce the same output seed, ensuring that property tests are
87
+ reproducible when the same job seed is used.
88
+
89
+ :param job_seed: The job-level seed value (typically a UUID string).
90
+ :param test_name: The fully qualified test name (e.g., "pkg.module#test_func").
91
+ :returns: An integer seed derived from the combination of job_seed and test_name.
92
+ """
93
+ combined = f"{job_seed}:{test_name}"
94
+ hash_bytes = hashlib.sha256(combined.encode()).digest()
95
+ return int.from_bytes(hash_bytes[:8], byteorder='big')
96
+
97
+
98
+ class PropertyRunner:
99
+ """
100
+ Orchestrates the execution of a property test function.
101
+
102
+ The runner generates random inputs using declared strategies, invokes
103
+ the test function for each set of inputs, detects failures, performs
104
+ automatic counterexample shrinking, and creates :class:`CheckResult`
105
+ instances for each generated example.
106
+
107
+ The per-test seed is always derived deterministically from the job seed
108
+ and fully qualified test name. This ensures that a given ``--job-seed``
109
+ value always reproduces the same property test results. Each generated
110
+ random value is derived from the previous PRNG state, guaranteeing a
111
+ fully deterministic sequence.
112
+
113
+ :param constraints: Dictionary of execution constraints. Supported keys:
114
+ ``max_examples`` (int, default 100), ``max_shrink_attempts`` (int, default 100).
115
+ :param job_seed: The job-level seed for reproducibility (UUID string).
116
+ :param test_name: The fully qualified test name.
117
+ :param recorder: The result recorder for writing check results.
118
+ :param parent_inst: The instance ID of the parent test result.
119
+ :param test_result: The parent :class:`TestResult` that receives the property metadata.
120
+ """
121
+
122
+ def __init__(self, constraints: dict, job_seed: str,
123
+ test_name: str, recorder: Any, parent_inst: str,
124
+ test_result: Optional[TestResult] = None):
125
+ """
126
+ Initializes the PropertyRunner.
127
+
128
+ :param constraints: Dictionary of execution constraints. Supported keys:
129
+ ``max_examples`` (int, default 100), ``max_shrink_attempts`` (int, default 100).
130
+ :param job_seed: The job-level seed for reproducibility (UUID string).
131
+ :param test_name: The fully qualified test name.
132
+ :param recorder: The result recorder for writing check results.
133
+ :param parent_inst: The instance ID of the parent test result.
134
+ :param test_result: Optional parent :class:`TestResult` of the property test. When
135
+ given, :meth:`run` attaches the property metadata to it (see
136
+ :meth:`TestResult.set_property_metadata`) on every outcome: passed, falsified,
137
+ errored, and aborted for too many rejected assumptions. Defaults to ``None``,
138
+ in which case the metadata is only returned by :meth:`run` when it passes.
139
+ """
140
+ configured_max_examples = constraints.get("max_examples", DEFAULT_MAX_EXAMPLES)
141
+ env_cap = _resolve_max_examples_cap()
142
+ if env_cap is not None and env_cap < configured_max_examples:
143
+ self._max_examples = env_cap
144
+ else:
145
+ self._max_examples = configured_max_examples
146
+
147
+ self._max_shrink_attempts = constraints.get("max_shrink_attempts", DEFAULT_MAX_SHRINK_ATTEMPTS)
148
+ self._job_seed = job_seed
149
+ self._test_name = test_name
150
+ self._recorder = recorder
151
+ self._parent_inst = parent_inst
152
+ self._test_result = test_result
153
+
154
+ # The per-test seed is always derived from the job seed and test name.
155
+ # This ensures full reproducibility: same job seed produces the same
156
+ # random sequence for every property test in the job.
157
+ self._test_seed = derive_test_seed(job_seed, test_name)
158
+
159
+ self._rng = random.Random(self._test_seed)
160
+ return
161
+
162
+ @property
163
+ def test_seed(self) -> int:
164
+ """
165
+ The resolved per-test seed used for random generation.
166
+ """
167
+ return self._test_seed
168
+
169
+ @property
170
+ def job_seed(self) -> str:
171
+ """
172
+ The job-level seed.
173
+ """
174
+ return self._job_seed
175
+
176
+ def run(self, test_func: Callable, strategies: Dict[str, Strategy],
177
+ injected_args: Dict[str, Any]) -> Dict[str, Any]:
178
+ """
179
+ Executes the property test by generating examples and calling the test function.
180
+
181
+ For each of ``max_examples`` iterations:
182
+
183
+ 1. Generates random values using the declared strategies
184
+ 2. Merges generated values with injected parameters
185
+ 3. Calls the test function with the combined arguments
186
+ 4. Records a :class:`CheckResult` for the example
187
+
188
+ If any example fails with an ``AssertionError``, the runner triggers
189
+ the shrinking engine to find a minimal counterexample, then records
190
+ the test as FAILED. If an unexpected exception occurs, the test is
191
+ recorded as ERRORED without shrinking.
192
+
193
+ When the runner was constructed with a ``test_result``, the property
194
+ metadata is attached to it before this method returns or raises, so the
195
+ parent :class:`TestResult` serializes it as ``property_metadata``.
196
+
197
+ :param test_func: The property test function to invoke.
198
+ :param strategies: Dictionary mapping parameter names to Strategy instances.
199
+ :param injected_args: Dictionary of injection-resolved parameter values.
200
+ :returns: A dictionary containing property test metadata with keys:
201
+ ``examples_run``, ``max_examples``, ``seed``, ``job_seed``,
202
+ ``counterexample`` (if failed), ``strategy_descriptions``,
203
+ and ``is_property_test``.
204
+ :raises AssertionError: Re-raised after recording when a property
205
+ test fails (after shrinking). It is chained to the ``AssertionError``
206
+ of the first failing example and its message includes that failure's
207
+ traceback.
208
+ :raises RuntimeError: When an example raises an unexpected (non-assertion)
209
+ exception, or when too many generated examples are rejected by ``assume()``.
210
+ """
211
+ max_examples = self._max_examples
212
+ examples_run = 0
213
+ assumptions_rejected = 0
214
+ max_rejections = 50 * max_examples
215
+ counterexample = None
216
+ first_failure_error = None
217
+ first_failure_traceback = None
218
+
219
+ strategy_descriptions = {
220
+ name: strategy.describe() for name, strategy in strategies.items()
221
+ }
222
+
223
+ example_index = 0
224
+
225
+ while examples_run < max_examples:
226
+ # Check for too many assumption rejections
227
+ if assumptions_rejected >= max_rejections:
228
+ self._attach_metadata(
229
+ examples_run=examples_run,
230
+ max_examples=max_examples,
231
+ assumptions_rejected=assumptions_rejected,
232
+ strategy_descriptions=strategy_descriptions
233
+ )
234
+ raise RuntimeError(
235
+ f"Too many assumption rejections ({assumptions_rejected}) "
236
+ f"after {examples_run} successful examples. This usually "
237
+ f"means the preconditions in assume() are too restrictive "
238
+ f"for the strategies being used."
239
+ )
240
+
241
+ # Generate values for this example
242
+ generated_values = {
243
+ name: strategy.generate(self._rng)
244
+ for name, strategy in strategies.items()
245
+ }
246
+
247
+ # Merge injected and generated args
248
+ all_args = {}
249
+ all_args.update(injected_args)
250
+ all_args.update(generated_values)
251
+
252
+ # Create a check result for this example
253
+ check_inst_id = str(uuid.uuid4())
254
+ check_name = f"check_{example_index:04d}"
255
+
256
+ check_result = CheckResult(
257
+ inst_id=check_inst_id,
258
+ name=check_name,
259
+ parent_inst=self._parent_inst,
260
+ generated_values=generated_values,
261
+ example_index=example_index,
262
+ seed=self._test_seed,
263
+ result_code=ResultCode.UNSET
264
+ )
265
+
266
+ # Preview the check result
267
+ self._recorder.preview(check_result)
268
+
269
+ try:
270
+ test_func(**all_args)
271
+
272
+ # Example passed — mark and record
273
+ check_result.finalize()
274
+ self._recorder.record(check_result)
275
+ examples_run += 1
276
+ example_index += 1
277
+
278
+ except UnsatisfiedAssumption:
279
+ # Precondition not met — skip this example entirely
280
+ assumptions_rejected += 1
281
+ example_index += 1
282
+ continue
283
+
284
+ except AssertionError as ae:
285
+ # Property assertion failure
286
+ # Property assertion failure — add failure detail, then finalize
287
+ tb_detail = create_traceback_detail(ae)
288
+ check_result.add_failure(tb_detail)
289
+ check_result.finalize()
290
+ self._recorder.record(check_result)
291
+ examples_run += 1
292
+
293
+ # Store first failure for shrinking
294
+ counterexample = generated_values
295
+ first_failure_error = ae
296
+ first_failure_traceback = tb_detail
297
+
298
+ # Attempt to shrink the counterexample
299
+ shrunk = self._shrink(test_func, strategies, generated_values, injected_args)
300
+ if shrunk is not None:
301
+ counterexample = shrunk
302
+
303
+ break
304
+
305
+ except Exception as ex:
306
+ # Unexpected error
307
+ # Unexpected error — add error detail, then finalize
308
+ tb_detail = create_traceback_detail(ex)
309
+ check_result.add_error(tb_detail)
310
+ check_result.finalize()
311
+ self._recorder.record(check_result)
312
+
313
+ # Attach the metadata to the test result, then re-raise as an error (no shrinking)
314
+ self._attach_metadata(
315
+ examples_run=examples_run,
316
+ max_examples=max_examples,
317
+ assumptions_rejected=assumptions_rejected,
318
+ strategy_descriptions=strategy_descriptions
319
+ )
320
+
321
+ raise RuntimeError(
322
+ f"Property test errored on example {example_index}: {ex!r}"
323
+ ) from ex
324
+
325
+ safe_counterexample = None
326
+ if counterexample is not None:
327
+ # Safely serialize counterexample for metadata
328
+ safe_counterexample = {}
329
+ for k, v in counterexample.items():
330
+ try:
331
+ json.dumps(v)
332
+ safe_counterexample[k] = v
333
+ except (TypeError, ValueError):
334
+ safe_counterexample[k] = repr(v)
335
+
336
+ # Build the property metadata and attach it to the test result
337
+ metadata = self._attach_metadata(
338
+ examples_run=examples_run,
339
+ max_examples=max_examples,
340
+ assumptions_rejected=assumptions_rejected,
341
+ strategy_descriptions=strategy_descriptions,
342
+ counterexample=safe_counterexample
343
+ )
344
+
345
+ if safe_counterexample is not None:
346
+ err_msg_lines = [
347
+ f"Property falsified after {examples_run} examples. "
348
+ f"Counterexample: {safe_counterexample}",
349
+ "",
350
+ "FIRST FAILURE:"
351
+ ]
352
+ first_failure_lines = format_traceback_detail(first_failure_traceback)
353
+ first_failure_lines = indent_lines_list(first_failure_lines, 1)
354
+ err_msg_lines.extend(first_failure_lines)
355
+
356
+ errmsg = os.linesep.join(err_msg_lines)
357
+ raise AssertionError(errmsg) from first_failure_error
358
+
359
+ return metadata
360
+
361
+ def _attach_metadata(self, *, examples_run: int, max_examples: int,
362
+ assumptions_rejected: int, strategy_descriptions: Dict[str, str],
363
+ counterexample: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
364
+ """
365
+ Builds the property-test metadata and, when the runner was given a parent
366
+ :class:`TestResult`, attaches it to that result.
367
+
368
+ :param examples_run: The number of examples that ran (assumption rejections excluded).
369
+ :param max_examples: The maximum number of examples for the test.
370
+ :param assumptions_rejected: The number of examples rejected by ``assume()``.
371
+ :param strategy_descriptions: The ``describe()`` output of each strategy, by parameter name.
372
+ :param counterexample: The JSON-safe (shrunk) counterexample when the property was
373
+ falsified, otherwise ``None``. Omitted from the metadata when ``None``.
374
+
375
+ :returns: The metadata dictionary with the keys ``is_property_test``, ``examples_run``,
376
+ ``max_examples``, ``seed``, ``job_seed``, ``assumptions_rejected``,
377
+ ``strategy_descriptions`` and, when falsified, ``counterexample``.
378
+ """
379
+ metadata = {
380
+ "is_property_test": True,
381
+ "examples_run": examples_run,
382
+ "max_examples": max_examples,
383
+ "seed": self._test_seed,
384
+ "job_seed": self._job_seed,
385
+ "assumptions_rejected": assumptions_rejected,
386
+ "strategy_descriptions": strategy_descriptions,
387
+ }
388
+
389
+ if counterexample is not None:
390
+ metadata["counterexample"] = counterexample
391
+
392
+ if self._test_result is not None:
393
+ self._test_result.set_property_metadata(metadata)
394
+
395
+ return metadata
396
+
397
+ def _shrink(self, test_func: Callable, strategies: Dict[str, Strategy],
398
+ failing_values: Dict[str, Any],
399
+ injected_args: Dict[str, Any]) -> Optional[Dict[str, Any]]:
400
+ """
401
+ Attempts to shrink the failing counterexample to a simpler input.
402
+
403
+ Iterates through each strategy parameter and tries shrunk candidates
404
+ from the strategy's ``shrink()`` method. Only candidates that still
405
+ reproduce the original failure are kept. The process is bounded by
406
+ ``max_shrink_attempts``.
407
+
408
+ :param test_func: The property test function.
409
+ :param strategies: Dictionary mapping parameter names to strategies.
410
+ :param failing_values: The original failing generated values.
411
+ :param injected_args: The injected parameter values.
412
+ :returns: The simplest failing set of generated values found,
413
+ or ``None`` if no simpler counterexample was found.
414
+ """
415
+ max_attempts = self._max_shrink_attempts
416
+ attempts = 0
417
+ current_best = dict(failing_values)
418
+ improved = False
419
+
420
+ for param_name, strategy in strategies.items():
421
+ if attempts >= max_attempts:
422
+ break
423
+
424
+ for shrunk_value in strategy.shrink(current_best[param_name]):
425
+ if attempts >= max_attempts:
426
+ break
427
+
428
+ attempts += 1
429
+
430
+ # Try the shrunk value
431
+ candidate = dict(current_best)
432
+ candidate[param_name] = shrunk_value
433
+
434
+ all_args = {}
435
+ all_args.update(injected_args)
436
+ all_args.update(candidate)
437
+
438
+ try:
439
+ test_func(**all_args)
440
+ # This candidate no longer fails — skip it
441
+ except AssertionError:
442
+ # Still fails — this is a better (simpler) counterexample
443
+ current_best = candidate
444
+ improved = True
445
+ except Exception:
446
+ # Different error — skip this candidate
447
+ pass
448
+
449
+ return current_best if improved else None