jeudi 8 avril 2021

Reuse expensive runtime-generated values across tests

I have a large amount of tests in my Rust code, and I require a RSA key pair for each of them. However, generating RSA key pairs is expensive and takes 3-4 seconds. I can reuse a single RSA key pair across all tests, but I'm not sure how to do that. At the moment, I'm generating an RSA key pair for each test separately.

What I have right now:

use rsa::{hash, PaddingScheme, PublicKey, RSAPublicKey};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_1() {
        let (pub_key, priv_key) = new_keypair();
        // ...
    }

    #[test]
    fn test_2() {
        let (pub_key, priv_key) = new_keypair();
        // ...
    }

    // ...

    fn new_keypair() -> (RSAPublicKey, RSAPrivateKey) {
        use rand::rngs::OsRng;
        let mut rng = OsRng;
        let bits = 2048;
        let private_key =
            RSAPrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
        let public_key = RSAPublicKey::from(&private_key);
        (public_key, private_key)
    }
}

(pseudocode for) What I need:

use rsa::{hash, PaddingScheme, PublicKey, RSAPublicKey};

#[cfg(test)]
mod tests {
    use super::*;

    // Pseudo-code
    #[test_main]
    fn main() {
        let (pub_key, priv_key) = new_keypair();
        run_tests(pub_key, priv_key);
    }

    #[test]
    fn test_1(pub_key: RSAPublicKey, priv_key: RSAPrivateKey) {
        // ...
    }

    #[test]
    fn test_2(pub_key: RSAPublicKey, priv_key: RSAPrivateKey) {
        // ...
    }

    // ...

    fn new_keypair() -> (RSAPublicKey, RSAPrivateKey) {
        use rand::rngs::OsRng;
        let mut rng = OsRng;
        let bits = 2048;
        let private_key =
            RSAPrivateKey::new(&mut rng, bits).expect("Failed to generate private key");
        let public_key = RSAPublicKey::from(&private_key);
        (public_key, private_key)
    }
}

Aucun commentaire:

Enregistrer un commentaire