Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

testing - Error using local modules in documentation tests

I'm playing around with a small crate for 2D noise generation. Here is a simplified snippet of my "lib.rs" file:

pub mod my_math {
    pub struct Vec2<T> {
        ...
    }
    ...
}
pub mod my_noise {
    use num::Float;
    use std::num::Wrapping;
    use my_math::*;

    /// Gets pseudo-random noise based on a seed vector.
    /// 
    /// # Examples
    /// 
    /// ```
    /// use my_math::Vec2;
    /// 
    /// let v_seed = Vec2::<f32>::new_values(4.134, -23.141);
    /// let noise_val = get_noise_white(&v_seed);
    /// 
    /// assert!(noise_val >= 0.0);
    /// assert!(noise_val <= 1.0);
    /// ```
    pub fn get_noise_white(seed: &Vec2<f32>) -> f32 {
        ...
    }
}

However, when I run cargo test, I get the following error:

---- my_noise::get_noise_white_0 stdout ----

<anon>:3:9: 3:16 error: unresolved import my_math::Vec2. Maybe a missing extern crate my_math?

<anon>:3 use my_math::Vec2;

I have also tried other forms of the use statement in the doc comment, including use my_math::*; and use self::my_math::*;. If I remove the line entirely, then I get an error that Vec2 is undefined.

What is the correct way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You must specify the toplevel name of your crate (let's call it mylib):

use mylib::my_math::Vec2;

The rationale is that your doc example must be usable as-is by a client of your library. If you put yourself in their shoes, they would fetch your library (usually by cargo, but it doesn't matter) and then put an extern crate mylib in their toplevel lib.rs/main.rs. Then, in order to use parts of your library, they would have to specify the fully qualified name in order to use its children.

And that's exactly what you have to do in your rustdoc-tested comment.

Also, I think it's worth quoting to the relevant part of the Rust book, Documentation as tests, which explains some minor modifications applied to doc-code snippets. One of them is:

If the example does not contain extern crate, then extern crate <mycrate>; is inserted.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...