首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Assert.equals()奇怪的行为不识别(显然)相等的字符串

Assert.equals()奇怪的行为不识别(显然)相等的字符串
EN

Ethereum用户
提问于 2019-07-21 20:05:48
回答 1查看 383关注 0票数 1

我面临与使用Assert.equals()进行字符串比较有关的问题。

我签了一份玩具合同,并做了一个相关的测试,看看问题出在哪里:

https://gist.github.com/brunoarruda/0cf813ee5aefe60427b5788e0489782e

当我使用v0.5.1+commit.c8a2cb62在Remix上运行该测试时,最后一个比较字符串和从它的bytes32对应构建的字符串的断言不会通过。我在assert消息中放置了两个字符串,以查看比较了什么,输出是:

代码语言:javascript
复制
browser/test1_test.sol
1 failing

test_1 - Test user adding
Alice and Alice are not the same.

因此,有人知道发生了什么,以及如何使字符串比较工作??

我试图寻找remix_tests.sol源代码来研究发生了什么,但我在任何地方都找不到它。

EN

回答 1

Ethereum用户

回答已采纳

发布于 2019-07-21 23:38:46

您的代码的问题是,0000000000000000000000000000000000000000000000000000000x416c696365000000000000000000000000000000000000000000000000000000中也被字符\u0000解码。

要解决这个问题,您可以使用这个函数bytes32ToString在没有零的情况下正确解码:

代码语言:javascript
复制
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);
    }
}
票数 1
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/73142

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档