我面临与使用Assert.equals()进行字符串比较有关的问题。
我签了一份玩具合同,并做了一个相关的测试,看看问题出在哪里:
https://gist.github.com/brunoarruda/0cf813ee5aefe60427b5788e0489782e
当我使用v0.5.1+commit.c8a2cb62在Remix上运行该测试时,最后一个比较字符串和从它的bytes32对应构建的字符串的断言不会通过。我在assert消息中放置了两个字符串,以查看比较了什么,输出是:
browser/test1_test.sol
1 failing
test_1 - Test user adding
Alice and Alice are not the same.因此,有人知道发生了什么,以及如何使字符串比较工作??
我试图寻找remix_tests.sol源代码来研究发生了什么,但我在任何地方都找不到它。
发布于 2019-07-21 23:38:46
您的代码的问题是,000000000000000000000000000000000000000000000000000000在0x416c696365000000000000000000000000000000000000000000000000000000中也被字符\u0000解码。
要解决这个问题,您可以使用这个函数bytes32ToString在没有零的情况下正确解码:
import "remix_tests.sol"; // this import is automatically injected by Remix.
import "./ContainerContract.sol";
contract test_1 {
ContainerContract container;
function beforeAll () public {
container = new ContainerContract();
}
function testUserAdding() public returns (string memory) {
// setup
string memory name = "Alice";
bytes32 nameBytes = 0x416c696365000000000000000000000000000000000000000000000000000000;
// processing
container.addData(name);
bytes32 recoveredNameBytes = container.data(0);
string memory recoveredName = bytes32ToString(recoveredNameBytes);
// asserting
Assert.equal(nameBytes, recoveredNameBytes, "byte representations should be the same.");
Assert.equal(name, name, "They should be literally the same.");
string memory assertMsg = string(abi.encodePacked(name, " and ", recoveredName, " are not the same."));
Assert.equal(name, recoveredName, assertMsg);
}
function bytes32ToString(bytes32 x) public returns (string memory value) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
value = string(bytesStringTrimmed);
}
}https://ethereum.stackexchange.com/questions/73142
复制相似问题