1

If I have the following:

├── Cargo.lock
├── Cargo.toml
├── main
│   ├── Cargo.toml
│   └── src
│       └── main.rs
├── module2
│   ├── Cargo.toml
│   └── src
│       ├── lib.rs
│       └── builder.rs

Where the Cargo.toml file in the root is the following:

[workspace]

members = [
    "main",
]

I want to access a function from builder.rs in main when testing(i.e. cfg(test)), how can I do so?

Module2 is a library(it was created by running cargo new module2 --lib.

I tried the following:

// module2/builder.rs

pub fn build() { /*...*/ }
// module2/lib.rs

#[cfg(test)]
mod mock;

#[cfg(test)]
pub use mock::build;
// main/Cargo.toml
// ...
[dependencies]
module2 = { path = "../module2" }
// main.rs

#[cfg(test)]
use module2::build;

/*
...
*/

This doesn't work and I get the following error:

error[E0432]: unresolved import `module2::build`
 --> main/src/main.rs:3:5
  |
3 | use module2::build;
  |     ^^^^^^^^^^^^^^ no `build` in the root
5
  • 1
    module2 is not in your workspace; is this intentional? Commented Aug 17, 2022 at 9:10
  • Please paste the full error here. Commented Aug 17, 2022 at 9:11
  • @ChayimFriedman Yes, it doesn't make any difference if it was in my workspace. Commented Aug 17, 2022 at 9:12
  • 1
    It should not, but this looks like a mistake so I asked. Commented Aug 17, 2022 at 9:13
  • I have pasted the full error now Commented Aug 17, 2022 at 9:14

1 Answer 1

1

test of module1 is not test of main: each crate gets cfg(test) turned on only when it itself is being tested, not when a dependency of it is being tested.

You can use cfg(debug_assertions) as an approximation or a custom feature.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.