Reuse tests from different crate

Hello community,

In short, our requirements are: write rust integ tests that can be executed in different infra setup (server A only, server A + dep B, server A + dep B,C)

for first setup, we write integ tests under crate-a/tests/..., where crate-a is the server lib/binary

for second setup, we want to reuse integ test from crate-a, and add additional integ tests under crate-b/tests/...

similarly for third setup, we want to reuse integ tests from crate-a and crate-b with additional tests.

Our project have following structure:

crate-a // server_A
crate-b // server_A + dependent services B
crate-c // server_A + dependent services B,C

Current problem is:

  1. functions annotated with #[test] can not be exported, so there is no clear way to reuse tests from crate-a in crate-b

The only reason I can figure for wanting to do this is testing that composing libraries doesn't cause breakage. I'm not sure how that's possible, or why reusing tests in unrelated environments is more useful than testing functionality close to where it matters.

This is a disappointing hack, but you can write the shared code as a library, e.g. pub functions without #[test] annotations. It can be made it a little easier by exporting a macro that calls all of the test stubs with the annotation.

//! shared_tests.rs

#[macro_export]
macro_rules! run_tests {
    () => {
        use shared_tests::*;

        #[test]
        fn test_add_one() {
            add_one();
        }

        // Etc.
    }
}

use lib_under_test::add;

#[inline(always)]
pub fn add_one() {
    let result = add(2, 2);
    assert_eq!(result, 4);
}

thanks,

I am experimenting with the proposal trying to understand how this works in code. when defining

macro_rules! run_tests {... #[test] fn test_foo() }

how to use the macro run_tests in other crate's integ tests? by quick chatgpt search:

#[tokio::test] within a macro does not work as expected

  • Each test function must be a top-level function that the test framework can discover.
  • Since macros expand before the compiler processes attributes, #[tokio::test] may not apply correctly.

meaning how can I expand the macro at top level?

I didn't actually try it at the time, but it's easy to fix. Add #[macro_export] to the macro, then you can import it in a dependent.

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.