https://github.com/qnighy/fakeenv
A simple wrapper of `std::env` which allows faking the environment in Rust
https://github.com/qnighy/fakeenv
mock rust testing
Last synced: 11 months ago
JSON representation
A simple wrapper of `std::env` which allows faking the environment in Rust
- Host: GitHub
- URL: https://github.com/qnighy/fakeenv
- Owner: qnighy
- Created: 2020-01-13T07:28:31.000Z (over 6 years ago)
- Default Branch: master
- Last Pushed: 2020-01-19T07:52:41.000Z (over 6 years ago)
- Last Synced: 2025-04-14T15:18:49.208Z (about 1 year ago)
- Topics: mock, rust, testing
- Language: Rust
- Homepage:
- Size: 10.7 KB
- Stars: 5
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# fakeenv
A simple wrapper of `std::env` which allows faking the environment.
[`std::env`]: https://doc.rust-lang.org/std/env/index.html
# Example
## Using the real environment
```rust
use fakeenv::EnvStore;
fn answer(env: &EnvStore) -> i32 {
env.var("THE_ANSWER").unwrap().parse().unwrap()
}
fn main() {
std::env::set_var("THE_ANSWER", "42");
let env = EnvStore::real();
assert_eq!(answer(&env), 42);
}
```
## Making a fake environment
Fake is only turned on when the `fake` feature is enabled.
As this is mostly for testing purpose, you might want to enable
the feature like this:
```toml
[dependencies]
fakeenv = "0.1.0"
[dev-dependencies]
fakeenv = { version = "0.1.0", features = ["fake"] }
```
Then you can generate a fake environment using [`EnvStore::fake`]:
[`EnvStore::fake`]: struct.EnvStore.html#method.fake
```rust
use fakeenv::EnvStore;
fn answer(env: &EnvStore) -> i32 {
env.var("THE_ANSWER").unwrap().parse().unwrap()
}
fn main() {
let env = EnvStore::fake();
env.set_var("THE_ANSWER", "42");
assert_eq!(answer(&env), 42);
}
```
## Faking user directories
The `dirs` feature enables faking the [`dirs`] functions.
[`dirs`]: https://docs.rs/dirs/2.*/dirs/index.html
```toml
[dependencies]
fakeenv = { version = "0.1.0", features = ["dirs"] }
```
```rust
let env = EnvStore::real();
println!("home directory = {:?}", env.home_dir());
```