Simple test + benchmark setup with Rust

Hello! I'm a Rust newbie and I'm trying to set up a simple test and benchmark for each of my modules but I can't seem to get it to work. I've tried all sorts of stuff, and eventually just tried to replicate the example given on this page:

// main.rs:

mod add_two;
use add_two::add_two;

fn main() {
    println!("add_two(3): {}", add_two(3));
}
// add_two.rs:

pub fn add_two(a: i32) -> i32 {
    a + 2
}

#![feature(test)]
extern crate test;

#[cfg(test)]
mod tests {
    use super::*;
    use test::Bencher;

    #[test]
    fn it_works() {
        assert_eq!(4, add_two(2));
    }
    #[bench]
    fn bench_add_two(b: &mut Bencher) {
        b.iter(|| add_two(2));
    }
}

When I run cargo +nightly test it gives me a lot of errors:

error: an inner attribute is not permitted in this context
 --> src/add_two.rs:5:1
  |
5 | #![feature(test)]
  | ^^^^^^^^^^^^^^^^^
  |
  = note: inner attributes, like `#![no_std]`, annotate the item enclosing them, and are usually found at the beginning of source files. Outer attributes, like `#[test]`, annotate the item following them.

error: use of unstable library feature 'test': `bench` is a part of custom test frameworks which are unstable
  --> src/add_two.rs:19:7
   |
19 |     #[bench]
   |       ^^^^^
   |
   = note: `#[deny(soft_unstable)]` on by default
   = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
   = note: for more information, see issue #64266 <https://github.com/rust-lang/rust/issues/64266>

error[E0658]: use of unstable library feature 'test'
 --> src/add_two.rs:7:1
  |
7 | extern crate test;
...........

I must be missing something here - can someone help me out? Thank you!

#![feature(test)] is not an attribute on extern crate test; and has to be in your main.rs. Also features are nightly only.

1 Like

Thank you! Moving [#!feature(test)] to main.rs fixed it :smiley: