Attribute Macro tracing_forest::test

source · []
#[test]
Expand description

Marks test to run in the context of a TreeLayer subscriber, suitable to test environment.

For more configuration options, see the builder module documentation

Examples

By default, logs are pretty-printed to stdout.

#[tracing_forest::test]
fn test_subscriber() {
    tracing::info!("Hello, world!");
}
INFO     💬 [info]: Hello, world!

Equivalent code not using #[tracing_forest::test]

#[test]
fn test_subscriber() {
    tracing_forest::builder()
        .with_test_writer()
        .blocking_layer()
        .on_closure(|| {
            tracing::info!("Hello, world!");
        })
}

Tags and formatting

Custom tags and formatting can be configured with the tag and fmt arguments respectively. Currently, only "pretty" and "json" are supported formats, and tag types must implement the Tag trait.

tracing_forest::declare_tags! {
    use tracing_forest::Tag;

    #[derive(Tag)]
    pub(crate) enum GreetingTag {
        #[tag(lvl = "info", msg = "greeting", macro = "greeting")]
        Greeting,
    }
}

#[tracing_forest::test(tag = "GreetingTag", fmt = "json")]
fn test_tag_and_formatted() {
    greeting!("Hello in JSON");
}
{"level":"INFO","kind":{"Event":{"tag":,"message":"Hello in JSON","fields":{}}}}

Equivalent code not using #[tracing_forest::test]

tracing_forest::declare_tags! {
    use tracing_forest::Tag;

    #[derive(Tag)]
    pub(crate) enum GreetingTag {
        #[tag(lvl = "info", msg = "greeting", macro = "greeting")]
        Greeting,
    }
}

#[test]
fn test_tagsand_formatted() {
    tracing_forest::builder()
        .json()
        .with_test_writer()
        .with_tag::<crate::tracing_forest_tag::GreetingTag>()
        .blocking_layer()
        .on_closure(|| {
            tracing::info!("Hello, world!");
        })
}

Using with Tokio runtime

When the sync feature is enabled, this attribute can also be proceeded by the [#[tokio::test]] attribute to run the test in the context of an async runtime.

#[tracing_forest::test]
#[tokio::test]
async fn test_tokio() {
    tracing::info!("Hello from Tokio!");
}
INFO     💬 [info]: Hello from Tokio!

Equivalent code not using #[tracing_forest::test]

#[tokio::test]
async fn test_tokio() {
    tracing_forest::builder()
        .with_test_writer()
        .async_layer()
        .on_future(async {
            tracing::info!("Hello from Tokio!");
        })
        .await
}