pub trait InputGenerator {
/// The type generated by this generator, and given as input to the code
/// being tested.
type Input;
code
Assistant
// TODO(ichen): default this to Self::Input when associated type defaults
// are stabilized (https://github.com/rust-lang/rust/issues/29661)
// TODO: explain this
type InputSource: Clone;
/// A type that stores shrinking history with the necessary information to
/// determine the next value to try during shrinking, when to stop
/// attempting to shrink, and information to generate a report of what
/// happened during shrinking.
type History;
/// Returns the number of possible values of type [`Input`], or [`None`] if
/// that value is unknown or greater than [`usize::MAX`].
///
/// [`Input`]: NewInputGenerator::Input
fn cardinality(&self) -> Option<usize>;
// TODO: docs outdated because ShrinkableInput was added
/// Returns an iterator over all possible values of type [`Input`], if
/// possible.
///
/// If [`cardinality`] returns [`None`], the contents of the iterator may be
/// anything and should not be relied on. If [`cardinality`] returns
/// [`Some`], the iterator should yield exactly that many items.
///
/// Additionally, assuming [`cardinality`] returns [`Some`], the returned
/// iterator should yield every possible value of type [`Input`] exactly
/// once, and always in the same order.
///
/// [`Input`]: NewInputGenerator::Input
/// [`cardinality`]: NewInputGenerator::cardinality
fn exhaustive(&self) -> impl Iterator<Item = Self::InputSource>;
/// Returns the number of adversarial inputs that will be returned by
/// [`adversarial`], or [`None`] if that value is greater than
/// [`usize::MAX`] or otherwise should not be relied on.
///
/// [`adversarial`]: NewInputGenerator::adversarial
fn adversarial_count(&self) -> Option<usize>;
// TODO: docs outdated because ShrinkableInput was added
/// Returns an iterator over specifically-chosen adversarial inputs, if
/// possible. These inputs are ones likely to encounter different branches
/// or edge cases in the code being tested.
///
/// If [`adversarial_count`] returns [`None`], the contents of the iterator
/// may be anything and should not be relied on. If [`adversarial_count`]
/// returns [`Some`], the iterator should yield exactly that many items.
///
/// Additionally, assuming [`adversarial_count`] returns [`Some`], the
/// returned iterator should each adversarial value exactly once, and always
/// in the same order.
///
/// [`adversarial_count`]: NewInputGenerator::adversarial_count
fn adversarial(&self) -> impl Iterator<Item = Self::InputSource>;
// TODO: docs outdated because ShrinkableInput was added
/// Samples a random value of type [`Input`].
///
/// The values are not necessarily sampled with equal distribution - some
/// implementations may choose to return certain values more often than
/// others, or may even have some values which will never be returned.
///
/// This function should be deterministic when given the same rng in the
/// same state - that is, if called multiple times with an `rng` that gives
/// the same outputs, this function should return the same value.
///
/// [`Input`]: NewInputGenerator::Input
fn sample(&self, rng: &mut (impl Rng + ?Sized)) -> Self::InputSource;
/// Returns a new [`History`], ready to be used for the shrinking process.
///
/// The `failing_input` argument should be the initial failing input to be
/// shrunk.
///
/// [`History`]: NewInputGenerator::History
fn new_history(&self, failing_input: Self::InputSource) -> Self::History;
/// TODO
fn current_simplest_failing(&self, history: &Self::History) -> Self::InputSource;
/// TODO
fn next_input(
&self,
rng: &mut impl Rng,
history: &Self::History,
) -> NextAttempt<Self::InputSource>;
/// TODO
fn update_history(
&self,
history: &mut Self::History,
shrinkable_input: Self::InputSource,
test_passed: bool,
);
/// TODO
fn generate_observations(&self, history: Self::History) -> Vec<Observation>;
// TODO: docs
// TODO: should this take an `InputSource` or an `&InputSource`?
fn create_input(&self, input_source: Self::InputSource) -> Self::Input;
}
// FILE: map.rs
use crate::{input_generator::NextAttempt, InputGenerator};
It looks like you're developing a Rust library for input generation and shrinking, potentially for property-based testing. You've implemented an InputGenerator trait with various methods for generating and shrinking inputs, and you've provided implementations for Map and started working on a TupleGen for generating tuple inputs.
The TupleGen implementation is currently incomplete, with several todo!() placeholders. Let's walk through how to complete the TupleGen implementation, focusing on the next_input, update_history, and generate_observations methods. We'll also ensure that the history management correctly handles the phases of shrinking for tuple inputs.
Overview of the TupleGen Implementation
The goal of TupleGen is to combine multiple InputGenerator instances (for each element of the tuple) into a single generator that can handle tuples of inputs. The shrinking process for tuples typically involves:
Shrinking each element individually: Attempt to shrink each element of the tuple while keeping the others fixed at their simplest failing values.
Shrinking all elements together: Attempt to shrink the entire tuple in a more holistic manner, considering the interactions between elements.
To manage this process, we'll define a history structure that maintains the state of shrinking across these phases.
Completing the TupleGen Implementation
1. Defining the History
The TupleHist3Phase enum manages the current phase of shrinking. We'll need to handle the following phases:
Element-wise Shrinking - First Pass: Shrink each element individually.
Element-wise Shrinking - Second Pass: Optionally, perform additional passes if needed.
All Together - First Pass: Attempt to shrink all elements together.
All Together - Second Pass: Optionally, perform additional passes if needed.
The next_input method generates the next candidate input to test based on the current history phase.
rust
fn next_input(
&self,
rng: &mut impl rand::Rng,
history: &Self::History,
) -> NextAttempt<Self::InputSource> {
match &history.phase {
TupleHist3Phase::ElementWiseFirstPass { curr_index } => {
if *curr_index < 3 {
let attempt = match *curr_index {
0 => self.0.next_input(rng, &history.inner_histories.0),
1 => self.1.next_input(rng, &history.inner_histories.1),
2 => self.2.next_input(rng, &history.inner_histories.2),
_ => return NextAttempt::Done,
};
match attempt {
NextAttempt::Done => NextAttempt::Done,
NextAttempt::InfoGathering(val) => NextAttempt::InfoGathering((
match *curr_index {
0 => val,
1 => val,
2 => val,
_ => unreachable!(),
},
self.1.current_simplest_failing(&history.inner_histories.1),
self.2.current_simplest_failing(&history.inner_histories.2),
)),
NextAttempt::ShrinkAttempt(val) => NextAttempt::ShrinkAttempt((
match *curr_index {
0 => val,
1 => val,
2 => val,
_ => unreachable!(),
},
self.1.current_simplest_failing(&history.inner_histories.1),
self.2.current_simplest_failing(&history.inner_histories.2),
)),
}
} else {
// Move to the next phase
NextAttempt::InfoGathering((
self.0.current_simplest_failing(&history.inner_histories.0),
self.1.current_simplest_failing(&history.inner_histories.1),
self.2.current_simplest_failing(&history.inner_histories.2),
))
}
}
TupleHist3Phase::AllTogetherFirstPass => {
// Attempt to shrink all elements together
NextAttempt::ShrinkAttempt((
self.0.current_simplest_failing(&history.inner_histories.0),
self.1.current_simplest_failing(&history.inner_histories.1),
self.2.current_simplest_failing(&history.inner_histories.2),
))
}
// Handle other phases similarly...
_ => NextAttempt::Done, // Placeholder
}
}
Explanation:
ElementWiseFirstPass:
Iterate through each element (curr_index from 0 to 2).
For each element, call next_input on the corresponding generator.
Wrap the result in the NextAttempt enum, keeping other elements at their simplest failing values.
AllTogetherFirstPass:
Attempt to shrink the entire tuple by generating a new tuple where all elements are shrunk together.
Other Phases:
Implement similar logic for additional passes or pairwise shrinking if required.
Note: The above implementation is a simplified version. Depending on the desired shrinking strategy, you might need to handle more complex interactions, especially for higher arity tuples.
3. Implementing update_history
The update_history method updates the history based on whether the last tested input caused the test to pass or fail.
rust
fn update_history(
&self,
history: &mut Self::History,
shrinkable_input: Self::InputSource,
test_passed: bool,
) {
if test_passed {
// If the test passed, we keep the new input as the current simplest failing
// input.
// Update the corresponding inner history
// (Assuming we know which part was shrunk, which might require additional state)
} else {
// If the test failed, we accept the shrinkable input
// and update the history accordingly.
// For simplicity, assume we update all sub-histories with their current states.
self.0.update_history(&mut history.inner_histories.0, shrinkable_input.0, false);
self.1.update_history(&mut history.inner_histories.1, shrinkable_input.1, false);
self.2.update_history(&mut history.inner_histories.2, shrinkable_input.2, false);
}
// Move to the next phase if necessary
match &mut history.phase {
TupleHist3Phase::ElementWiseFirstPass { curr_index } => {
*curr_index += 1;
if *curr_index >= 3 {
history.phase = TupleHist3Phase::AllTogetherFirstPass;
}
}
TupleHist3Phase::AllTogetherFirstPass => {
// Transition to the next phase or finish
history.phase = TupleHist3Phase::Done; // Define a Done phase
}
// Handle other phases similarly...
_ => {}
}
}
Explanation:
Test Passed:
If the test passed with the shrunk input, we continue searching for simpler inputs. You might need to adjust the history to reflect that this input is acceptable.
Test Failed:
If the test failed with the shrunk input, we update the inner histories and keep this input as a new candidate for further shrinking.
Phase Transition:
After handling the current phase, transition to the next phase as necessary.
Note: The TupleHist3Phase::Done variant should be defined to indicate that all shrinking phases are complete.
4. Implementing generate_observations
The generate_observations method creates a report based on the history.
rust
fn generate_observations(&self, history: Self::History) -> Vec<crate::report::Observation> {
let mut observations = Vec::new();
// Collect observations from each inner history
observations.extend(self.0.generate_observations(history.inner_histories.0));
observations.extend(self.1.generate_observations(history.inner_histories.1));
observations.extend(self.2.generate_observations(history.inner_histories.2));
// Add any tuple-specific observations if necessary
// For example, interactions between tuple elements.
observations
}
Explanation:
Aggregate observations from each of the inner generators.
Optionally, add observations specific to the tuple shrinking process.
5. Completing the Phases
To fully implement the TupleGen, you need to handle all phases in both next_input and update_history. Here's how you can define the additional phases and handle them:
The current implementation is tailored for 3-element tuples. To generalize, you might consider using recursive tuple generation or macros to handle different tuple sizes. However, for brevity, we'll continue with the 3-element tuple.
Complete TupleGen Implementation Example
Here's an example of how the completed TupleGen might look. Note that this is a simplified version and may need adjustments based on your actual shrinking strategies and requirements.
rust
Key Points:
Phase Management: Properly manage the current phase of shrinking to ensure all aspects of the tuple are considered.
History Updates: Accurately update the history based on whether a shrink attempt passed or failed.
Observations: Aggregate observations from all inner generators to provide comprehensive reports.
Tuple Size: This example is for 3-element tuples. For different sizes, consider generalizing the approach or using macros.
Testing the TupleGen
Once the TupleGen is fully implemented, you should write tests to ensure it behaves as expected. Here's an example test case:
rust
#[cfg(test)]
mod tests {
use super::*;
use crate::{run_test, rand::thread_rng};
struct MockGenerator {
inputs: Vec<i32>,
}
impl InputGenerator for MockGenerator {
type Input = i32;
type InputSource = i32;
type History = ();
fn cardinality(&self) -> Option<usize> {
Some(self.inputs.len())
}
fn exhaustive(&self) -> impl Iterator<Item = Self::InputSource> {
self.inputs.clone().into_iter()
}
fn adversarial_count(&self) -> Option<usize> {
Some(1)
}
fn adversarial(&self) -> impl Iterator<Item = Self::InputSource> {
vec![self.inputs[0]].into_iter()
}
fn sample(&self, _rng: &mut impl rand::Rng) -> Self::InputSource {
self.inputs[0]
}
fn new_history(&self, _failing_input: Self::InputSource) -> Self::History {}
fn current_simplest_failing(&self, _history: &Self::History) -> Self::InputSource {
self.inputs[0]
}
fn next_input(
&self,
_rng: &mut impl rand::Rng,
_history: &Self::History,
) -> NextAttempt<Self::InputSource> {
NextAttempt::Done
}
fn update_history(
&self,
_history: &mut Self::History,
_shrinkable_input: Self::InputSource,
_test_passed: bool,
) {}
fn generate_observations(&self, _history: Self::History) -> Vec<crate::report::Observation> {
vec![]
}
fn create_input(&self, input_source: Self::InputSource) -> Self::Input {
input_source
}
}
#[test]
fn test_tuple_gen() {
let gen_a = MockGenerator { inputs: vec![1, 2, 3] };
let gen_b = MockGenerator { inputs: vec![4, 5, 6] };
let gen_c = MockGenerator { inputs: vec![7, 8, 9] };
let tuple_gen = TupleGen::new(gen_a, gen_b, gen_c);
let mut history = tuple_gen.new_history((3, 6, 9));
let mut rng = thread_rng();
// Attempt to get the next input
let next = tuple_gen.next_input(&mut rng, &history);
println!("{:?}", next);
// Update history based on the test result
// For example, if the test passed
tuple_gen.update_history(&mut history, (2, 5, 8), true);
// Generate observations
let observations = tuple_gen.generate_observations(history);
println!("{:?}", observations);
}
}
Explanation:
MockGenerator: A simple mock implementation of InputGenerator to test TupleGen.
Test Case:
Create three mock generators for each element of the tuple.
Combine them into a TupleGen.
Simulate shrinking by calling next_input and updating the history.
Print the outputs to verify behavior.
Final Thoughts
Implementing a robust tuple input generator with shrinking capabilities requires careful management of the shrinking phases and history. The example provided is a starting point and may need to be tailored to fit more complex shrinking strategies or different tuple sizes. Additionally, consider edge cases and ensure that the shrinking process terminates correctly to avoid infinite loops.
Remember to thoroughly test each component to ensure correctness and reliability, especially as the complexity of the input generators increases.
impl<
A,
B,
C,
GenA: InputGenerator<Input = A>,
GenB: InputGenerator<Input = B>,
GenC: InputGenerator<Input = C>,
> InputGenerator for TupleGen<GenA, GenB, GenC>
{
type Input = (A, B, C);
type InputSource = (GenA::InputSource, GenB::InputSource, GenC::InputSource);
type History = TupleHist3<GenA::History, GenB::History, GenC::History>;
fn cardinality(&self) -> Option<usize> {
Some(
self.0.cardinality()? * self.1.cardinality()? * self.2.cardinality()?,
)
}
fn exhaustive(&self) -> impl Iterator<Item = Self::InputSource> {
cartesian_product_3(
|| self.0.exhaustive(),
|| self.1.exhaustive(),
|| self.2.exhaustive(),
)
}
fn adversarial_count(&self) -> Option<usize> {
Some(
self.0.adversarial_count()? * self.1.adversarial_count()? * self.2.adversarial_count()?,
)
}
fn adversarial(&self) -> impl Iterator<Item = Self::InputSource> {
cartesian_product_3(
|| self.0.adversarial(),
|| self.1.adversarial(),
|| self.2.adversarial(),
)
}
fn sample(&self, rng: &mut impl rand::Rng) -> Self::InputSource {
(
self.0.sample(rng),
self.1.sample(rng),
self.2.sample(rng),
)
}
fn new_history(&self, failing_input: Self::InputSource) -> Self::History {
TupleHist3 {
inner_histories: (
self.0.new_history(failing_input.0),
self.1.new_history(failing_input.1),
self.2.new_history(failing_input.2),
),
phase: TupleHist3Phase::ElementWiseFirstPass { curr_index: 0 },
}
}
fn current_simplest_failing(&self, history: &Self::History) -> Self::InputSource {
(
self.0.current_simplest_failing(&history.inner_histories.0),
self.1.current_simplest_failing(&history.inner_histories.1),
self.2.current_simplest_failing(&history.inner_histories.2),
)
}
fn next_input(
&self,
rng: &mut impl rand::Rng,
history: &Self::History,
) -> NextAttempt<Self::InputSource> {
match &history.phase {
TupleHist3Phase::ElementWiseFirstPass { curr_index } => {
if *curr_index < 3 {
let attempt = match *curr_index {
0 => self.0.next_input(rng, &history.inner_histories.0),
1 => self.1.next_input(rng, &history.inner_histories.1),
2 => self.2.next_input(rng, &history.inner_histories.2),
_ => return NextAttempt::Done,
};
match attempt {
NextAttempt::Done => NextAttempt::Done,
NextAttempt::InfoGathering(val) => NextAttempt::InfoGathering((
val,
self.1.current_simplest_failing(&history.inner_histories.1),
self.2.current_simplest_failing(&history.inner_histories.2),
)),
NextAttempt::ShrinkAttempt(val) => NextAttempt::ShrinkAttempt((
val,
self.1.current_simplest_failing(&history.inner_histories.1),
self.2.current_simplest_failing(&history.inner_histories.2),
)),
}
} else {
NextAttempt::InfoGathering((
self.0.current_simplest_failing(&history.inner_histories.0),
self.1.current_simplest_failing(&history.inner_histories.1),
self.2.current_simplest_failing(&history.inner_histories.2),
))
}
}
TupleHist3Phase::AllTogetherFirstPass => {
// Attempt to shrink all together
match self.next_together_shrink(rng, history) {
Some(attempt) => attempt,
None => NextAttempt::Done, // Or transition to Next Phase
}
}
TupleHist3Phase::Done => NextAttempt::Done,
// Implement other phases...
_ => NextAttempt::Done,
}
}
fn update_history(
&self,
history: &mut Self::History,
shrinkable_input: Self::InputSource,
test_passed: bool,
) {
if test_passed {
// Test passed with the shrinkable_input, continue searching for smaller inputs.
// Typically, you'd revert to previous state or handle accordingly.
} else {
// Test failed with the shrinkable_input, accept it and continue shrinking.
self.0.update_history(&mut history.inner_histories.0, shrinkable_input.0, false);
self.1.update_history(&mut history.inner_histories.1, shrinkable_input.1, false);
self.2.update_history(&mut history.inner_histories.2, shrinkable_input.2, false);
}
// Transition to the next phase
match &mut history.phase {
TupleHist3Phase::ElementWiseFirstPass { curr_index } => {
*curr_index += 1;
if *curr_index >= 3 {
history.phase = TupleHist3Phase::AllTogetherFirstPass;
}
}
TupleHist3Phase::AllTogetherFirstPass => {
history.phase = TupleHist3Phase::Done;
}
// Handle other phases...
_ => {}
}
}
fn generate_observations(&self, history: Self::History) -> Vec<crate::report::Observation> {
let mut observations = Vec::new();
observations.extend(self.0.generate_observations(history.inner_histories.0));
observations.extend(self.1.generate_observations(history.inner_histories.1));
observations.extend(self.2.generate_observations(history.inner_histories.2));
observations
}
fn create_input(&self, input_source: Self::InputSource) -> Self::Input {
(
self.0.create_input(input_source.0),
self.1.create_input(input_source.1),
self.2.create_input(input_source.2),
)
}
}
impl<
A,
B,
C,
GenA: InputGenerator<Input = A>,
GenB: InputGenerator<Input = B>,
GenC: InputGenerator<Input = C>,
> TupleGen<GenA, GenB, GenC>
{
fn next_together_shrink(
&self,
rng: &mut impl rand::Rng,
history: &Self::History,
) -> Option<NextAttempt<Self::InputSource>> {
// Example logic: attempt to shrink each element and combine
let shrunk_a = self.0.next_input(rng, &history.inner_histories.0);
let shrunk_b = self.1.next_input(rng, &history.inner_histories.1);
let shrunk_c = self.2.next_input(rng, &history.inner_histories.2);
match (shrunk_a, shrunk_b, shrunk_c) {
(
NextAttempt::ShrinkAttempt(a),
NextAttempt::ShrinkAttempt(b),
NextAttempt::ShrinkAttempt(c),
) => Some(NextAttempt::ShrinkAttempt((a, b, c))),
_ => None,
}
}
}