Skip to content

Implementing Arbitrary, what to name Strategy? #98

@zmitchell

Description

@zmitchell

I have an enum that I want to select an arbitrary variant of during my tests:

pub enum Polarization {
    Linear(Angle),
    Circular(Handedness),
    Elliptical(Complex<f64>, Complex<f64>),
}

where Angle and Handedness are

pub enum Angle {
    Degrees(f64),
    Radians(f64),
}

pub enum Handedness {
    Left,
    Right,
}

and Complex comes from num_complex.

I also want to be able to select arbitrary values of particular variants i.e. Polarization::Linear(Angle) with an arbitrary Angle. To do that, I just defined a new enum with the variants:

pub enum PolarizationKind {
    Linear,
    Circular,
    Elliptical,
    Any,
}

I started implementing Arbitrary for Polarization, but I'm kind of stuck on the type Strategy = ??? piece. I'm not exactly sure what the type of my Strategy is. Here is my implementation so far:

impl Arbitrary for Polarization {
    type Parameters = PolarizationKind;
    type Strategy = I_DONT_KNOW;

    fn arbitrary_with(args: Self::Parameters) -> Self::Strategy {
        match args {
            PolarizationKind::Linear => any_linear_polarization(),
            PolarizationKind::Circular => any_circular_polarization(),
            PolarizationKind::Elliptical => any_elliptical_polarization(),
            PolarizationKind::Any => {
                prop_oneof![
                    any_linear_polarization(),
                    any_circular_polarization(),
                    any_elliptical_polarization(),
                ]
            }
        }
    }
}

pub fn any_linear_polarization() -> impl Strategy<Value = Polarization> {
    any::<Angle>().prop_map(|angle| {
        Polarization::Linear(angle)
    })
}

pub fn any_circular_polarization() -> impl Strategy<Value = Polarization> {
    any::<Handedness>().prop_map(|h| {
        Polarization::Circular(h)
    })
}

pub fn any_elliptical_polarization() -> impl Strategy<Value = Polarization> {
    (any::<f64>(), any::<f64>(), any::<f64>(), any::<f64>()).prop_map(|(xr, xi, yr, yi)| {
        let x = Complex::new(xr, xi);
        let y = Complex::new(yr, yi);
        Polarization::Elliptical(x, y)
    })
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    help-requestThis issue is asking for advice/help on using proptest

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions