10 releases

0.2.7 Oct 27, 2023
0.2.6 Oct 27, 2023
0.2.5 May 5, 2023
0.2.4 Sep 14, 2022
0.1.1 Aug 5, 2022

#427 in Rust patterns

Download history 198/week @ 2024-01-02 708/week @ 2024-01-09 445/week @ 2024-01-16 318/week @ 2024-01-23 474/week @ 2024-01-30 594/week @ 2024-02-06 369/week @ 2024-02-13 1073/week @ 2024-02-20 650/week @ 2024-02-27 628/week @ 2024-03-05 1071/week @ 2024-03-12 1064/week @ 2024-03-19 485/week @ 2024-03-26 1055/week @ 2024-04-02 987/week @ 2024-04-09 676/week @ 2024-04-16

3,492 downloads per month
Used in diffsync

MIT license

17KB
420 lines

RandomVariant

Trait that returns a random variant of the given type, if you are creating a new type to limit some values, instead of deriving the RandomVariant, implement it manually to ensure only correct values are created Unless you also want to try the Result type Useful for hunting down unwraps or other assumptions in your code, The benefit over the crate EveryVariant is that this can be limited to A much smaller set to test, where generting every variant quickly can grow to unmanageable testing sets

Example

    use serde::Serialize;
    use std::net::IpAddr;

    #[derive(RandomVariant, Serialize)]
    enum Message {
        Log(String),
        ErrorCode(u32),
        /// This tuple will fail to serialize if flattened in serde
        Rebooting,
    }

    #[derive(RandomVariant, Serialize)]
    struct LoggedMessage {
        /// Fail to serialize, since flatteing enums is not supported
        #[serde(flatten)]
        t: Message,
        add: IpAddr,
    }
    let mut rng = crate::rand::thread_rng();
    
    /// This allows us to limit the testing set to trying 100 randomized structs
    for _i in 0..100 {
        let v = LoggedMessage::random_variant(&mut rng);
        serde_json::to_string(&v).unwrap();
    }

Dependencies

~1.4–2MB
~42K SLoC