Home > Mobile >  How to generate documentation for modules that are behind #[cfg(test)]?
How to generate documentation for modules that are behind #[cfg(test)]?

Time:05-25

In a Rust project there is a module with utilities to support testing, packed in a module test_utils:

#[cfg(test)]
pub mod test_utils;

Question: is there a way to make cargo doc generate also the documentation for test_utils module and the things inside?

CodePudding user response:

There are probably multiple ways of generating documentation for tests, but I think the easier approach is to generate the documentation with cargo rustdoc and pass the --cfg test flag through:

cargo rustdoc -- --cfg test

CodePudding user response:

I just found that this works too:

#[cfg(any(test, doc))]
pub mod test_utils;

While documentation is generated with regular

cargo doc

CodePudding user response:

I think #[cfg(any(test, doc))] is probably not enough, it will generate doc with no function information.

/// The module should work
#[cfg(any(test, doc))]
pub mod test_utils {

    /// The function about test1
    #[test]
    fn test1() {
        assert!(true);
    }
}

enter image description here

In order to doc with utilities to support testing, perhaps [cfg_attr(not(doc), test)] is necessary.

/// The module should work
#[cfg(any(test, doc))]
pub mod test_utils {

    /// The function about test1
    #[cfg_attr(not(doc), test)]
    fn test1() {
        assert!(true);
    }
}

After added [cfg_attr(not(doc), test)] above test cases:

enter image description here

  • Related