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.
Update: The tests are async tests and need to use the key pairs as Arc
s, so lazy_static!
won't work (returns reference)
What I have right now:
use rsa::{hash, PaddingScheme, PublicKey, RSAPublicKey};
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn test_1() {
let (pub_key, priv_key) = new_keypair();
// ...
}
#[tokio::test]
async 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
#[tokio::test_main]
async fn main() {
let (pub_key, priv_key) = new_keypair();
run_tests(pub_key, priv_key);
}
#[tokio::test]
async fn test_1(pub_key: RSAPublicKey, priv_key: RSAPrivateKey) {
// ...
}
#[tokio::test]
async 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)
}
}