rustsubstrate

How to share a file in test files?


I have this hierarchy in my substrate pallet:

src/
├── lib.rs
├── mock.rs
├── tests.rs
└── common.rs
Cargo.toml

My mock.rs and tests.rs need to share some constants and types, so I put those into common.rs.

in my mock.rs and tests.rs:

mod common;
use crate::common::{
        TOKEN_TRANSFER_FEE, Balance,
};

in my common.rs:

pub mod common {
  pub type Balance = u128;

  pub const TOKEN_TRANSFER_FEE: Balance = 1_000;
}

then I got these errors:

error[E0583]: file not found for module `common`
  --> pallets/bridge/src/mock.rs:48:1
   |
48 | mod common;
   | ^^^^^^^^^^^
   |
   = help: to create the module `common`, create file "pallets/bridge/src/mock/common.rs" or "pallets/bridge/src/mock/common/mod.rs"

error[E0583]: file not found for module `common`
  --> pallets/bridge/src/tests.rs:36:1
   |
36 | mod common;
   | ^^^^^^^^^^^
   |
   = help: to create the module `common`, create file "pallets/bridge/src/tests/common.rs" or "pallets/bridge/src/tests/common/mod.rs"

Is there an easier way to import those constants and types from that shared common file into mock.rs and tests.rs, instead of making mock folder and tests folders?


Solution

  • Use only mod once and in the other files use:

    lib

    mod common;
    mod mock;
    
    fn entry() {
        eprintln!("{}", common::common::TEST);
    }
    

    common

    pub mod common {
        pub const TEST: &str = "";
    }
    

    mock

    use crate::common;
    
    fn mock() {
        eprintln!("{}", common::common::TEST);
    }