Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a custom module inside a doctest?

mod simulation;

use simulation::factory::FactoryType;

works fine in main.rs, but not in a doctest inside simulation/factory.rs:

impl product_type::ProductType for FactoryType {
    /// Lorem Ipsum
    ///
    /// # Examples
    ///
    /// ```
    /// use simulation::factory::FactoryType;
    ///
    /// ...
    /// ```
    fn human_id(&self) -> &String {
        ...
    }
}

cargo test gives me the error

---- simulation::factory::human_id_0 stdout ----
    <anon>:2:9: 2:19 error: unresolved import `simulation::factory::FactoryType`. Maybe a missing `extern crate simulation`?
<anon>:2     use simulation::factory::FactoryType;
                 ^~~~~~~~~~
error: aborting due to previous error
thread 'simulation::factory::human_id_0' panicked at 'Box<Any>', /home/rustbuild/src/rust-buildbot/slave/stable-dist-rustc-linux/build/src/libsyntax/diagnostic.rs:192

How can I get doctests to work?

like image 538
wrongusername Avatar asked Sep 09 '15 07:09

wrongusername


2 Answers

When you write a doc test, you have to act as the user of your code would. Given these files:

src/lib.rs

pub mod simulation {
    pub mod factory {
        pub struct FactoryType;

        impl FactoryType {
            /// ```
            /// use foo::simulation::factory::FactoryType;
            ///
            /// let f = FactoryType;
            /// assert_eq!(42, f.human_id())
            /// ```
            pub fn human_id(&self) -> u8 { 41 }
        }
    }
}

src/main.rs

extern crate foo;
use foo::simulation::factory::FactoryType;

fn main() {
    let f = FactoryType;
    println!("{}", f.human_id());
}

Everything works. Note that in main.rs, you have to say extern crate, then all your references need to include the crate name. The doctest is the same, except the extern crate is automatically included for you.

like image 158
Shepmaster Avatar answered Nov 10 '22 17:11

Shepmaster


As huon-dbaupp noted, bin crates cannot be imported from doc tests.

The solution is to define most of your code as a library crate and have one binary that is just a shell around that.

For example, racer employs this technique.

like image 41
llogiq Avatar answered Nov 10 '22 17:11

llogiq