How to share set-up between multiple documentation example

I have a function that can be uses in quite different ways. I would like to give an example for all possible usages, but the set-up required before calling the function is quite long (about 10 lines). Is it possible to share the set-up between multiple tests?

/// common set-up
/// ```
/// let graph = create_graph();
/// let a = graph.add_node();
/// let b = graph.add_node();
/// let c = graph.add_node();
/// ```
///
/// first usage
/// ```
/// foo(graph, a);
/// ```
///
/// second usage
/// ```
/// foo(graph, b);
/// ```
fn foo(g: Graph, node: Graph::Node);

No, but you can hide it by prefixing the lines with # or move it into a separate function.

… or put it in a macro

Is it possible to use #[cfg(doctest)] for such common setup functions?
I didn't tested it, but I think things like this would be possible.

#[cfg(doctest)]
pub mod doctest {
    pub fn create_graph() -> (Graph, Graph::Node, Graph::Node) { .. }
}

/// Does foo.
///
/// common set-up
// This is actually implemented in `doctest::create_graph()`, so don't run this directly.
///
/// ```no_run
/// let graph = create_graph();
/// let a = graph.add_node();
/// let b = graph.add_node();
/// let c = graph.add_node();
/// ```
///
/// ```
/// #let (graph, a, _b) = doctest::create_graph();
/// foo(graph, a);
/// ```
///
/// Another example.
///
/// ```
/// #let (graph, _a, b) = doctest::create_graph();
/// foo(graph, b);
/// ```
fn foo(g: Graph, node: Graph::Node) { .. }

Thanks all. I think that @nop_thread's solution is the best so far. However, I cannot manage to import doctest.

failed to resolve: use of undeclared type or module doctest

Note that they will still link against only the public items of your crate; if you need to test private items, you need to write a unit test.

Documentation tests -

Sorry, cfg(doctest) seems to work only when collecting items, and we cannot link them to the doctest executable.
My idea don't work, and I think such functions available only for doctests is not possible.

(Marking the setup function #[doc(hidden)] might be useful, but it is not elegant because it actually exports the function.)

Oh! That's sad :frowning: And this also means that it's not possible to have an example split in more than 1 part.

For anyone interested, I opened a RFC to try to solve this issue. The initial proposition I did need modifications that are explained in the comment.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.