Truffle
松露腳本:如何在不停止程序的情況下執行多個斷言?
我正在嘗試使用單個腳本執行多個斷言。我的腳本在第一個斷言後停止:我的輸出是:
t$ truffle exec ts4_for_forum.js Using network 'development'. acc2 balance 66998739200000000000 address 0x6b6bD90bFdc16291A9DAa6BDddA78d0Be52184Ba SC1 deployed 0xA368944966a2B816d63646baeC466764F1Ca0c00 Initial SC1: 0xA368944966a2B816d63646baeC466764F1Ca0c00 balance is 22000000000000000000 Deposited 11 Ether from 0x6b6bD90bFdc16291A9DAa6BDddA78d0Be52184Ba, sc1: 0xA368944966a2B816d63646baeC466764F1Ca0c00 balance is 33000000000000000000 { AssertionError [ERR_ASSERTION]: Victim balance not same as victim balance before transfer at module.exports (/home/zulfi/Truffle_programs/transfer_Eth_script/ts4_for_forum.js:41:12) at process._tickCallback (internal/process/next_tick.js:68:7) generatedMessage: false, name: 'AssertionError [ERR_ASSERTION]', code: 'ERR_ASSERTION', actual: '33000000000000000000', expected: '0', operator: '==' }
我的腳本是:
var assert = require('assert'); const MySC1 = artifacts.require("MySC1") module.exports = async function(callback) { try { // Fetch accounts from wallet - these are unlocked const accounts = await web3.eth.getAccounts() // Set up account to transferEther to Victim const acc2 = accounts[2] acc2bal = await web3.eth.getBalance(acc2) web3.utils.fromWei(acc2bal, "ether") console.log('acc2 balance', acc2bal, 'address',acc2) // Fetch the deployed exchange const sc1 = await MySC1.deployed() console.log('SC1 deployed', sc1.address) sc1bal = await web3.eth.getBalance(sc1.address) web3.utils.fromWei(sc1bal, "ether") console.log(`Initial SC1:`,sc1.address,` balance is ${sc1bal}`) amount = '11' await web3.eth.sendTransaction({to:sc1.address, from:acc2, value: web3.utils.toWei(amount)}) sc1bal = await web3.eth.getBalance(sc1.address) web3.utils.fromWei(sc1bal, "ether") console.log(`Deposited ${amount} Ether from ${acc2}, sc1:`, sc1.address,` balance is ${sc1bal}`) assert.equal(sc1bal, '0',"Victim balance not same as victim balance before transfer"); assert.equal(sc1bal, '10',"Testing again Victim balance not same as victim balance before transfer"); } catch(error) { console.log(error) } callback() }
我的sc是:
pragma solidity ^0.5.8; contract MySC1 { address owner; constructor() public { owner = msg.sender; } function sendTo(address payable receiver, uint amount) public { (bool success,) = receiver.call.value(amount)(""); require(success); } function() external payable{ } }
我找到了這個連結,但他們沒有提供任何執行範例,並且與松露無關。 與 Truffle 無關的連結,沒有範例
祖爾菲。
在多個斷言的情況下,如果一個斷言失敗,那麼我們將退出腳本。這個問題可以通過使用 try-catch 塊處理斷言來解決。
祖爾菲。
首先,您沒有將腳本作為單元測試執行,所以我想它並不是一個單元測試。如果它不是一個單元測試,它可能不應該有
assert
s.truffle test
您應該使用該功能執行單元測試。
assert
否則,一般來說,正如您在連結中所說的那樣,每個單元測試應該只有一個。我個人也不經常遵守這條規則,但記住這是一個很好的目標。如果第一個assert
失敗,則第二個assert
根本沒有經過測試,因此您將不知道這是否會成功。單元測試(我猜也是腳本執行)在任何斷言失敗時取消。另外,就您而言,您的兩個斷言沒有多大意義。他們正在檢查一個值是否是兩個不同的值。其中一個斷言將始終失敗,因此腳本將失敗。