[][src]Macro test_generator_utest::utest

macro_rules! utest {
    ( $id: ident, $setup:expr, $test:expr, $teardown:expr ) => { ... };
}

Macro implementing the 3 phases setup/test/teardown

Usage

The utest functionality supports the stable release of Rust-compiler since version 1.30.

This example is not tested
#[cfg(test)]
extern crate test_generator_utest;

// demonstrating usage of utest-harness
mod testsuite {
    use std::fs::File;
    use std::io::prelude::*;

    use test_generator_utest::utest;

    utest!(hello_world,
        || setup("/tmp/hello_world.txt"),
        |ctx_ref| test_write_hello_world(ctx_ref),
        |ctx|teardown(ctx));

    utest!(hello_europe,
        || setup("/tmp/hello_europe.txt"),
        test_write_hello_europe,
        teardown);

    // Defining a context structure, storing the resources
    struct Context<'t> { file: File, name: &'t str }

    // Setup - Initializing the resources
    fn setup<'t>(filename: &str) -> Context {
        // unwrap may panic
        Context { file: File::create(filename).unwrap(), name: filename }
    }

    // Teardown - Releasing the resources
    fn teardown(context: Context) {
        let Context { file, name } = context;
        // drop file resources explicitly
        std::mem::drop(file);
        // unwrap may panic
        std::fs::remove_file(name).unwrap();
    }

    // Test - verify feature
    fn test_write_hello_world(ctx: &Context) {
        // may panic
        let mut file = ctx.file.try_clone().unwrap();
        // may panic
        file.write_all(b"Hello, world!\n").unwrap();
        // !!!! although this assertion will fail, the teardown function will be invoked
        assert_eq!(1, 0);
    }

    // Test - verify feature
    fn test_write_hello_europe(ctx: &Context) {
        // may panic
        let mut file = ctx.file.try_clone().unwrap();
        // may panic
        file.write_all(b"Hello, Europe!\n").unwrap();
    }
}