### Settings::database() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Sets the database path for storing failing examples. ```APIDOC ## Settings::database(database: Option) ### Description Set the database path for storing failing examples, or None to disable. ### Parameters - **database** (Option) - Required - The path to a failure database directory, or None to disable. ### Returns - **Self** - Returns self for method chaining. ``` -------------------------------- ### State Machine Implementation Example Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/macros.md A complete example of a Stack state machine with push/pop rules and a size invariant. ```rust use hegel::TestCase; use hegel::generators as gs; struct Stack { items: Vec, } #[hegel::state_machine] impl Stack { #[rule] fn push(&mut self, tc: TestCase) { let value = tc.draw(gs::integers::()); self.items.push(value); } #[rule] fn pop(&mut self, _: TestCase) { self.items.pop(); } #[invariant] fn size_invariant(&self, _: TestCase) { assert!(self.items.len() <= 1000); } } #[hegel::test] fn test_stack(tc: TestCase) { let stack = Stack { items: Vec::new() }; hegel::stateful::run(stack, tc); } ``` -------------------------------- ### Configure Database Path Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Set the directory path for storing failing examples or disable the database. ```rust pub fn database(mut self, database: Option) -> Self ``` ```rust let s = Settings::new().database(Some(".hegel".to_string())); ``` -------------------------------- ### Configuring test settings Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Example of chaining custom settings to a test builder. ```rust use hegel::{Hegel, Settings}; let test = Hegel::new(|tc| { // test body }).settings(Settings::new().test_cases(500)); ``` -------------------------------- ### #[hegel::reproduce_failure] Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Replays a single failing example from a base64 blob. ```APIDOC ## #[hegel::reproduce_failure] ### Description Replay a single failing example from a base64 blob. When set, the test decodes the blob and runs exactly that one example, bypassing generation and shrinking. ``` -------------------------------- ### Run Development Commands with `just` Source: https://github.com/hegeldev/hegel-rust/blob/main/CONTRIBUTING.md Use `just` for common development tasks like testing, formatting, and pre-PR checks. Install `just` if you prefer it over direct `cargo` commands. ```bash just test ``` ```bash just format ``` ```bash # full pre-PR check: lint + tests + docs just check ``` -------------------------------- ### Implementing a Full State Machine Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md A complete example of an IntegerStack state machine with rules, invariants, and a test runner. ```rust use hegel::TestCase; use hegel::generators as gs; struct IntegerStack { stack: Vec, } #[hegel::state_machine] impl IntegerStack { #[rule] fn push(&mut self, tc: TestCase) { let element = tc.draw(gs::integers::()); self.stack.push(element); } #[rule] fn pop(&mut self, _: TestCase) { self.stack.pop(); } #[rule] fn push_pop_identity(&mut self, tc: TestCase) { let initial = self.stack.clone(); let element = tc.draw(gs::integers::()); self.stack.push(element); let popped = self.stack.pop().unwrap_or(element); assert_eq!(popped, element); assert_eq!(self.stack, initial); } #[invariant] fn stack_invariant(&self, _: TestCase) { // Stack can be any size assert!(self.stack.len() >= 0); } } #[hegel::test] fn test_integer_stack(tc: TestCase) { let stack = IntegerStack { stack: Vec::new() }; hegel::stateful::run(stack, tc); } ``` -------------------------------- ### Example output for repeatable draw Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/test-case.md This shows the expected output format when the repeatable flag is set to true. ```text let name_1 = value; let name_2 = value; ``` -------------------------------- ### Install Hegel-Rust dependency Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/README.md Add the library as a development dependency to your Cargo project. ```bash cargo add --dev hegeltest ``` -------------------------------- ### Reproduce failures with #[hegel::reproduce_failure] Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Replays a single failing example from a base64 blob. Bypasses generation and shrinking. ```rust #[hegel::test] #[hegel::reproduce_failure("AAEC…")] fn my_test(tc: hegel::TestCase) { // test body } ``` -------------------------------- ### Test with Rand Integration Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/extras.md Example usage of the randoms generator within a Hegel test case. ```rust #[cfg(feature = "rand")] #[hegel::test] fn test_with_rand(tc: hegel::TestCase) { use hegel::generators::extras::rand as rand_gen; use rand::SeedableRng; let rng = tc.draw(rand_gen::randoms::()); } ``` -------------------------------- ### Target Input Generation in Rust Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Guide the generation process toward specific values using the tc.target method. ```rust #[hegel::test] fn my_test(tc: hegel::TestCase) { let n: u32 = tc.draw(gs::integers::()); tc.target(n as f64); // Generates larger values } ``` -------------------------------- ### Use chrono and jiff generators Source: https://github.com/hegeldev/hegel-rust/blob/main/CHANGELOG.md Example usage of the new chrono and jiff generator modules within a test case. ```rust use hegel::extras::chrono as chrono_gs; use hegel::extras::jiff as jiff_gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let _: chrono::NaiveDate = tc.draw(chrono_gs::naive_dates()); let _: jiff::Zoned = tc.draw(jiff_gs::zoneds()); } ``` -------------------------------- ### Disable database storage Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Use the database method with None to prevent Hegel from storing failing examples. ```rust let settings = Settings::new().database(None); ``` -------------------------------- ### Initialize Settings Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Create a new Settings instance with default values, which are automatically adjusted for CI environments. ```rust impl Settings { pub fn new() -> Self } ``` -------------------------------- ### Creating a new test builder Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Initializes a test builder with default settings and executes it. ```rust use hegel::{Hegel, generators as gs}; fn main() { let test = Hegel::new(|tc| { let x: i32 = tc.draw(gs::integers()); assert_eq!(x, x); }).run(); } ``` -------------------------------- ### Get Pool length Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md Returns the number of values currently stored in the pool. ```rust pub fn len(&self) -> usize ``` ```rust assert_eq!(pool.len(), 5); ``` -------------------------------- ### Configure Antithesis Backend Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/extras.md Manually configure the test backend to Urandom for Antithesis integration. ```rust #[cfg(feature = "antithesis")] #[hegel::test(backend = Backend::Urandom)] fn my_test(tc: hegel::TestCase) { // Hegel reads from /dev/urandom for Antithesis control } ``` -------------------------------- ### Execute Development and CI Commands Source: https://github.com/hegeldev/hegel-rust/blob/main/AGENTS.md Use these Justfile commands to manage the build, test, and linting processes for the repository. ```bash just check # run full CI checks (lint + tests + all-features tests) just test # run tests just lint # run clippy, rustfmt --check, and the repo lint scripts just format # format just docs # build and open docs just check-coverage # check coverage (requires cargo-llvm-cov + llvm-tools-preview) just c-test # hegel-c smoke tests + example C programs just miri # fast core of the suite under Miri cargo test test_name # run a single test ``` -------------------------------- ### #[hegel::main] Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Turns a function into a standalone Hegel binary entry point, supporting various CLI flags for test execution. ```APIDOC ## #[hegel::main] ### Description Turn a function into a standalone Hegel binary entry point. ### Supported CLI Flags - `--test-cases N`: Override test case count - `--seed N`: Set a fixed seed - `--verbosity quiet|normal|verbose|debug`: Set verbosity - `--derandomize`: Enable derandomization - `--database PATH`: Set database path - `--suppress-health-check CHECK`: Suppress a health check - `-h`, `--help`: Show help message ``` -------------------------------- ### Settings::new() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Creates a new Settings instance with default values, automatically detecting CI environments to adjust defaults. ```APIDOC ## Settings::new() ### Description Creates a new Settings instance with default values. Detects CI environments automatically to adjust settings like database usage and derandomization. ### Returns - **Settings** - A new instance with default values. ``` -------------------------------- ### Settings::backend() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Selects the randomness backend. ```APIDOC ## Settings::backend(backend: Backend) ### Description Select the randomness backend. Calling this method pins the choice, overriding automatic detection. ### Parameters - **backend** (Backend) - Required - The backend to use. ### Returns - **Self** - Returns self for method chaining. ``` -------------------------------- ### Example of a Hegel failure report Source: https://github.com/hegeldev/hegel-rust/blob/main/README.md Hegel outputs the specific input values that caused a test assertion to fail. ```text Draw 1: [0, 0] thread 'test_matches_builtin' (2) panicked at src/main.rs:15:5: assertion `left == right` failed left: [0, 0] right: [0] ``` -------------------------------- ### Define a Hegel binary entry point with #[hegel::main] Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Turns a function into a standalone Hegel binary entry point. Supports various CLI flags for test configuration. ```rust #[hegel::main(test_cases = 500)] fn main(tc: hegel::TestCase) { // test body } ``` ```bash cargo run -- --test-cases 1000 --seed 42 --verbosity verbose ``` -------------------------------- ### #[rule] Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/macros.md Attribute macro to mark a method as a state transition rule. ```APIDOC ## #[rule] ### Description Marks a method as an action that modifies the state machine. Rules take `&mut self` and a `TestCase` instance, allowing for state modification and value generation via `tc.draw()`. ### Behavior - Hegel randomly selects rules to apply during test execution. - Panics within a rule cause the specific rule application to be rejected. ``` -------------------------------- ### Configure Backend Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Manually select the randomness backend, overriding automatic detection. ```rust pub fn backend(mut self, backend: Backend) -> Self ``` ```rust use hegel::Backend; let s = Settings::new().backend(Backend::Default); ``` -------------------------------- ### Create a new Rule Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md Use Rule::new to manually instantiate a rule, though the #[state_machine] macro is preferred for most use cases. ```rust impl Rule { pub fn new(name: &str, apply: fn(&mut M, TestCase)) -> Self } ``` ```rust use hegel::stateful::Rule; use hegel::TestCase; let push_rule = Rule::new("push", |state: &mut Stack, tc: TestCase| { let value = tc.draw(hegel::generators::integers::()); state.push(value); }); ``` -------------------------------- ### Configure Settings Programmatically Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Use the Settings builder to define test parameters, verbosity, and lifecycle phases before passing them to the runner. ```rust use hegel::{Settings, Verbosity, Backend, Mode, Phase, HealthCheck}; let settings = Settings::new() .test_cases(500) .seed(Some(12345)) .verbosity(Verbosity::Verbose) .database(Some(".hegel".to_string())) .suppress_health_check([HealthCheck::FilterTooMuch]) .phases([Phase::Reuse, Phase::Generate]) .print_blob(true) .report_multiple_failures(false) .backend(Backend::Default) .mode(Mode::TestRun); ``` -------------------------------- ### Hegel::new Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Creates a new test builder instance with default settings. ```APIDOC ## pub fn new(test_fn: F) ### Description Create a new test builder with default settings. ### Parameters - **test_fn** (F: FnMut(TestCase)) - Required - A closure taking a TestCase and performing test assertions ### Returns A Hegel builder. ``` -------------------------------- ### Rule::new(name: &str, apply: fn(&mut M, TestCase)) Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md Creates a new Rule instance representing an action that can be applied to a state machine. ```APIDOC ## Rule::new(name: &str, apply: fn(&mut M, TestCase)) ### Description Create a new rule manually. This represents a single action that can be applied to a state machine. ### Parameters - **name** (&str) - Required - The rule's name (used in error output) - **apply** (fn(&mut M, TestCase)) - Required - The function to apply the rule ### Returns - **Rule** - A new Rule instance. ### Example ```rust use hegel::stateful::Rule; use hegel::TestCase; let push_rule = Rule::new("push", |state: &mut Stack, tc: TestCase| { let value = tc.draw(hegel::generators::integers::()); state.push(value); }); ``` ``` -------------------------------- ### Crate Structure Overview Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/module-guide.md Visual representation of the file system hierarchy for the Hegel-Rust project. ```text hegeltest (root crate) ├── src/ │ ├── lib.rs (Public API surface) │ ├── runner.rs (Hegel builder, Settings, enums) │ ├── test_case.rs (TestCase handle) │ ├── generators/ │ │ ├── mod.rs (Module re-exports) │ │ ├── generators.rs (Generator trait, map/filter/flat_map) │ │ ├── numeric.rs (integers, floats, Integer/Float traits) │ │ ├── strings.rs (text, binary, email, url, domain, uuid, ip, date/time) │ │ ├── collections.rs (vecs, hashsets, hashmaps, arrays) │ │ ├── combinators.rs (one_of, sampled_from, optional) │ │ ├── tuples.rs (tuples0..tuples12) │ │ ├── misc.rs (booleans, just, unit) │ │ ├── compose.rs (ComposedGenerator, composite macro support) │ │ ├── deferred.rs (Deferred generators for recursion) │ │ ├── default.rs (DefaultGenerator trait, default()) │ │ └── time.rs (durations) │ ├── stateful.rs (StateMachine, run, Pool, Rule) │ ├── extras/ (Feature-gated integrations) │ │ ├── mod.rs │ │ ├── chrono/ │ │ ├── jiff/ │ │ ├── rand/ │ │ └── serde_json/ │ ├── run_lifecycle.rs (Test execution lifecycle) │ ├── ffi.rs (C ABI boundary to libhegel) │ ├── backend.rs (Result types) │ ├── control.rs (Control flow: AssumeFailed, StopTest, etc.) │ ├── explicit_test_case.rs (ExplicitTestCase support) │ ├── antithesis.rs (Antithesis integration) │ └── cli.rs (CLI argument parsing) ├── hegel-macros/ (Proc-macro crate) │ ├── src/ │ │ ├── lib.rs │ │ ├── test_macro.rs (#[hegel::test]) │ │ ├── main_macro.rs (#[hegel::main]) │ │ ├── composite.rs (#[hegel::composite]) │ │ ├── default_gen.rs (#[derive(DefaultGenerator)]) │ │ ├── state_machine.rs (#[hegel::state_machine]) │ │ ├── standalone_function.rs (#[hegel::standalone_function]) │ │ ├── explicit_test_case.rs (#[hegel::explicit_test_case]) │ │ ├── reproduce_failure.rs (#[hegel::reproduce_failure]) │ │ └── utils.rs (Common macro utilities) └── hegel-c/ (Native engine crate, built as libhegel) ├── src/ │ ├── lib.rs (C ABI exports: hegel_* functions) │ ├── backend.rs │ └── native/ (Engine implementation) │ ├── core/ (Choice sequences, shrinking) │ ├── draws/ (Typed draws: int, float, string, etc.) │ ├── shrinker/ (Shrink algorithm) │ └── re/ (Regex generation) └── include/hegel.h (Generated C header) ``` -------------------------------- ### Configure Antithesis Backend in Rust Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Set the backend to Urandom when running tests within the Antithesis environment. ```rust use hegel::Backend; #[hegel::test(backend = Backend::Urandom)] fn my_test(tc: hegel::TestCase) { // Hegel reads entropy from /dev/urandom for Antithesis control } ``` -------------------------------- ### run(mut state: M, tc: TestCase) Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md Executes a state machine against a given TestCase by repeatedly applying rules until completion or invariant failure. ```APIDOC ## run(mut state: M, tc: TestCase) ### Description Execute a state machine against the given TestCase. Repeatedly applies rules from the state machine until the test case is complete or an invariant fails. ### Parameters - **state** (M: StateMachine) - Required - The state machine instance to run - **tc** (TestCase) - Required - The test case handle for drawing values ### Example ```rust use hegel::TestCase; #[hegel::test] fn my_test(tc: TestCase) { let stack = IntegerStack { stack: Vec::new() }; hegel::stateful::run(stack, tc); } ``` ``` -------------------------------- ### Settings Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/types.md Configuration object for defining the behavior of a Hegel test run. ```APIDOC ## Settings ### Description Configuration for a Hegel test run. ### Methods - `new() -> Self`: Creates a new default Settings instance. - `test_cases(n: u64) -> Self`: Sets the number of test cases. - `seed(seed: Option) -> Self`: Sets the random seed. - `derandomize(bool) -> Self`: Enables or disables derandomization. - `database(path: Option) -> Self`: Sets the database path. - `verbosity(verbosity: Verbosity) -> Self`: Sets the verbosity level. - `backend(backend: Backend) -> Self`: Sets the test backend. - `mode(mode: Mode) -> Self`: Sets the execution mode. - `phases(phases: impl IntoIterator) -> Self`: Configures test phases. - `suppress_health_check(checks: impl IntoIterator) -> Self`: Suppresses specific health checks. - `print_blob(bool) -> Self`: Toggles blob printing. - `report_multiple_failures(bool) -> Self`: Toggles reporting of multiple failures. - `has_phase(phase: Phase) -> bool`: Checks if a specific phase is enabled. ``` -------------------------------- ### Extras Module Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/module-guide.md Feature-gated integrations for external crates. ```APIDOC ## Extras Module ### Description Provides DefaultGenerator implementations and type-specific generators for integrated crates. ### Integrations - **chrono** (feature: "chrono") - Chrono integration. - **jiff** (feature: "jiff") - Jiff integration. - **serde_json** (feature: "serde_json") - Serde JSON integration. - **rand** (feature: "rand") - Rand RNG integration. ``` -------------------------------- ### #[state_machine] Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md Attribute macro for defining state machines. ```APIDOC ## #[state_machine] ### Description An attribute macro applied to an `impl` block to generate an executable state machine. Methods within the block can be annotated with `#[rule]` or `#[invariant]`. ### Usage ```rust #[hegel::state_machine] impl MyStateMachine { #[rule] fn my_rule(&mut self, tc: TestCase) { ... } #[invariant] fn my_invariant(&self, tc: TestCase) { ... } } ``` ``` -------------------------------- ### Sample elements with sampled_from Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Picks an element from a provided collection uniformly at random. Panics if the input collection is empty. ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let status: &str = tc.draw(gs::sampled_from(&["pending", "active", "done"])); } ``` -------------------------------- ### Define Settings Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/types.md Configuration structure for customizing Hegel test execution parameters. ```rust pub struct Settings { /* opaque */ } ``` -------------------------------- ### Settings::mode() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Sets the execution mode. ```APIDOC ## Settings::mode(mode: Mode) ### Description Set the execution mode. Defaults to Mode::TestRun. ### Parameters - **mode** (Mode) - Required - The execution mode. ### Returns - **Self** - Returns self for method chaining. ``` -------------------------------- ### Migrate stateful-testing value-pool API Source: https://github.com/hegeldev/hegel-rust/blob/main/CHANGELOG.md Demonstrates the transition from the deprecated Variables API to the new Pool API for stateful testing. ```rust // Before use hegel::stateful::{Variables, variables}; let mut accounts: Variables = variables(&tc); let account = accounts.draw().clone(); let consumed = accounts.consume(); // After use hegel::stateful::{Pool, pool}; let mut accounts: Pool = pool(&tc); let account = tc.draw(accounts.values_reusable()).clone(); let consumed = tc.draw(accounts.values_consumed()); ``` -------------------------------- ### Configure Tuple Variant Generators Source: https://github.com/hegeldev/hegel-rust/blob/main/CHANGELOG.md Illustrates using the *_with methods to configure specific tuple variant fields or entire variants. ```rust // configure just the second entry of the tuple variant Op::default_generator() .read_write_with(|g| g._1(gs::just(42))) // configure the entire tuple variant with a custom generator Op::default_generator() .read_write_with(|_| hegel::compose!(|tc| { let n = tc.draw(gs::integers::().max_value(1024)); Op::ReadWrite(n, n) })) ``` -------------------------------- ### Visualize Test Execution Flow Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/module-guide.md Represents the sequence of operations from test initialization to lifecycle completion. ```text #[hegel::test] ↓ (rewrite draws, explicit test cases) ↓ test_fn() -> Hegel::new() ↓ Hegel::run() ↓ run_lifecycle::drive() ↓ [loop] hegel_next_test_case() ↓ run_test_case(test_fn, tc) ↓ test_fn(tc) ↓ tc.draw(generator) ↓ generator.do_draw(tc) ↓ tc.generate_integer_i64() [or other typed draw] ↓ hegel_generate_integer() [C ABI] ↓ [back to test_fn] ↓ [assertion passes/fails/panics] ↓ hegel_mark_complete() [C ABI] ↓ [engine decides: shrink more? replay? done?] ↓ run_lifecycle reports result ``` -------------------------------- ### Generate a bounded integer Source: https://github.com/hegeldev/hegel-rust/blob/main/hegel-c/CHANGELOG.md Replaces the previous CBOR-based schema construction for integer generation with a direct function call. ```c int64_t n; hegel_result_t rc = hegel_generate_integer(ctx, tc, 0, 100, &n); ``` -------------------------------- ### gs::binary() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Generates arbitrary byte sequences. ```APIDOC ## fn binary() ### Description Generate arbitrary byte sequences. Returns a BinaryGenerator with defaults: 0–100 bytes. ### Builder Methods - .min_size(n): Minimum length in bytes - .max_size(n): Maximum length in bytes ``` -------------------------------- ### one_of Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Pick one generator uniformly at random, then draw from it. ```APIDOC ## one_of ### Description Pick one generator uniformly at random, then draw from it. ### Signature `pub fn one_of(generators: impl IntoIterator + 'static>) -> OneOfGenerator` ### Parameters - **generators** (impl IntoIterator + 'static>) - A collection of generators ### Returns A `OneOfGenerator`. ``` -------------------------------- ### Import Chrono generators Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/extras.md Import the chrono module from extras to access supported type generators. ```rust use hegel::generators::extras::chrono as chrono_gen; ``` -------------------------------- ### Generate domain names Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Creates a DomainGenerator for producing domain name strings. ```rust pub fn domains() -> DomainGenerator ``` ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let domain: String = tc.draw(gs::domains()); } ``` -------------------------------- ### Importing Stateful Testing Modules Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md Required imports for defining and running state machines. ```rust use hegel::stateful::{run, Rule, Pool}; use hegel::state_machine; // re-exported from hegel_macros ``` -------------------------------- ### Running property-based tests Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Executes the test suite defined by the builder. ```rust use hegel::Hegel; Hegel::new(|tc| { // test body }).run(); ``` -------------------------------- ### FFI Module Functions Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/module-guide.md Functions for managing test runs and settings via the C ABI boundary. ```APIDOC ## FFI Module Functions ### Description Provides safe Rust wrappers for C ABI functions to manage test settings, execution, and generation. ### Functions - **settings_new() -> SettingsHandle** - Creates a new settings opaque handle. - **settings_set_*()** - Configures settings. - **run_start(settings, database_key) -> RunHandle** - Starts a run with the provided settings and database key. - **next_test_case(run) -> CTestCase** - Retrieves the next test case from a run. - **mark_complete(test_case, outcome)** - Marks a test case as complete with a specific outcome. - **generate_*()** - Typed generation functions for integer, float, boolean, bytes, string, and date types. - **start_span() / stop_span()** - Manages execution spans. - **target()** - Handles targeting logic. ``` -------------------------------- ### Import Rand Generator Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/extras.md Import the rand generator module from the extras package. ```rust use hegel::generators::extras::rand as rand_gen; ``` -------------------------------- ### Settings::test_cases() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Sets the number of test cases to run. ```APIDOC ## Settings::test_cases(n: u64) ### Description Sets the number of test cases to run (default: 100). ### Parameters - **n** (u64) - Required - The number of test cases. ### Returns - **Self** - Returns self for method chaining. ``` -------------------------------- ### Generate date, time, and datetime strings Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Functions for generating date and time strings within a test case. ```rust pub fn dates() -> DateGenerator ``` ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let date: String = tc.draw(gs::dates()); } ``` ```rust pub fn times() -> TimeGenerator ``` ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let time: String = tc.draw(gs::times()); } ``` ```rust pub fn datetimes() -> DateTimeGenerator ``` ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let dt: String = tc.draw(gs::datetimes()); } ``` -------------------------------- ### gs::domains() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Generates domain names. ```APIDOC ## fn domains() ### Description Generate domain names. ``` -------------------------------- ### Configure test lifecycle phases Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Use this to specify which test lifecycle phases to execute. Skipping phases like shrinking can be useful when only a witness is required rather than a minimal counterexample. ```rust use hegel::Phase; let s = Settings::new().phases([Phase::Reuse, Phase::Generate]); ``` -------------------------------- ### Hegel::run Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Executes the configured property-based tests. ```APIDOC ## pub fn run(self) ### Description Run the property-based tests. Panics if any test case fails. ``` -------------------------------- ### Settings::seed() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Sets a fixed seed for reproducibility. ```APIDOC ## Settings::seed(seed: Option) ### Description Set a fixed seed for reproducibility, or None for random. ### Parameters - **seed** (Option) - Required - A seed value, or None for random. ### Returns - **Self** - Returns self for method chaining. ``` -------------------------------- ### Test Serde JSON Value Generation Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/extras.md Demonstrates drawing various Serde JSON types using the default generator. ```rust #[cfg(feature = "serde_json")] #[hegel::test] fn test_json_values(tc: hegel::TestCase) { use hegel::generators::{self as gs, DefaultGenerator}; let value = tc.draw(gs::default::()); let map = tc.draw(gs::default::>()); let number = tc.draw(gs::default::()); } ``` -------------------------------- ### Generate URLs Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Creates a UrlGenerator for producing URL strings. ```rust pub fn urls() -> UrlGenerator ``` ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let url: String = tc.draw(gs::urls()); } ``` -------------------------------- ### Defining Rule and Invariant Methods Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md Method signatures for state machine actions and assertions. ```rust #[rule] fn rule_name(&mut self, tc: TestCase) { // modify self, draw values, assert invariants } ``` ```rust #[invariant] fn invariant_name(&self, tc: TestCase) { // assert properties of self } ``` -------------------------------- ### sampled_from Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Pick one element from a collection uniformly at random. ```APIDOC ## sampled_from ### Description Pick one element from a collection uniformly at random. ### Signature `pub fn sampled_from(choices: impl IntoIterator) -> SampledFromGenerator` ### Parameters - **choices** (impl IntoIterator) - A collection of values to sample from ### Returns A `SampledFromGenerator`. ### Panics If the collection is empty. ``` -------------------------------- ### Configure Execution Mode Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Set the execution mode for the test runner. ```rust pub fn mode(mut self, mode: Mode) -> Self ``` ```rust use hegel::Mode; let s = Settings::new().mode(Mode::SingleTestCase); ``` -------------------------------- ### Configure text generators in Rust Source: https://github.com/hegeldev/hegel-rust/blob/main/CHANGELOG.md Configures parameters for text generation using the gs::text() builder pattern. ```rust gs::text().codec("ascii"); gs::text().alphabet("abc"); gs::text().min_codepoint(0x20).max_codepoint(0x7E); gs::text().categories(&["L", "Nd"]); gs::text().exclude_categories(&["Cc"]); gs::text().include_characters("@#$"); gs::text().exclude_characters("\n\t"); ``` -------------------------------- ### Combine #[hegel::test] with other test macros Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/macros.md Hegel macros are compatible with other test frameworks like tokio. ```rust #[tokio::test] #[hegel::test] async fn my_async_test(tc: hegel::TestCase) { // test body } ``` -------------------------------- ### Public API Exports in lib.rs Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/module-guide.md Direct exports from the crate root, including main types, macros, and framework-level utilities. ```rust // Main types pub use test_case::TestCase; pub use generators::Generator; pub use runner::{Hegel, Settings, Backend, HealthCheck, Mode, Phase, Verbosity}; pub use stateful; pub use extras; pub use explicit_test_case::ExplicitTestCase; // Macros pub use hegel_macros::{ test, main, composite, explicit_test_case, reproduce_failure, state_machine, DefaultGenerator, standalone_function, }; // Re-exported for convenience pub use generators; pub use paste; // For macro helpers // Hidden/semi-hidden (for framework use) #[doc(hidden)] pub use control::currently_in_test_context; #[doc(hidden)] pub use test_case::{__IsTestCase, __assert_is_test_case, with_output_override}; #[doc(hidden)] pub use antithesis::TestLocation; #[doc(hidden)] pub use cli::CliOutcome; #[doc(hidden)] pub use runner::hegel as __hegel_internal; ``` -------------------------------- ### hegel::stateful::run Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md Executes a state machine test using the provided state machine instance and test case. ```APIDOC ## hegel::stateful::run ### Description Executes a state machine test. This function takes an instance of a struct marked with the `#[state_machine]` macro and a `TestCase` to drive the execution of rules and invariant checks. ### Signature `fn run(machine: T, tc: TestCase)` ### Parameters - **machine** (T: StateMachine) - The state machine instance to test. - **tc** (TestCase) - The test case context used for drawing values and managing test state. ``` -------------------------------- ### Configure Seed Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Set a fixed seed for reproducibility or None for random behavior. ```rust pub fn seed(mut self, seed: Option) -> Self ``` ```rust let s = Settings::new().seed(Some(12345)); ``` -------------------------------- ### Internal methods start_span and stop_span Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/test-case.md Used by generators to bracket related draws for the shrinker. These methods are not intended for direct external use. ```rust pub(crate) fn start_span(&self, label: u64) pub(crate) fn stop_span(&self, rejected: bool) ``` -------------------------------- ### Update Default Generator Usage Source: https://github.com/hegeldev/hegel-rust/blob/main/CHANGELOG.md Demonstrates the transition from weakly typed BoxedGenerator to concrete generator types for improved type safety. ```rust #[derive(DefaultGenerator)] struct Person { name: String, age: u32 } // before let p: Person = tc.draw(gs::default()); // after let p = tc.draw(gs::default::()); // writing the following is now possible, where it would have errored before gs::default::().age(gs::integers::()) gs::default::().min_value(0).max_value(100) ``` -------------------------------- ### Execute test loop with loop_step Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/test-case.md Runs a closure as a single iteration of a test loop, returning a boolean to indicate whether the loop should continue. ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let mut i = 0; while tc.loop_step(|_| { i += 1; assert!(i < 1000); }) { // loop continues } } ``` -------------------------------- ### assume Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/test-case.md Enforces a condition, rejecting the test input if the condition is false. ```APIDOC ## pub fn assume(&self, condition: bool) ### Description Assume a condition is true. If false, reject the current test input. Too many rejections trigger the FilterTooMuch health check. ### Parameters - **condition** (bool) - Required - The condition to check ``` -------------------------------- ### Define composite generators with #[hegel::composite] Source: https://github.com/hegeldev/hegel-rust/blob/main/CHANGELOG.md Use the composite macro to define custom test case generators. Requires importing TestCase, composite, and generators from the hegel crate. ```rust use hegel::{TestCase, composite, generators}; #[derive(Debug)] struct Person { age: i32, has_drivers_license: bool, } #[composite] fn persons(tc: TestCase) -> Person { let age: i32 = tc.draw(generators::integers().min_value(0).max_value(100)); let has_drivers_license = age > 18 && tc.draw(generators::booleans()); Person { age, has_drivers_license } } ``` -------------------------------- ### Enable Reproducer Blob Printing in Rust Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Configure settings to output a reproducer blob upon test failure. ```rust let settings = Settings::new().print_blob(true); ``` -------------------------------- ### Importing Hegel types Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Required imports for using the Hegel testing framework. ```rust use hegel::{Hegel, Settings, Backend, HealthCheck, Phase, Mode, Verbosity}; ``` -------------------------------- ### gs::ip_addresses() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Generates IP addresses. ```APIDOC ## fn ip_addresses() ### Description Generate IP addresses (both IPv4 and IPv6). ### Builder Methods - .ipv4_only(): Generate only IPv4 addresses - .ipv6_only(): Generate only IPv6 addresses ``` -------------------------------- ### note Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/test-case.md Records a message to be displayed with a failing test case. ```APIDOC ## pub fn note(&self, message: &str) ### Description Note a message which will be displayed with the reported failing test case. ### Parameters - **message** (&str) - Required - The message to record ``` -------------------------------- ### Import Serde JSON Generators Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/extras.md Required import for accessing Serde JSON-related generator utilities. ```rust use hegel::generators::extras::serde_json as json_gen; ``` -------------------------------- ### Floating-point generator usage Source: https://github.com/hegeldev/hegel-rust/blob/main/CHANGELOG.md Native backend support for floating-point generators with configurable bounds and shrink passes. ```rust gs::floats::() ``` ```rust gs::floats::() ``` -------------------------------- ### Generate IP addresses Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Creates an IpAddressGenerator for producing IPv4 or IPv6 addresses. Use builder methods to restrict to specific IP versions. ```rust pub fn ip_addresses() -> IpAddressGenerator ``` ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let ip: String = tc.draw(gs::ip_addresses()); } ``` -------------------------------- ### Drive generation from another thread Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/test-case.md Clones a TestCase to move it into a separate thread for concurrent generation. Ensure the test case is not accessed by multiple threads simultaneously. ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let tc_worker = tc.clone(); let handle = std::thread::spawn(move || { tc_worker.draw(gs::vecs(gs::integers()).max_size(10)) }); let xs = handle.join().unwrap(); let more: bool = tc.draw(gs::booleans()); let _ = (xs, more); } ``` -------------------------------- ### Enable Hegel Features Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/README.md Add Hegel as a development dependency in Cargo.toml with specific feature flags enabled. ```toml [dev-dependencies] hegeltest = { version = "0.25", features = ["chrono", "serde_json"] } ``` -------------------------------- ### Define DomainGenerator Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/types.md Structure definition for generating domain names. ```rust pub struct DomainGenerator { /* opaque */ } ``` -------------------------------- ### phases Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Sets the test lifecycle phases to be executed during the test run. ```APIDOC ## fn phases(phases: impl IntoIterator) -> Self ### Description Sets which test lifecycle phases to run. Defaults to all phases: [Phase::Explicit, Phase::Reuse, Phase::Generate, Phase::Target, Phase::Shrink]. ### Parameters - **phases** (impl IntoIterator) - Required - An iterable of Phase values ### Returns - **Self** - The settings instance for method chaining. ``` -------------------------------- ### Configure Derandomization Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/runner.md Enable or disable deterministic seed derivation based on the test name. ```rust pub fn derandomize(mut self, derandomize: bool) -> Self ``` ```rust let s = Settings::new().derandomize(true); ``` -------------------------------- ### #[hegel::standalone_function] Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/macros.md Rewrites a function taking a TestCase plus additional arguments into one that runs Hegel internally. ```APIDOC ## #[hegel::standalone_function] ### Description Rewrites a function taking a TestCase plus additional arguments into one that runs Hegel internally. It removes the TestCase parameter from the signature and wraps the body in a Hegel execution context. ``` -------------------------------- ### hegel::stateful::run Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md Executes a defined state machine within a test case. ```APIDOC ## fn hegel::stateful::run ### Description Executes the provided state machine instance using the given test case context. This function drives the random selection of rules and verification of invariants. ### Signature `fn run(machine: T, tc: TestCase)` ### Parameters - **machine** (T) - The state machine instance defined with the #[state_machine] macro. - **tc** (TestCase) - The test case handle used for drawing values and managing the test execution. ``` -------------------------------- ### Simple Counter State Machine Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/stateful.md A basic implementation of a state machine using increment and decrement rules with an invariant check. ```rust use hegel::TestCase; use hegel::generators as gs; struct Counter { value: i32, } #[hegel::state_machine] impl Counter { #[rule] fn increment(&mut self, _: TestCase) { self.value += 1; } #[rule] fn decrement(&mut self, _: TestCase) { self.value -= 1; } #[invariant] fn always_valid(&self, _: TestCase) { // Counter can be any value let _ = self.value; } } #[hegel::test] fn test_counter(tc: TestCase) { let counter = Counter { value: 0 }; hegel::stateful::run(counter, tc); } ``` -------------------------------- ### loop_step(body: F) -> bool Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/test-case.md Executes a provided closure as one iteration of a test loop, returning a boolean indicating whether to continue or exit. ```APIDOC ## loop_step(body: F) -> bool ### Description Run body as one iteration of a test loop, returning true to continue the loop and false to exit. At the start of each iteration, a // Loop iteration N note is emitted into the failing-test replay output. ### Returns - **bool** - false when the test case completes (either succeeding or failing); true to continue looping. ### Example ```rust #[hegel::test] fn my_test(tc: hegel::TestCase) { let mut i = 0; while tc.loop_step(|_| { i += 1; assert!(i < 1000); }) { // loop continues } } ``` ``` -------------------------------- ### TestCase Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/types.md A handle to the current test case providing methods for drawing values, making assumptions, and recording test outcomes. ```APIDOC ## TestCase ### Description A handle to the current test case. Provides methods for drawing values, making assumptions, recording notes, and targeting. ### Methods - `draw(&self, generator: impl Generator) -> T`: Draws a value from a generator. - `draw_silent(&self, generator: impl Generator) -> T`: Draws a value silently. - `assume(&self, condition: bool)`: Assumes a condition is true. - `reject(&self) -> !`: Rejects the current test case. - `note(&self, message: &str)`: Records a note for the test case. - `target(&self, score: f64)`: Sets a target score. - `target_labelled(&self, score: f64, label: impl Into)`: Sets a target score with a label. - `loop_step(&self, body: F) -> bool`: Executes a loop step. ``` -------------------------------- ### Internal method with_ctc Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/test-case.md Acquires the libhegel handle and executes the provided closure. Intended for internal framework use only. ```rust pub(crate) fn with_ctc(&self, f: F) -> Result where F: FnOnce(&mut CTestCase) -> Result, ``` -------------------------------- ### Generate unit values with unit() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Creates a generator that produces the unit value (). ```rust pub fn unit() -> JustGenerator<()> ``` ```rust use hegel::generators as gs; #[hegel::test] fn my_test(tc: hegel::TestCase) { let _: () = tc.draw(gs::unit()); } ``` -------------------------------- ### gs::text() Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/generators.md Generates Unicode text strings with configurable constraints. ```APIDOC ## fn text() ### Description Generates Unicode text strings. Returns a TextGenerator with defaults: 0–100 characters, any Unicode except surrogates. ### Builder Methods - .min_size(n): Minimum length in characters - .max_size(n): Maximum length in characters - .alphabet(chars): Use a fixed alphabet - .codec(name): Restrict to characters encodable in a codec - .min_codepoint(u): Minimum Unicode codepoint - .max_codepoint(u): Maximum Unicode codepoint - .categories(cats): Include only characters from these Unicode general categories - .exclude_categories(cats): Exclude characters from these categories ``` -------------------------------- ### Define UrlGenerator Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/types.md Structure definition for generating URLs. ```rust pub struct UrlGenerator { /* opaque */ } ``` -------------------------------- ### #[hegel::explicit_test_case] Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/configuration.md Defines a fixed test case to be run before generated ones. ```APIDOC ## #[hegel::explicit_test_case] ### Description Define a fixed test case to be run before generated ones. The function receives the explicitly-provided values via `tc.draw()` calls in the same order. ``` -------------------------------- ### #[hegel::state_machine] Source: https://github.com/hegeldev/hegel-rust/blob/main/_autodocs/api-reference/macros.md The primary macro used to annotate an implementation block as a state machine for model-based testing. ```APIDOC ## #[hegel::state_machine] ### Description Defines a stateful model-based test by annotating an `impl` block. The macro processes methods marked with `#[rule]` and `#[invariant]` to drive the state machine execution. ### Usage ```rust #[hegel::state_machine] impl MyStateMachine { #[rule] fn rule_name(&mut self, tc: hegel::TestCase) { ... } #[invariant] fn invariant_name(&self, tc: hegel::TestCase) { ... } } ``` ```