Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using external files in rust tests

I am writing a service that reads file content from the file, which location is read from env variable FILE_LOCATION.

fn my_function(){
    let path = match env::var("FILE_LOCATION") {
    ...
    let contents = match fs::read(&path) {
}

I have a test file test_file.json in:

proj
  resources
    test
      test_file.json
  src
    main.rs
  tests
    unit_tests.rs

In tests I can set FILE_LOCATION:

env::set_var("FILE_LOCATION", "path/to/test/file");

The question is what should be the value of path/to/test/file?

or in other words:

How can I access external files in Rust tests?

like image 783
Peeech Avatar asked Apr 23 '26 08:04

Peeech


1 Answers

Cargo sets the environment variable CARGO_MANIFEST_DIR to the directory containing your Cargo.toml file. So you can get that environment variable, and append resources/test/test_file.json to it.

See https://doc.rust-lang.org/cargo/reference/environment-variables.html for what environment variables Cargo sets.

like image 126
Daniel Wagner-Hall Avatar answered Apr 26 '26 01:04

Daniel Wagner-Hall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!