methodic_scout-contract-lab/test/Greeter.t.sol

73 lines
2.4 KiB
Solidity

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "forge-std/Test.sol";
import "../contracts/Greeter.sol";
contract GreeterTest is Test {
Greeter public greeter;
address public owner;
address public randomUser;
function setUp() public {
owner = makeAddr("owner");
randomUser = makeAddr("randomUser");
vm.prank(owner);
greeter = new Greeter("Hello, World!");
}
function test_Constructor() public {
assertEq(greeter.getGreeting(), "Hello, World!", "Initial greeting should match constructor");
assertEq(greeter.getOwner(), owner, "Owner should be contract deployer");
assertEq(greeter.getGreetingCount(), 0, "Initial greeting count should be zero");
}
function test_Greet() public {
vm.prank(randomUser);
string memory greeting = greeter.greet();
assertEq(greeting, "Hello, World!", "Greeting should return correct message");
assertEq(greeter.getGreetingCount(), 1, "Greeting count should increment");
}
function testFuzz_SetGreeting(string memory newGreeting) public {
vm.assume(bytes(newGreeting).length > 0);
vm.assume(keccak256(bytes(newGreeting)) != keccak256(bytes("Hello, World!")));
vm.prank(owner);
greeter.setGreeting(newGreeting);
assertEq(greeter.getGreeting(), newGreeting, "Greeting should update correctly");
}
function testRevert_SetGreetingUnauthorized() public {
vm.prank(randomUser);
vm.expectRevert(abi.encodeWithSelector(Greeter.Unauthorized.selector, randomUser));
greeter.setGreeting("Unauthorized Greeting");
}
function testRevert_SetEmptyGreeting() public {
vm.prank(owner);
vm.expectRevert(abi.encodeWithSelector(Greeter.InvalidGreeting.selector, "New greeting cannot be empty"));
greeter.setGreeting("");
}
function testRevert_SetSameGreeting() public {
vm.prank(owner);
vm.expectRevert(abi.encodeWithSelector(Greeter.InvalidGreeting.selector, "New greeting must be different"));
greeter.setGreeting("Hello, World!");
}
function test_GetGreeting() public {
assertEq(greeter.getGreeting(), "Hello, World!", "Get greeting should return current greeting");
}
function testGas_Greet() public {
greeter.greet();
}
function testGas_SetGreeting() public {
vm.prank(owner);
greeter.setGreeting("New Greeting");
}
}