Skip to content

Instantly share code, notes, and snippets.

@phuson
Last active April 5, 2022 19:31
Show Gist options
  • Save phuson/7fc3ac1f8abde377e8374609c4971967 to your computer and use it in GitHub Desktop.
Save phuson/7fc3ac1f8abde377e8374609c4971967 to your computer and use it in GitHub Desktop.
Since OpenZeppelin AccessControl's dynamic error messaging changes based on the sender's address and the checked role, it's been a challenge to write tests against it. As part of my solution, I wrote a utility function to automate the error message generation for my tests in Foundry Forge.
function getEncodedAccessControlError(address account, bytes32 role)
public
pure
returns (bytes memory)
{
return
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
);
}
// test in Forge
function testAccessControl() public {
vm.startPrank(user);
vm.expectRevert(
getEncodedAccessControlError(user, ADMIN_ROLE)
);
contract.doSomethingThatRequiresAdminRole();
vm.stopPrank();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment