Merge branch 'use-testing-rng'

This commit is contained in:
Nick Mathewson 2022-06-07 19:02:12 -04:00
commit 5854e4bbd9
30 changed files with 141 additions and 126 deletions

16
Cargo.lock generated
View File

@ -1155,6 +1155,12 @@ version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d"
[[package]]
name = "float_eq"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1d53499e94f9a7828e63c574adf62bcade7f358c3738f9ea70d7c2edb61023d"
[[package]]
name = "float_eq"
version = "1.0.0"
@ -3345,7 +3351,7 @@ dependencies = [
"async-trait",
"derive_more",
"educe",
"float_eq",
"float_eq 1.0.0",
"futures",
"futures-await-test",
"hex-literal",
@ -3486,7 +3492,7 @@ dependencies = [
"digest 0.10.3",
"educe",
"event-listener",
"float_eq",
"float_eq 1.0.0",
"fs-mistrust",
"fslock",
"futures",
@ -3555,7 +3561,7 @@ dependencies = [
"derive_builder_fork_arti",
"derive_more",
"educe",
"float_eq",
"float_eq 1.0.0",
"futures",
"humantime 2.1.0",
"humantime-serde",
@ -3620,6 +3626,7 @@ dependencies = [
"simple_asn1",
"subtle",
"thiserror",
"tor-basic-utils",
"typenum",
"x25519-dalek",
"zeroize",
@ -3632,6 +3639,7 @@ dependencies = [
"bitflags",
"derive_builder_fork_arti",
"derive_more",
"float_eq 0.7.0",
"futures",
"hex",
"hex-literal",
@ -3640,6 +3648,7 @@ dependencies = [
"serde",
"signature",
"thiserror",
"tor-basic-utils",
"tor-checkable",
"tor-config",
"tor-linkspec",
@ -3771,6 +3780,7 @@ dependencies = [
"pin-project",
"rand 0.8.5",
"thiserror",
"tor-basic-utils",
"tor-rtcompat",
"tracing",
]

View File

@ -119,6 +119,7 @@ impl Default for RetryDelay {
#[cfg(test)]
mod test {
use super::*;
use crate::test_rng::testing_rng;
#[test]
fn init() {
@ -152,7 +153,7 @@ mod test {
let mut rd = RetryDelay::from_msec(50);
let real_low_bound = std::cmp::max(50, MIN_LOW_BOUND);
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
for _ in 1..100 {
let (b_lo, b_hi) = rd.delay_bounds();
assert!(b_lo == real_low_bound);

View File

@ -1,3 +1,4 @@
use tor_basic_utils::test_rng::testing_rng;
use tor_bytes::Error as BytesError;
/// Example relay messages to encode and decode.
///
@ -468,7 +469,7 @@ fn test_data() {
// Try creating a data cell from too much data.
use rand::RngCore;
let mut b = vec![0_u8; 3000];
rand::thread_rng().fill_bytes(&mut b[..]);
testing_rng().fill_bytes(&mut b[..]);
let d = msg::Data::new(&b[..]);
assert!(d.is_err());

View File

@ -86,6 +86,7 @@ mod test {
use crate::path::assert_same_path_when_owned;
use crate::test::OptDummyGuardMgr;
use std::collections::HashSet;
use tor_basic_utils::test_rng::testing_rng;
use tor_guardmgr::fallback::{FallbackDir, FallbackList};
use tor_linkspec::ChanTarget;
use tor_netdir::testnet;
@ -96,7 +97,7 @@ mod test {
.unwrap()
.unwrap_if_sufficient()
.unwrap();
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let dirinfo = (&netdir).into();
let guards: OptDummyGuardMgr<'_> = None;
@ -136,7 +137,7 @@ mod test {
];
let fb: FallbackList = fb_owned.clone().into();
let dirinfo = (&fb).into();
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let guards: OptDummyGuardMgr<'_> = None;
for _ in 0..10 {
@ -158,7 +159,7 @@ mod test {
fn dirpath_no_fallbacks() {
let fb = FallbackList::from([]);
let dirinfo = DirInfo::Fallbacks(&fb);
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let guards: OptDummyGuardMgr<'_> = None;
let err = DirPathBuilder::default().pick_path(&mut rng, dirinfo, guards);
@ -178,7 +179,7 @@ mod test {
.unwrap()
.unwrap_if_sufficient()
.unwrap();
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let dirinfo = (&netdir).into();
let statemgr = tor_persist::TestingStateMgr::new();
let guards = tor_guardmgr::GuardMgr::new(rt.clone(), statemgr, [].into()).unwrap();

View File

@ -237,6 +237,7 @@ mod test {
use crate::path::{assert_same_path_when_owned, OwnedPath, TorPathInner};
use crate::test::OptDummyGuardMgr;
use std::collections::HashSet;
use tor_basic_utils::test_rng::testing_rng;
use tor_linkspec::ChanTarget;
use tor_netdir::testnet;
use tor_rtcompat::SleepProvider;
@ -262,7 +263,7 @@ mod test {
#[test]
fn by_ports() {
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let netdir = testnet::construct_netdir()
.unwrap()
.unwrap_if_sufficient()
@ -309,7 +310,7 @@ mod test {
#[test]
fn any_exit() {
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let netdir = testnet::construct_netdir()
.unwrap()
.unwrap_if_sufficient()
@ -359,7 +360,7 @@ mod test {
.unwrap()
.unwrap_if_sufficient()
.unwrap();
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let dirinfo = (&netdir).into();
let guards: OptDummyGuardMgr<'_> = None;
let config = PathConfig::default();
@ -392,7 +393,7 @@ mod test {
.unwrap()
.unwrap_if_sufficient()
.unwrap();
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let dirinfo = (&netdir).into();
let statemgr = tor_persist::TestingStateMgr::new();
let guards = tor_guardmgr::GuardMgr::new(rt.clone(), statemgr, [].into()).unwrap();

View File

@ -648,6 +648,7 @@ mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::timeouts::TimeoutEstimator;
use tor_basic_utils::test_rng::testing_rng;
/// Return an action to build a 3-hop circuit.
fn b3() -> Action {
@ -915,7 +916,7 @@ mod test {
use rand::Rng;
let mut est = ParetoTimeoutEstimator::default();
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
for _ in 0..1000 {
let d = Duration::from_millis(rng.gen_range(10..3_000));
est.note_hop_completed(2, d, true);

View File

@ -365,6 +365,7 @@ pub(crate) mod test {
use crate::isolation::{IsolationToken, StreamIsolationBuilder};
use crate::path::OwnedPath;
use crate::test::OptDummyGuardMgr;
use tor_basic_utils::test_rng::testing_rng;
use tor_linkspec::ChanTarget;
use tor_netdir::testnet;
@ -660,7 +661,7 @@ pub(crate) mod test {
#[test]
fn buildpath() {
use crate::mgr::AbstractSpec;
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let netdir = testnet::construct_netdir()
.unwrap()
.unwrap_if_sufficient()
@ -735,7 +736,7 @@ pub(crate) mod test {
fn build_testing_noexit() {
// Here we'll try to build paths for testing circuits on a network
// with no exits.
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let netdir = testnet::construct_custom_netdir(|_idx, bld| {
bld.md.parse_ipv4_policy("reject 1-65535").unwrap();
})

View File

@ -285,6 +285,7 @@ where
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn doctype() {
@ -356,7 +357,7 @@ mod test {
use rand::Rng;
// Construct a big query.
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let ids: HashSet<MdDigest> = (0..3400).into_iter().map(|_| rng.gen()).collect();
// Test microdescs.

View File

@ -998,6 +998,7 @@ mod test {
use crate::docmeta::{AuthCertMeta, ConsensusMeta};
use std::time::Duration;
use tempfile::TempDir;
use tor_basic_utils::test_rng::testing_rng;
use tor_netdoc::doc::netstatus::ConsensusFlavor;
use tor_netdoc::doc::{authcert::AuthCertKeyIds, netstatus::Lifetime};
use tor_rtcompat::SleepProvider;
@ -1218,7 +1219,7 @@ mod test {
id_fingerprint: [99; 20].into(),
sk_fingerprint: [100; 20].into(),
};
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
#[cfg(feature = "routerdesc")]
let rd_ids: Vec<DocId> = (0..1000).map(|_| DocId::RouterDesc(rng.gen())).collect();
let md_ids: Vec<DocId> = (0..1000).map(|_| DocId::Microdesc(rng.gen())).collect();

View File

@ -125,13 +125,14 @@ impl DownloadSchedule {
#[cfg(test)]
mod test {
use super::*;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn config() {
// default configuration is 3 tries, 1000 msec initial delay
let cfg = DownloadSchedule::default();
let one_sec = Duration::from_secs(1);
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
assert_eq!(cfg.n_attempts(), 3);
let v: Vec<_> = cfg.attempts().collect();

View File

@ -231,14 +231,14 @@ mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::FirstHopId;
use rand::Rng;
use tor_basic_utils::test_rng::testing_rng;
/// Construct a `FallbackDir` with random identity keys and addresses.
///
/// Since there are 416 bits of random id here, the risk of collision is
/// negligible.
fn rand_fb() -> FallbackDir {
use rand::Rng;
let mut rng = rand::thread_rng();
fn rand_fb<R: Rng>(rng: &mut R) -> FallbackDir {
let ed: [u8; 32] = rng.gen();
let rsa: [u8; 20] = rng.gen();
let ip: u32 = rng.gen();
@ -255,8 +255,14 @@ mod test {
use rand::seq::SliceRandom;
// fabricate some fallbacks.
let fbs = vec![rand_fb(), rand_fb(), rand_fb(), rand_fb()];
let fb_other = rand_fb();
let mut rng = testing_rng();
let fbs = vec![
rand_fb(&mut rng),
rand_fb(&mut rng),
rand_fb(&mut rng),
rand_fb(&mut rng),
];
let fb_other = rand_fb(&mut rng);
let id_other = FallbackId::from_chan_target(&fb_other);
// basic case: construct a set
@ -282,7 +288,7 @@ mod test {
let mut redundant_fbs = fbs.clone();
redundant_fbs.extend(fbs.clone());
redundant_fbs.extend(fbs[0..2].iter().map(Clone::clone));
redundant_fbs[..].shuffle(&mut rand::thread_rng());
redundant_fbs[..].shuffle(&mut testing_rng());
let list2 = redundant_fbs.into();
assert_ne!(&list, &list2);
let set2: FallbackState = list2.into();
@ -298,14 +304,21 @@ mod test {
#[test]
fn set_choose() {
let fbs = vec![rand_fb(), rand_fb(), rand_fb(), rand_fb()];
dbg!("X");
let mut rng = testing_rng();
let fbs = vec![
rand_fb(&mut rng),
rand_fb(&mut rng),
rand_fb(&mut rng),
rand_fb(&mut rng),
];
let list: FallbackList = fbs.into();
let mut set: FallbackState = list.into();
let mut counts = [0_usize; 4];
let mut rng = rand::thread_rng();
let now = Instant::now();
dbg!("A");
fn lookup_idx(set: &FallbackState, id: &FirstHopId) -> Option<usize> {
if let FirstHopId(crate::ids::FirstHopIdInner::Fallback(id)) = id {
set.fallbacks.binary_search_by(|ent| ent.id().cmp(id)).ok()
@ -319,6 +332,7 @@ mod test {
let idx = lookup_idx(&set, fb.id()).unwrap();
counts[idx] += 1;
}
dbg!("B");
assert!(counts.iter().all(|v| *v > 0));
// Mark somebody down and make sure they don't get chosen.
@ -354,7 +368,13 @@ mod test {
#[test]
fn test_status() {
let fbs = vec![rand_fb(), rand_fb(), rand_fb(), rand_fb()];
let mut rng = testing_rng();
let fbs = vec![
rand_fb(&mut rng),
rand_fb(&mut rng),
rand_fb(&mut rng),
rand_fb(&mut rng),
];
let list: FallbackList = fbs.clone().into();
let mut set: FallbackState = list.into();
let ids: Vec<_> = set.fallbacks.iter().map(|fb| fb.id().clone()).collect();
@ -398,7 +418,7 @@ mod test {
.filter(|fb| FallbackId::from_chan_target(fb) != ids[2])
.collect();
// add 2 new ones.
let fbs_new = [rand_fb(), rand_fb(), rand_fb()];
let fbs_new = vec![rand_fb(&mut rng), rand_fb(&mut rng), rand_fb(&mut rng)];
fbs2.extend(fbs_new.clone());
let mut set2 = FallbackState::from(FallbackList::from(fbs2.clone()));

View File

@ -63,13 +63,14 @@ fn round_time(when: SystemTime, d: u32) -> SystemTime {
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn test_randomize_time() {
let now = SystemTime::now();
let one_hour = Duration::from_secs(3600);
let ten_sec = Duration::from_secs(10);
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
for _ in 0..1000 {
let t = randomize_time(&mut rng, now, one_hour);

View File

@ -52,6 +52,7 @@ cipher = "0.4.1"
hex-literal = "0.3"
rand = "0.8"
serde_test = "1.0.124"
tor-basic-utils = { path = "../tor-basic-utils", version = "0.3.1" }
[target.wasm32-unknown-unknown.dependencies]
getrandom = { version = "0.2.3", features = ["js"] }

View File

@ -173,10 +173,10 @@ mod tests {
fn curve_to_ed_compatible() {
use crate::pk::{curve25519, ed25519};
use crate::util::rand_compat::RngCompatExt;
use rand::thread_rng;
use signature::Verifier;
use tor_basic_utils::test_rng::testing_rng;
let rng = thread_rng().rng_compat();
let rng = testing_rng().rng_compat();
let curve_sk = curve25519::StaticSecret::new(rng);
let curve_pk = curve25519::PublicKey::from(&curve_sk);

View File

@ -124,6 +124,7 @@ fn err_to_old(e: &Error) -> OldError {
mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use tor_basic_utils::test_rng::testing_rng;
/// OR every byte of src into dest.
///
@ -147,7 +148,7 @@ mod test {
#[test]
fn test_wrapper_as_old() {
let mut wrapped = rand::thread_rng().rng_compat();
let mut wrapped = testing_rng().rng_compat();
let mut z64 = 0xffffffffffffffff_u64;
let mut z32 = 0xffffffff_u32;
@ -190,7 +191,7 @@ mod test {
#[test]
fn test_wrapper_as_new() {
let mut wrapped = rand::thread_rng().rng_compat();
let mut wrapped = testing_rng().rng_compat();
let mut z64 = 0xffffffffffffffff_u64;
let mut z32 = 0xffffffff_u32;

View File

@ -71,8 +71,9 @@ fn batch_verify() {
use ll::util::rand_compat::RngCompatExt;
use rand_core::RngCore;
use signature::Signer;
use tor_basic_utils::test_rng::testing_rng;
let mut rng = rand::thread_rng().rng_compat();
let mut rng = testing_rng().rng_compat();
let mut sigs = Vec::new();
for _ in 0..3 {
let kp = Keypair::generate(&mut rng);

View File

@ -45,7 +45,9 @@ tor-units = { path = "../tor-units", version = "0.3.0" }
tracing = "0.1.18"
[dev-dependencies]
float_eq = "0.7"
hex = "0.4"
hex-literal = "0.3"
rand_chacha = "0.3"
tor-basic-utils = { path = "../tor-basic-utils", version = "0.3.1" }
tor-netdoc = { path = "../tor-netdoc", version = "0.4.0", features = ["build_docs"] }

View File

@ -60,8 +60,6 @@
mod err;
pub mod params;
#[cfg(test)]
mod testing;
mod weight;
#[cfg(any(test, feature = "testing"))]
@ -1101,8 +1099,10 @@ mod test {
#![allow(clippy::cognitive_complexity)]
use super::*;
use crate::testnet::*;
use float_eq::assert_float_eq;
use std::collections::HashSet;
use std::time::Duration;
use tor_basic_utils::test_rng;
// Basic functionality for a partial netdir: Add microdescriptors,
// then you have a netdir.
@ -1246,10 +1246,25 @@ mod test {
assert!(dir.unwrap_if_sufficient().is_err());
}
/// Return a 3-tuple for use by `test_pick_*()` of an Rng, a number of
/// iterations, and a tolerance.
///
/// If the Rng is deterministic (the default), we can use a faster setup,
/// with a higher tolerance and fewer iterations. But if you've explicitly
/// opted into randomization (or are replaying a seed from an earlier
/// randomized test), we give you more iterations and a tighter tolerance.
fn testing_rng_with_tolerances() -> (impl rand::Rng, usize, f64) {
// Use a deterministic RNG if none is specified, since this is slow otherwise.
let config = test_rng::Config::from_env().unwrap_or(test_rng::Config::Deterministic);
let (iters, tolerance) = match config {
test_rng::Config::Deterministic => (5000, 0.02),
_ => (50000, 0.01),
};
(config.into_rng(), iters, tolerance)
}
#[test]
fn test_pick() {
use crate::testing::*; // for stochastic testing
let (consensus, microdescs) = construct_network().unwrap();
let mut dir = PartialNetDir::new(consensus, None);
for md in microdescs.into_iter() {
@ -1258,10 +1273,10 @@ mod test {
}
let dir = dir.unwrap_if_sufficient().unwrap();
let total = get_iters() as isize;
let (mut rng, total, tolerance) = testing_rng_with_tolerances();
let mut picked = [0_isize; 40];
let mut rng = get_rng();
for _ in 0..get_iters() {
for _ in 0..total {
let r = dir.pick_relay(&mut rng, WeightRole::Middle, |r| {
r.supports_exit_port_ipv4(80)
});
@ -1273,11 +1288,13 @@ mod test {
picked[0..10].iter().for_each(|x| assert_eq!(*x, 0));
picked[20..30].iter().for_each(|x| assert_eq!(*x, 0));
let picked_f: Vec<_> = picked.iter().map(|x| *x as f64 / total as f64).collect();
// We didn't we any non-default weights, so the other relays get
// weighted proportional to their bandwidth.
check_close(picked[19], (total * 10) / 110);
check_close(picked[38], (total * 9) / 110);
check_close(picked[39], (total * 10) / 110);
assert_float_eq!(picked_f[19], (10.0 / 110.0), abs <= tolerance);
assert_float_eq!(picked_f[38], (9.0 / 110.0), abs <= tolerance);
assert_float_eq!(picked_f[39], (10.0 / 110.0), abs <= tolerance);
}
#[test]
@ -1285,14 +1302,12 @@ mod test {
// This is mostly a copy of test_pick, except that it uses
// pick_n_relays to pick several relays at once.
use crate::testing::*; // for stochastic testing
let dir = construct_netdir().unwrap().unwrap_if_sufficient().unwrap();
let total = get_iters() as isize;
let (mut rng, total, tolerance) = testing_rng_with_tolerances();
let mut picked = [0_isize; 40];
let mut rng = get_rng();
for _ in 0..get_iters() / 4 {
for _ in 0..total / 4 {
let relays = dir.pick_n_relays(&mut rng, 4, WeightRole::Middle, |r| {
r.supports_exit_port_ipv4(80)
});
@ -1306,11 +1321,13 @@ mod test {
picked[0..10].iter().for_each(|x| assert_eq!(*x, 0));
picked[20..30].iter().for_each(|x| assert_eq!(*x, 0));
let picked_f: Vec<_> = picked.iter().map(|x| *x as f64 / total as f64).collect();
// We didn't we any non-default weights, so the other relays get
// weighted proportional to their bandwidth.
check_close(picked[19], (total * 10) / 110);
check_close(picked[36], (total * 7) / 110);
check_close(picked[39], (total * 10) / 110);
assert_float_eq!(picked_f[19], (10.0 / 110.0), abs <= tolerance);
assert_float_eq!(picked_f[36], (7.0 / 110.0), abs <= tolerance);
assert_float_eq!(picked_f[39], (10.0 / 110.0), abs <= tolerance);
}
#[test]

View File

@ -1,56 +0,0 @@
//! Testing-only functionality, used elsewhere in this crate.
pub(crate) use imp::*;
/// Testing implementation helpers.
///
/// This module comes in two flavors: a stochastic and a non-stochastic one.
/// When stochastic testing is enabled, we use a real PRNG, and therefore
/// we require more iterations and broader tolerances.
///
/// The stochastic testing version of this module is on when the
/// `stochastic-tests` feature is enabled.
#[cfg(any(doc, not(feature = "stochastic-tests")))]
mod imp {
/// Return a new RNG -- possibly a pre-seeded one.
pub(crate) fn get_rng() -> impl rand::Rng {
// When stochastic tests aren't enabled, we use a RNG seeded
// with a fixed value and a small number of iterators for each test.
use rand::SeedableRng;
// Use this RNG to make the tests reproducible.
rand_chacha::ChaCha12Rng::from_seed(
// Fun facts:
// The Julius Tote was a mechanical computer and point-of-sale
// system from the 1920s that used horses as an RNG.
*b"George Alfred Julius Totalisator",
)
}
/// Return the number of iterations for which to run a randomized test.
pub(crate) fn get_iters() -> usize {
5000
}
/// Assert that a is close to b.
pub(crate) fn check_close(a: isize, b: isize) {
assert!((a - b).abs() <= (b / 20) + 5);
}
}
// ------ stochastic implementations of above features.
#[cfg(all(not(doc), feature = "stochastic-tests"))]
mod imp {
pub(crate) fn get_rng() -> impl rand::Rng {
rand::thread_rng()
}
#[cfg(all(not(doc), feature = "stochastic-tests"))]
pub(crate) fn get_iters() -> usize {
1000000
}
#[cfg(feature = "stochastic-tests")]
pub(crate) fn check_close(a: isize, b: isize) {
assert!((a - b).abs() <= (b / 100));
}
}

View File

@ -404,6 +404,7 @@ mod test {
use netstatus::RelayWeight as RW;
use std::net::SocketAddr;
use std::time::{Duration, SystemTime};
use tor_basic_utils::test_rng::testing_rng;
use tor_netdoc::doc::netstatus::{Lifetime, RelayFlags, RouterStatusBuilder};
#[test]
@ -621,7 +622,7 @@ mod test {
use rand::Rng;
let now = SystemTime::now();
let one_hour = Duration::new(3600, 0);
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let mut bld = MdConsensus::builder();
bld.consensus_method(34)
.lifetime(Lifetime::new(now, now + one_hour, now + 2 * one_hour).unwrap())

View File

@ -242,6 +242,7 @@ mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use futures::channel::{mpsc, oneshot};
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn circmap_basics() {
@ -249,7 +250,7 @@ mod test {
let mut map_high = CircMap::new(CircIdRange::High);
let mut ids_low: Vec<CircId> = Vec::new();
let mut ids_high: Vec<CircId> = Vec::new();
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
assert!(map_low.get_mut(CircId::from(77)).is_none());

View File

@ -677,8 +677,8 @@ mod test {
use futures::stream::StreamExt;
use futures::task::SpawnExt;
use hex_literal::hex;
use rand::thread_rng;
use std::time::Duration;
use tor_basic_utils::test_rng::testing_rng;
use tor_cell::chancell::{msg as chanmsg, ChanCell};
use tor_cell::relaycell::{msg as relaymsg, RelayCell, StreamId};
use tor_llcrypto::pk;
@ -690,7 +690,7 @@ mod test {
ID: Into<StreamId>,
{
let body: RelayCellBody = RelayCell::new(id.into(), msg)
.encode(&mut thread_rng())
.encode(&mut testing_rng())
.unwrap()
.into();
let chanmsg = chanmsg::Relay::from_raw(body.into());
@ -777,7 +777,7 @@ mod test {
// Future to pretend to be a relay on the other end of the circuit.
let simulate_relay_fut = async move {
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let create_cell = rx.next().await.unwrap();
assert_eq!(create_cell.circid(), 128.into());
let reply = if fast {
@ -1053,7 +1053,7 @@ mod test {
RelayMsg::Extend2(e2) => e2,
_ => panic!(),
};
let mut rng = thread_rng();
let mut rng = testing_rng();
let (_, reply) =
NtorServer::server(&mut rng, &[example_ntor_key()], e2.handshake()).unwrap();
let extended2 = relaymsg::Extended2::new(reply).into();

View File

@ -395,6 +395,7 @@ mod test {
use super::*;
use crate::SecretBytes;
use rand::RngCore;
use tor_basic_utils::test_rng::testing_rng;
fn add_layers(
cc_out: &mut OutboundClientCrypt,
@ -436,7 +437,7 @@ mod test {
let mut r2 = Tor1RelayCrypto::construct(KGen::new(seed2)).unwrap();
let mut r3 = Tor1RelayCrypto::construct(KGen::new(seed3)).unwrap();
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
for _ in 1..300 {
// outbound cell
let mut cell = [0_u8; 509];

View File

@ -94,10 +94,11 @@ mod test {
use super::*;
use crate::crypto::handshake::{ClientHandshake, KeyGenerator, ServerHandshake};
use hex_literal::hex;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn roundtrip() {
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let (state, cmsg) = CreateFastClient::client1(&mut rng, &()).unwrap();
let (s_kg, smsg) = CreateFastServer::server(&mut rng, &[()], cmsg).unwrap();
@ -111,7 +112,7 @@ mod test {
#[test]
fn failure() {
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
// badly formatted client message.
let cmsg = [6_u8; 19];

View File

@ -499,12 +499,13 @@ fn get_rendezvous1_key_material(
mod test {
use super::*;
use hex_literal::hex;
use tor_basic_utils::test_rng::testing_rng;
#[test]
/// Basic HS Ntor test that does the handshake between client and service
/// and makes sure that the resulting keys and KDF is legit.
fn hs_ntor() -> Result<()> {
let mut rng = rand::thread_rng().rng_compat();
let mut rng = testing_rng().rng_compat();
// Let's initialize keys for the client (and the intro point)
let intro_b_privkey = curve25519::StaticSecret::new(&mut rng);

View File

@ -314,11 +314,12 @@ mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::crypto::testing::FakePRNG;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn simple() -> Result<()> {
use crate::crypto::handshake::{ClientHandshake, ServerHandshake};
let mut rng = rand::thread_rng().rng_compat();
let mut rng = testing_rng().rng_compat();
let relay_secret = StaticSecret::new(&mut rng);
let relay_public = PublicKey::from(&relay_secret);
let relay_identity = RsaIdentity::from_bytes(&[12; 20]).unwrap();
@ -400,7 +401,7 @@ mod tests {
#[test]
fn failing_handshakes() {
use crate::crypto::handshake::{ClientHandshake, ServerHandshake};
let mut rng = rand::thread_rng().rng_compat();
let mut rng = testing_rng().rng_compat();
// Set up keys.
let relay_secret = StaticSecret::new(&mut rng);

View File

@ -561,10 +561,11 @@ impl super::ClientHandshake for NtorV3Client {
mod test {
use super::*;
use hex_literal::hex;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn test_ntor3_roundtrip() {
let b = curve25519::StaticSecret::new(rand::thread_rng().rng_compat());
let b = curve25519::StaticSecret::new(testing_rng().rng_compat());
let mut rng = rand::thread_rng();
let id = b"not identifier---but correct len";

View File

@ -148,6 +148,7 @@ mod test {
#![allow(clippy::unwrap_used)]
use super::*;
use tor_basic_utils::test_rng::testing_rng;
#[test]
fn make_skew() {
@ -207,7 +208,7 @@ mod test {
.map(|n| CS::from_secs_f64(n).unwrap())
.collect();
let mut rng = rand::thread_rng();
let mut rng = testing_rng();
let mut v = sorted.clone();
for _ in 0..100 {
v.shuffle(&mut rng);

View File

@ -22,4 +22,5 @@ tracing = "0.1.18"
[dev-dependencies]
futures-await-test = "0.3.0"
rand = "0.8"
tor-basic-utils = { path = "../tor-basic-utils", version = "0.3.1" }
tor-rtcompat = { path = "../tor-rtcompat", version = "0.4.0", features = ["tokio", "native-tls"] }

View File

@ -187,14 +187,14 @@ mod test {
use futures::io::{AsyncReadExt, AsyncWriteExt};
use futures_await_test::async_test;
use rand::thread_rng;
use rand::Rng;
use tor_basic_utils::test_rng::testing_rng;
#[async_test]
async fn basic_rw() {
let (mut s1, mut s2) = stream_pair();
let mut text1 = vec![0_u8; 9999];
thread_rng().fill(&mut text1[..]);
testing_rng().fill(&mut text1[..]);
let (v1, v2): (IoResult<()>, IoResult<()>) = futures::join!(
async {