Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access files in the src directory from files in my tests directory?

I have a project layout that looks like the following:

src/
    int_rle.rs
    lib.rs
tests/
    test_int_rle.rs

The project compiles with cargo build, but I am unable to run the test with cargo test. I get the error

error[E0432]: unresolved import `int_rle`. There is no `int_rle` in the crate root
 --> tests/test_int_rle.rs:1:5
  |
1 | use int_rle;
  |     ^^^^^^^

error[E0433]: failed to resolve. Use of undeclared type or module `int_rle`
 --> tests/test_int_rle.rs:7:9
  |
7 |         int_rle::IntRle { values: vec![1, 2, 3] }
  |         ^^^^^^^^^^^^^^^ Use of undeclared type or module `int_rle`

error: aborting due to 2 previous errors

error: Could not compile `minimal_example_test_directories`.

My code:

// src/lib.rs
pub mod int_rle;

// src/int_rle.rs

#[derive(Debug, PartialEq)]
pub struct IntRle {
    pub values: Vec<i32>,
}

// tests/test_int_rle.rs
use int_rle;

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        int_rle::IntRle { values: vec![1, 2, 3] }
    }
}

// Cargo.toml
[package]
name = "minimal_example_test_directories"
version = "0.1.0"
authors = ["Johann Gambolputty de von Ausfern ... von Hautkopft of Ulm"]

[dependencies]

Related: How do I compile a multi-file crate in Rust? (how to do it if the test and source files are in the same folder.)

like image 813
The Unfun Cat Avatar asked Jan 06 '23 03:01

The Unfun Cat


1 Answers

The files src/int_rle.rs and src/lib.rs form your library, and together are called a crate.

Your tests and examples folders are not considered part of the crate. This is good, because when someone uses your library, they don't need your tests, they just need your library.

You can fix your issue by adding the line extern crate minimal_example_test_directories; to the top of tests/test_int_rle.rs.

You can read more about Rust's crate and module structure in the book, here.

This should be a working version of your test file:

// tests/test_int_rle.rs
extern crate minimal_example_test_directories;

pub use minimal_example_test_directories::int_rle;

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        super::int_rle::IntRle { values: vec![1, 2, 3] };
    }
}
like image 134
paholg Avatar answered Jan 07 '23 18:01

paholg