Hegel 0.18.3
Property-based testing for C++
Loading...
Searching...
No Matches
internal.h
1#pragma once
2
3#include "printer.h"
4#include "test_case.h"
5
6#include <any>
7#include <cstddef>
8#include <cstdint>
9#include <exception>
10#include <optional>
11#include <stdexcept>
12#include <string>
13#include <string_view>
14#include <typeinfo>
15#include <vector>
16
18// opaque libhegel handle types.
19struct hegel_collection_t;
20struct hegel_pool_t;
21struct hegel_state_machine_t;
22struct hegel_recursion_t;
23struct hegel_repeat_t;
25
29namespace hegel::internal {
31
32 /* Typed draw primitives over libhegel's C ABI. Declared here (rather
33 * than in a private header) because the generator templates in the
34 * public headers call them from their do_draw implementations. Each
35 * throws HegelStopTest when the engine's choice budget is exhausted,
36 * HegelReject when the draw rejects itself, and std::runtime_error on
37 * any other engine failure.
38 */
39
40 // The names the generators derive their span labels from. The engine
41 // identifies a span only by its label: spans with the same label come
42 // from the same generator, which makes them candidates for swapping and
43 // reordering when it shrinks. src/engine.cpp maps each name to a
44 // `hegel.<kind>` string, the same one every Hegel frontend uses for that
45 // generator, and derives its label with hegel_label_from_name.
46 enum class LabelName {
47 Composite,
48 Map,
49 FlatMap,
50 Filter,
51 FilterAttempt,
52 Just,
53 SampledFrom,
54 OneOf,
55 Optional,
56 Deferred,
57 Integers,
58 Floats,
59 Booleans,
60 Text,
61 Characters,
62 FromRegex,
63 FromLark,
64 Binary,
65 Emails,
66 Urls,
67 Domains,
68 IpAddressesV4,
69 IpAddressesV6,
70 Uuids,
71 Lists,
72 Sets,
73 Dicts,
74 Tuples,
75 Array,
76 Permutation,
77 Subsequence,
78 Sample,
79 Recursive,
80 StatefulRule,
81 PoolValuesReusable,
82 PoolValuesConsumed,
83 Dates,
84 Times,
85 Datetimes,
86 Instants,
87 Offsets,
88 Zones,
89 ZonedDatetimes,
90 Durations,
91 Spans,
92 };
93 inline constexpr std::size_t label_name_count =
94 static_cast<std::size_t>(LabelName::Spans) + 1;
95
96 // The label of a generator with no component generators, derived once
97 // per process.
98 uint64_t label(LabelName name);
99
100 // The label of a generator that gives none of its own: derived from the
101 // name of its type (hegel_label_from_name), once per type.
102 uint64_t type_label(const std::type_info& type);
103
104 // The label of a generator built from other generators: its own label
105 // first, then its components' labels (hegel_label_combine).
106 uint64_t combine_labels(const std::vector<uint64_t>& labels);
107
108 // Open / close a labeled span around a group of draws so the shrinker
109 // can treat them as a unit. Every TestCase draw opens one labelled with
110 // its generator's label, so a generator only opens its own for spans
111 // it closes with stop_span(tc, true), which marks the span rejected
112 // (e.g. a filter predicate failed) so the engine retries from before it.
113 void start_span(const TestCase& tc, uint64_t label);
114 void stop_span(const TestCase& tc, bool discard = false);
115
116 // Pause / resume fault injection on the test case for the duration of
117 // a check (a stateful invariant declared with pause_faults). Inside
118 // Antithesis the engine asks the fault injector to hold off between the
119 // two; elsewhere both do nothing.
120 void pause_faults(const TestCase& tc);
121 void unpause_faults(const TestCase& tc);
122
123 // Brackets a check with pause_faults / unpause_faults when enabled, so a
124 // check that throws still resumes fault injection. Does nothing when
125 // enabled is false.
126 class PauseFaultsScope {
127 public:
128 PauseFaultsScope(const TestCase& tc, bool enabled);
129 ~PauseFaultsScope();
130 PauseFaultsScope(const PauseFaultsScope&) = delete;
131 PauseFaultsScope& operator=(const PauseFaultsScope&) = delete;
132
133 private:
134 const TestCase& tc_;
135 bool enabled_;
136 };
137
138 int64_t draw_integer(const TestCase& tc, int64_t min_value,
139 int64_t max_value);
140 // Uses the engine's big-integer draw when the range exceeds int64_t.
141 uint64_t draw_integer_unsigned(const TestCase& tc, uint64_t min_value,
142 uint64_t max_value);
143 // Draws an integer between `min_value` and `max_value` inclusive. All
144 // three buffers hold `len` bytes of two's-complement little-endian
145 // integer, and the drawn value is sign-filled to `len` bytes.
146 void draw_integer_bytes(const TestCase& tc, const uint8_t* min_value,
147 const uint8_t* max_value, std::size_t len,
148 uint8_t* out);
149 bool draw_boolean(const TestCase& tc, double p,
150 std::optional<bool> forced = std::nullopt);
151 double draw_float(const TestCase& tc, uint32_t width, double min_value,
152 double max_value, bool allow_nan, bool allow_infinity,
153 bool exclude_min, bool exclude_max,
154 double smallest_nonzero_magnitude);
155
156 // How many values a filter() draws before it rejects the test case:
157 // the engine's HEGEL_FILTER_ATTEMPTS, which src/engine.cpp checks it
158 // against.
159 inline constexpr int filter_attempts = 3;
160
161 inline constexpr uint64_t no_max_size = ~uint64_t{0};
162 class CollectionHandle {
163 public:
164 CollectionHandle(const TestCase& tc, uint64_t min_size,
165 uint64_t max_size);
166 ~CollectionHandle();
167 CollectionHandle(const CollectionHandle&) = delete;
168 CollectionHandle& operator=(const CollectionHandle&) = delete;
169
170 bool more(const TestCase& tc);
171
172 void reject(const TestCase& tc, const char* why);
173
174 private:
175 hegel_collection_t* handle_ = nullptr;
176 };
177
178 // The engine's loop behind TestCase::repeat (hegel_new_repeat): it
179 // decides how many repetitions run and is told which one failed.
180 class RepeatHandle {
181 public:
182 explicit RepeatHandle(const TestCase& tc);
183 ~RepeatHandle();
184 RepeatHandle(const RepeatHandle&) = delete;
185 RepeatHandle& operator=(const RepeatHandle&) = delete;
186
187 bool more(const TestCase& tc);
188
189 void failed(const TestCase& tc);
190
191 private:
192 hegel_repeat_t* handle_ = nullptr;
193 };
194
195 class PoolHandle {
196 public:
197 explicit PoolHandle(const TestCase& tc);
198 ~PoolHandle();
199 PoolHandle(const PoolHandle&) = delete;
200 PoolHandle& operator=(const PoolHandle&) = delete;
201
202 // Returns a fresh variable id.
203 int64_t add(const TestCase& tc);
204 // Returns the variable id the engine picked, removing it from the
205 // pool when consume is true.
206 int64_t draw_variable(const TestCase& tc, bool consume);
207 // Puts back a variable that a consuming draw_variable removed.
208 void restore(const TestCase& tc, int64_t variable);
209 void restore_unchecked(const TestCase& tc, int64_t variable) noexcept;
210
211 private:
212 hegel_pool_t* handle_ = nullptr;
213 };
214
215 // The engine's scope for one recursive value (hegel_new_recursion):
216 // it decides where the value branches and when an attempt has grown too
217 // large and must start again from the root.
218 class RecursionHandle {
219 public:
220 RecursionHandle(const TestCase& tc, uint64_t max_depth,
221 uint64_t max_leaves);
222 ~RecursionHandle();
223 RecursionHandle(const RecursionHandle&) = delete;
224 RecursionHandle& operator=(const RecursionHandle&) = delete;
225
226 // Whether the sub-value at `depth` branches (true) or is a leaf.
227 bool branch(const TestCase& tc, uint64_t depth);
228 // Counts one leaf against the attempt's budget. Throws
229 // LeafBudgetExceeded when the attempt is over the budget.
230 void leaf(const TestCase& tc);
231 // Discards an attempt that threw LeafBudgetExceeded. Throws
232 // HegelReject when the engine gives up on the test case.
233 void retry(const TestCase& tc);
234 // Reports that the value is complete. Throws AttemptMispriced when
235 // the engine discards the attempt.
236 void finish(const TestCase& tc);
237
238 private:
239 hegel_recursion_t* handle_ = nullptr;
240 };
241
242 // Thrown out of the generators of a recursive value when its attempt
243 // has more leaves than its budget. The recursive generator catches it,
244 // discards the attempt and starts again.
245 class LeafBudgetExceeded : public std::exception {};
246
247 // Thrown when the engine discards a completed recursive value. The
248 // recursive generator catches it and starts again.
249 class AttemptMispriced : public std::exception {};
250
251 inline constexpr int64_t state_machine_done = INT64_MIN;
252
253 struct RuleSpec {
254 std::string name;
255 std::vector<int64_t> groups;
256 double weight;
257 };
258
259 struct InvariantSpec {
260 std::string name;
261 bool always_check;
262 };
263
264 // Owns a started engine state machine: the constructor creates it with
265 // the concurrency bounds and the step budget, declares each rule and
266 // invariant, then starts it. concurrency() is max_concurrency, the
267 // number of workers to run.
268 class StateMachineHandle {
269 public:
270 StateMachineHandle(const TestCase& tc,
271 const std::vector<RuleSpec>& rules,
272 const std::vector<InvariantSpec>& invariants,
273 int64_t min_concurrency, int64_t max_concurrency,
274 int64_t step_count);
275 ~StateMachineHandle();
276 StateMachineHandle(const StateMachineHandle&) = delete;
277 StateMachineHandle& operator=(const StateMachineHandle&) = delete;
278
279 // Starts the next round and returns its concurrency group, or
280 // state_machine_done once the engine's step budget for this test case
281 // is used up. Sets round_concurrency() to the round's concurrency
282 // level.
283 int64_t next_group(const TestCase& tc);
284 // Returns the index of the next rule to run this round, or
285 // state_machine_done once the round's rule stream is exhausted.
286 int64_t next_rule(const TestCase& tc, int64_t worker_index);
287 // Report that an assumption failed in the last rule, so it does not
288 // count against the step budget.
289 void rule_rejected(const TestCase& tc, int64_t worker_index);
290 bool should_check_invariant(const TestCase& tc,
291 int64_t invariant_index);
292
293 int64_t concurrency() const { return concurrency_; }
294 int64_t round_concurrency() const { return round_concurrency_; }
295
296 private:
297 hegel_state_machine_t* handle_ = nullptr;
298 int64_t concurrency_ = 0;
299 int64_t round_concurrency_ = 0;
300 };
301
302 struct CapturedException {
303 std::exception_ptr exception;
304 std::string origin;
305
306 [[noreturn]] void rethrow() const;
307 };
308
309 CapturedException capture_current_exception();
310
311 // Marks a draw in progress on `tc`. A draw made inside another one
312 // (a generator that draws from the test case itself) prints nothing:
313 // the outermost draw prints the whole value.
314 class NestedDraw {
315 public:
316 explicit NestedDraw(const TestCase& tc);
317 ~NestedDraw();
318 NestedDraw(const NestedDraw&) = delete;
319 NestedDraw& operator=(const NestedDraw&) = delete;
320
321 bool outermost() const { return outermost_; }
322
323 private:
324 const TestCase& tc_;
325 bool outermost_;
326 };
327
328 // Whether `tc` runs an explicit test case, whose draws take the values
329 // it was given instead of generating them.
330 bool is_explicit(const TestCase& tc);
331
332 void check_not_explicit(const TestCase& tc, const char* what);
333
334 // Takes the value that the explicit test case `tc` gives a draw, and
335 // records the draw for the failure report: the value named for the
336 // draw's display name, else the next positional value. Throws
337 // std::invalid_argument when there is none, or when its type is not
338 // `type`.
339 const std::any& take_explicit_value(const TestCase& tc,
340 std::string_view name,
341 const std::type_info& type);
342
343 // Whether notes and drawn values of `tc` are recorded in the engine's
344 // document (see TestCase::note).
345 bool records_output(const TestCase& tc);
346
347 // `tc`'s printer onto its region of the test case's document.
348 hegel::Printer test_case_printer(const TestCase& tc);
349
350 // The variable name a draw prints under: `name_<n>` for the n-th draw
351 // under `name` (`draw_<n>` for an unnamed draw).
352 std::string draw_display_name(const TestCase& tc, std::string_view name);
353
354 // A handle onto `tc`'s own choice sequence whose output is a block
355 // nested `indent` columns further in, at the current position of `tc`'s
356 // output (hegel_test_case_block). Draw through either, never both at
357 // once.
358 TestCase block(const TestCase& tc, uint64_t indent);
359
360 /* Exception thrown when a test case is rejected and should be
361 * discarded (e.g. by `TestCase::assume(false)`, an exhausted
362 * `filter()`, or an `UnsatisfiedAssumption` from the engine).
363 * The runner records the case as INVALID and continues.
364 */
365 class HegelReject : public std::exception {
366 public:
367 const char* what() const noexcept override {
368 return "test case rejected";
369 }
370 };
371
372 class UsageError : public std::invalid_argument {
373 public:
374 using std::invalid_argument::invalid_argument;
375 };
376
377 /* Exception thrown when the backend tells us to abandon the current
378 * test iteration entirely (StopTest, Overflow, FlakyStrategyDefinition,
379 * FlakyReplay). The runner unwinds the test body and skips
380 * `mark_complete` — the engine already knows the iteration is over.
381 */
382 class HegelStopTest : public std::exception {
383 public:
384 const char* what() const noexcept override {
385 return "test case stopped by backend";
386 }
387 };
388
389 /* Exception thrown by TestCase::repeat when the engine ends its loop.
390 * The runner records the case as VALID: code after the loop never runs.
391 */
392 class HegelLoopDone : public std::exception {
393 public:
394 const char* what() const noexcept override {
395 return "test case ended by repeat";
396 }
397 };
398
399} // namespace hegel::internal
400
uint64_t combine_labels(const std::vector< uint64_t > &labels)
The label of a generator built from other generators.
Definition core.h:947