Skip to content

Commit

Permalink
Move some alloc tests to the alloctests crate
Browse files Browse the repository at this point in the history
Unit tests directly inside of standard library crates require a very
fragile way of building that is hard to reproduce outside of bootstrap.
  • Loading branch information
bjorn3 committed Dec 4, 2024
1 parent 733616f commit b440ef8
Show file tree
Hide file tree
Showing 14 changed files with 123 additions and 27 deletions.
3 changes: 0 additions & 3 deletions library/alloc/src/alloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,6 @@ use core::hint;
#[cfg(not(test))]
use core::ptr::{self, NonNull};

#[cfg(test)]
mod tests;

extern "Rust" {
// These are the magic symbols to call the global allocator. rustc generates
// them to call `__rg_alloc` etc. if there is a `#[global_allocator]` attribute
Expand Down
3 changes: 0 additions & 3 deletions library/alloc/src/collections/binary_heap/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -155,9 +155,6 @@ use crate::collections::TryReserveError;
use crate::slice;
use crate::vec::{self, AsVecIntoIter, Vec};

#[cfg(test)]
mod tests;

/// A priority queue implemented with a binary heap.
///
/// This will be a max-heap.
Expand Down
3 changes: 0 additions & 3 deletions library/alloc/src/ffi/c_str.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
//! [`CString`] and its related types.
#[cfg(test)]
mod tests;

use core::borrow::Borrow;
use core::ffi::{CStr, c_char};
use core::num::NonZero;
Expand Down
2 changes: 0 additions & 2 deletions library/alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -238,8 +238,6 @@ pub mod string;
pub mod sync;
#[cfg(all(not(no_global_oom_handling), not(no_rc), not(no_sync)))]
pub mod task;
#[cfg(test)]
mod tests;
pub mod vec;

#[doc(hidden)]
Expand Down
3 changes: 0 additions & 3 deletions library/alloc/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,6 @@ use crate::string::String;
#[cfg(not(no_global_oom_handling))]
use crate::vec::Vec;

#[cfg(test)]
mod tests;

/// A soft limit on the amount of references that may be made to an `Arc`.
///
/// Going above this limit will abort your program (although not
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
use super::*;
use alloc::alloc::*;
use alloc::boxed::Box;

extern crate test;
use test::Bencher;

use crate::boxed::Box;

#[test]
fn allocate_zeroed() {
unsafe {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use alloc::ffi::CString;
use alloc::rc::Rc;
use alloc::sync::Arc;
use core::assert_matches::assert_matches;
use core::ffi::FromBytesUntilNulError;
use core::ffi::{CStr, FromBytesUntilNulError, c_char};
#[allow(deprecated)]
use core::hash::SipHasher13 as DefaultHasher;
use core::hash::{Hash, Hasher};

use super::*;

#[test]
fn c_to_rust() {
let data = b"123\0";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
use alloc::boxed::Box;
use alloc::collections::binary_heap::*;
use std::iter::TrustedLen;
use std::mem;
use std::panic::{AssertUnwindSafe, catch_unwind};

use super::*;
use crate::boxed::Box;
use crate::testing::crash_test::{CrashTestDummy, Panic};

#[test]
Expand Down Expand Up @@ -531,7 +533,7 @@ fn panic_safe() {
self.0.partial_cmp(&other.0)
}
}
let mut rng = crate::test_helpers::test_rng();
let mut rng = crate::test_rng();
const DATASZ: usize = 32;
// Miri is too slow
let ntest = if cfg!(miri) { 1 } else { 10 };
Expand Down
1 change: 1 addition & 0 deletions library/alloc/tests/collections/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
mod binary_heap;
24 changes: 24 additions & 0 deletions library/alloc/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,10 @@
#![feature(btree_extract_if)]
#![feature(cow_is_borrowed)]
#![feature(core_intrinsics)]
#![feature(downcast_unchecked)]
#![feature(extract_if)]
#![feature(exact_size_is_empty)]
#![feature(hashmap_internals)]
#![feature(linked_list_cursors)]
#![feature(map_try_insert)]
#![feature(pattern)]
Expand All @@ -29,9 +31,11 @@
#![feature(const_str_from_utf8)]
#![feature(panic_update_hook)]
#![feature(pointer_is_aligned_to)]
#![feature(test)]
#![feature(thin_box)]
#![feature(drain_keep_rest)]
#![feature(local_waker)]
#![feature(str_as_str)]
#![feature(strict_provenance_lints)]
#![feature(vec_pop_if)]
#![feature(unique_rc_arc)]
Expand All @@ -40,25 +44,33 @@
#![deny(fuzzy_provenance_casts)]
#![deny(unsafe_op_in_unsafe_fn)]

extern crate test;

use std::hash::{DefaultHasher, Hash, Hasher};

mod alloc;
mod arc;
mod autotraits;
mod borrow;
mod boxed;
mod btree_set_hash;
mod c_str;
mod c_str2;
mod collections;
mod const_fns;
mod cow_str;
mod fmt;
mod heap;
mod linked_list;
mod misc_tests;
mod rc;
mod slice;
mod sort;
mod str;
mod string;
mod sync;
mod task;
mod testing;
mod thin_box;
mod vec;
mod vec_deque;
Expand All @@ -69,6 +81,18 @@ fn hash<T: Hash>(t: &T) -> u64 {
s.finish()
}

/// Copied from `std::test_helpers::test_rng`, since these tests rely on the
/// seed not being the same for every RNG invocation too.
fn test_rng() -> rand_xorshift::XorShiftRng {
use std::hash::{BuildHasher, Hash, Hasher};
let mut hasher = std::hash::RandomState::new().build_hasher();
std::panic::Location::caller().hash(&mut hasher);
let hc64 = hasher.finish();
let seed_vec = hc64.to_le_bytes().into_iter().chain(0u8..8).collect::<Vec<u8>>();
let seed: [u8; 16] = seed_vec.as_slice().try_into().unwrap();
rand::SeedableRng::from_seed(seed)
}

// FIXME: Instantiated functions with i128 in the signature is not supported in Emscripten.
// See https://github.com/kripken/emscripten-fastcomp/issues/169
#[cfg(not(target_os = "emscripten"))]
Expand Down
File renamed without changes.
10 changes: 6 additions & 4 deletions library/alloc/src/sync/tests.rs → library/alloc/tests/sync.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
use alloc::sync::*;
use std::alloc::{AllocError, Allocator, Layout};
use std::any::Any;
use std::clone::Clone;
use std::mem::MaybeUninit;
use std::option::Option::None;
use std::ptr::NonNull;
use std::sync::Mutex;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::atomic::Ordering::*;
use std::sync::atomic::{self, AtomicUsize};
use std::sync::mpsc::channel;
use std::thread;

use super::*;

struct Canary(*mut AtomicUsize);

impl Drop for Canary {
Expand Down
80 changes: 80 additions & 0 deletions library/alloc/tests/testing/crash_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
use std::cmp::Ordering;
use std::fmt::Debug;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;

/// A blueprint for crash test dummy instances that monitor drops.
/// Some instances may be configured to panic at some point.
///
/// Crash test dummies are identified and ordered by an id, so they can be used
/// as keys in a BTreeMap.
#[derive(Debug)]
pub struct CrashTestDummy {
pub id: usize,
dropped: AtomicUsize,
}

impl CrashTestDummy {
/// Creates a crash test dummy design. The `id` determines order and equality of instances.
pub fn new(id: usize) -> CrashTestDummy {
CrashTestDummy { id, dropped: AtomicUsize::new(0) }
}

/// Creates an instance of a crash test dummy that records what events it experiences
/// and optionally panics.
pub fn spawn(&self, panic: Panic) -> Instance<'_> {
Instance { origin: self, panic }
}

/// Returns how many times instances of the dummy have been dropped.
pub fn dropped(&self) -> usize {
self.dropped.load(SeqCst)
}
}

#[derive(Debug)]
pub struct Instance<'a> {
origin: &'a CrashTestDummy,
panic: Panic,
}

#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum Panic {
Never,
InDrop,
}

impl Instance<'_> {
pub fn id(&self) -> usize {
self.origin.id
}
}

impl Drop for Instance<'_> {
fn drop(&mut self) {
self.origin.dropped.fetch_add(1, SeqCst);
if self.panic == Panic::InDrop {
panic!("panic in `drop`");
}
}
}

impl PartialOrd for Instance<'_> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.id().partial_cmp(&other.id())
}
}

impl Ord for Instance<'_> {
fn cmp(&self, other: &Self) -> Ordering {
self.id().cmp(&other.id())
}
}

impl PartialEq for Instance<'_> {
fn eq(&self, other: &Self) -> bool {
self.id().eq(&other.id())
}
}

impl Eq for Instance<'_> {}
1 change: 1 addition & 0 deletions library/alloc/tests/testing/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod crash_test;

0 comments on commit b440ef8

Please sign in to comment.