Attribute Macro test

Source
#[test]
Expand description

Marks async function to be executed by async runtime, suitable to test environment

It supports:

By default it uses tokio runtime. Switch runtime with feature flags:

  • tokio: tokio runtime;
  • monoio: monoio runtime;

§Usage for tokio runtime

§Multi-thread runtime

#[async_entry::test(flavor = "multi_thread", worker_threads = 1)]
async fn my_test() {
    assert!(true);
}

worker_threads>0 implies flavor="multi_thread". worker_threads==0 implies flavor="current_thread".

§Using default

The default test runtime is single-threaded.

#[async_entry::test]
async fn my_test() {
    assert!(true);
}

§Configure the runtime to start with time paused

#[async_entry::test(start_paused = true)]
async fn my_test() {
    assert!(true);
}

Note that start_paused requires the test-util feature to be enabled.

§Add initialization statement

#[async_entry::test(init = "init_log!()")]
async fn my_test() {
    assert!(true);
}
// Will produce:
//
// fn my_test() {
//
//     let _g = init_log!();  // Add init statement
//
//     let body = async { assert!(true); };
//     let rt = ...
//     rt.block_on(body);
// }

§Add tracing span over the test fn

#[async_entry::test(tracing_span = "info")]
async fn my_test() {
    assert!(true);
}
// Will produce:
//
// fn my_test() {
//     let body = async { assert!(true); };
//
//     use ::tracing::Instrument;                       // Add tracing span
//     let body_span = ::tracing::info_span("my_test"); //
//     let body = body.instrument(body_span);           //
//
//     let rt = ...
//     rt.block_on(body);
// }

§Use other lib to import tracing and tracing_future

#[async_entry::test(tracing_span = "info" ,tracing_lib="my_lib::")]
async fn my_test() {
    assert!(true);
}
// Will produce:
//
// fn my_test() {
//     let body = async { assert!(true); };
//
//     use my_lib::tracing::Instrument;                         // Add tracing span
//     let body_span = my_lib::tracing::info_span("my_test");   //
//     let body = body.instrument(body_span);                   //
//
//     let rt = ...
//     rt.block_on(body);
// }

§Usage for monoio runtime

When using monoio runtime with feature flag monoio enabled: flavor, worker_threads and start_paused are ignored.

It is the same as using tokio runtime, except the runtime is monoio:

#[async_entry::test()]
async fn my_test() {
    assert!(true);
}
// Will produce:
//
// fn my_test() {
//     // ...
//
//     let body = async { assert!(true); };
//     let rt = monoio::RuntimeBuilder::<_>::new()...
//     rt.block_on(body);
// }

§NOTE:

If you rename the async_entry crate in your dependencies this macro will not work.