How to run a single test suite against multiple modules?

Hi all,

I'm learning the Quicksort algorithm. I have implemented several versions of this algorithm, each in its own module. Right now, each module has it's own test suite, but the test suite is the same across all modules (so I have duplicated three times the same test suite).

The crate is organized like this:

.
├── Cargo.lock
├── Cargo.toml
└── src
    ├── main.rs
    └── quicksort
        ├── hoare_partition_scheme
        │   ├── leftmost_element_as_pivot.rs
        │   ├── mod.rs
        │   └── rightmost_element_as_pivot.rs
        ├── lomuto_partition_scheme
        │   ├── mod.rs
        │   └── README.md
        └── mod.rs

I have the same test suite for the following modules:

  • hoare_partition_scheme::leftmost_element_as_pivot
  • hoare_partition_sheme::rightmost_element_as_pivot
  • lomuto_partition_scheme

All of these modules implement the same public function quicksort.

Is there a way to run a single test suites on different modules?

Thank you :pray:

How about this?

trait Algorithm {
    fn quicksort(numbers: &mut Vec<i32>);
}

enum LomutoPartitionScheme {}
impl Algorithm for LomutoPartitionScheme {
    fn quicksort(numbers: &mut Vec<i32>) {
        crate::quicksort::lomuto_partition_scheme(numbers);
    }
}
enum LeftHoarePartitionScheme {}
impl Algorithm for LeftHoarePartitionScheme {
    fn quicksort(numbers: &mut Vec<i32>) {
        crate::quicksort::hoare_partition_scheme::leftmost_element_as_pivot::quicksort(numbers);
    }
}

#[test]
fn quicksort_with_zero_as_last_element_test() {
    quicksort_with_zero_as_last_element_generic::<LomutoPartitionScheme>();
    quicksort_with_zero_as_last_element_generic::<LeftHoarePartitionScheme>();
}

fn quicksort_with_zero_as_last_element_generic<T: Algorithm>() {
    let mut input: Vec<i32> = vec![5, 2, 1, 6, 3, 0];
    T::quicksort(&mut input);
    assert_eq!(vec![0, 1, 2, 3, 5, 6], input);
}

Something similar can also be done with macros.

1 Like

Thank you @alice!
I tried it and it worked, even learned about generics at the same time!

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.