Skip to content

Commit

Permalink
feat: add envExists cheatcode to check if a environment variable exis…
Browse files Browse the repository at this point in the history
…ts (#7744)
  • Loading branch information
0xtekgrinder authored Apr 20, 2024
1 parent 6f2668f commit db74e6e
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 0 deletions.
20 changes: 20 additions & 0 deletions crates/cheatcodes/assets/cheatcodes.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions crates/cheatcodes/spec/src/vm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1501,6 +1501,10 @@ interface Vm {
#[cheatcode(group = Environment)]
function setEnv(string calldata name, string calldata value) external;

/// Gets the environment variable `name` and returns true if it exists, else returns false.
#[cheatcode(group = Environment)]
function envExists(string calldata name) external view returns (bool exists);

/// Gets the environment variable `name` and parses it as `bool`.
/// Reverts if the variable was not found or could not be parsed.
#[cheatcode(group = Environment)]
Expand Down
7 changes: 7 additions & 0 deletions crates/cheatcodes/src/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,13 @@ impl Cheatcode for setEnvCall {
}
}

impl Cheatcode for envExistsCall {
fn apply(&self, _state: &mut Cheatcodes) -> Result {
let Self { name } = self;
Ok(env::var(name).is_ok().abi_encode())
}
}

impl Cheatcode for envBool_0Call {
fn apply(&self, _state: &mut Cheatcodes) -> Result {
let Self { name } = self;
Expand Down
1 change: 1 addition & 0 deletions testdata/cheats/Vm.sol

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions testdata/default/cheats/Env.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ contract EnvTest is DSTest {
vm.setEnv(key, val);
}

function testEnvExists() public {
string memory key = "_foundryCheatcodeEnvExistsTestKey";
string memory val = "_foundryCheatcodeEnvExistsTestVal";
vm.setEnv(key, val);
require(vm.envExists(key), "envExists failed");
require(!vm.envExists("nonexistent"), "envExists failed");
}

uint256 constant numEnvBoolTests = 2;

function testEnvBool() public {
Expand Down

0 comments on commit db74e6e

Please sign in to comment.