unit-testing - 单元测试日期时间值

标签 unit-testing ethereum solidity

我有一个使用当前时间的函数 (now)。契约(Contract)作为一个整体是一个众筹代币,代币的成本根据购买代币的日期和时间而有所不同。

测试智能合约时如何模拟不同的时间?例如,对于下面的代码,我想做单元测试以确定设置价格的代码是否正确,但我无法更改 now 的值。

简单地将 now 关键字替换为另一个临时测试变量(例如 now_sim ,然后在期间手动更改 now_sim 是否是一个很好的解决方案模拟?

    if (now < (startTime + 1 days)) {
        currentPrice = safeDiv(safeMul(price, 80), 100);  // 20 % discount (x * 80 / 100)
    } 
    else if (now < (startTime + 2 days)) {
        currentPrice = safeDiv(safeMul(price, 90), 100);  // 10 % discount (x * 90 / 100)
    }
    else if (now < (startTime + 12 days)) {
        // 1 % reduction in the discounted rate from day 2 until day 12 (sliding scale per second)
        // 8640000 is 60 x 60 x 24 x 100 (100 for 1%) (60 x 60 x 24 for seconds per day)
        currentPrice = price - safeDiv(safeMul((startTime + 12 days) - now), price), 8640000);
    }
    else {
        currentPrice = price;
    }

最佳答案

如果您使用 pyethereum 进行测试——我强烈推荐,它很不错——您可以直接更改正在挖掘您的交易的模拟区 block 的时间戳。

self.s = t.state()
self.s.block.timestamp = self.s.block.timestamp + 86400
self.s.mine(1)
some_val = your_contract.do_something(some_parameter)
self.assertEqual(some_val, whatever)

请在此处查看工作示例(可能有点过时):https://github.com/realitykeys/subjectivocracy/blob/master/contracts/test.py#L85

关于unit-testing - 单元测试日期时间值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43250397/

相关文章:

unit-testing - F# - 如何使用 NUnit 正确实现设置和初始化变量

mysql - 测试时的 CakePHP 连接

ethereum - 如何在 Solidity 中实现自毁模式?

c++ - 通过引用识别 Lambda

cryptography - Solidity:插入符号 ^ 运算符有什么作用?

Python 3、以太坊——如何发送 ERC20 代币?

blockchain - 无法通过 Etherscan 验证 Truffle 部署的合约

arrays - Solidity 中字符串到数组的转换

ethereum - Solidity 中定点数的求幂(即 a^b)

unit-testing - Electron + Jest - ipcRenderer 在单元测试中未定义