Incomplete Constructor Tests in Test Functions
Overview
- Severity: Low
- Confidence: High
- Affected Versions: All
What are Incomplete Constructor Tests?
Incomplete constructor tests occur when test functions for smart contracts do not thoroughly verify all aspects of the contract's constructor. This can lead to missed initialization issues and potential vulnerabilities in the contract's initial state.
Why are Incomplete Constructor Tests Problematic?
Incomplete constructor tests can lead to several issues:
- Failure to detect incorrect initialization of state variables
- Overlooking edge cases in constructor parameter handling
- Missing potential vulnerabilities in the contract's initial setup
- Incomplete validation of constructor's side effects or external calls
- Reduced confidence in the contract's foundational security and correctness
Technical Example of Incomplete Constructor Tests
pragma solidity ^0.8.0;
import "./test.sol";
contract TokenTest is Test {
Token token;
function testConstructor() public {
token = new Token("MyToken", "MTK", 1000000);
assertEq(token.name(), "MyToken");
assertEq(token.symbol(), "MTK");
// Missing checks for total supply and owner initialization
}
}
In this example, the test function only checks the name and symbol of the token, but fails to verify the total supply and any other important initial states set by the constructor.
Technical Example with Comprehensive Constructor Tests
pragma solidity ^0.8.0;
import "./test.sol";
contract TokenTest is Test {
Token token;
function testConstructor(string memory name, string memory symbol, uint256 initialSupply) public {
vm.assume(bytes(name).length > 0 && bytes(symbol).length > 0);
vm.assume(initialSupply > 0 && initialSupply <= type(uint256).max);
token = new Token(name, symbol, initialSupply);
assertEq(token.name(), name);
assertEq(token.symbol(), symbol);
assertEq(token.totalSupply(), initialSupply);
assertEq(token.balanceOf(address(this)), initialSupply);
assertEq(token.owner(), address(this));
// Test constructor reverts with invalid inputs
vm.expectRevert("Name cannot be empty");
new Token("", symbol, initialSupply);
vm.expectRevert("Symbol cannot be empty");
new Token(name, "", initialSupply);
vm.expectRevert("Initial supply must be positive");
new Token(name, symbol, 0);
}
}
In this improved version, the test function comprehensively checks all aspects of the constructor, including:
- Verifying all state variables set by the constructor
- Checking the initial token balance of the contract creator
- Testing constructor behavior with edge case inputs
- Verifying that the constructor reverts with invalid inputs