Unit Testing in Truffle

@George
After running it again, this is the full message.

truffle(ganache)> test
Using network ‘ganache’.not recognized as an internal or external command,
operable program or batch file.

Compiling your contracts…eopleproject>test
=========================== an internal or external command,

Compiling .\contracts\Migrations.sol
Compiling .\contracts\Ownable.sol
Compiling .\contracts\People.soloject>truffle console
Compiling .\contracts\Ownable.sol
Artifacts written to C:\Users\Archie\AppData\Local\Temp\test–2344-Us7dwZm5s1Ga
Compiled successfully using:

  • solc: 0.5.12+commit.7709ece9.Emscripten.clang

TypeError [ERR_INVALID_REPL_INPUT]: Listeners for uncaughtException cannot be used in the REPL
at process. (repl.js:256:15)
at process.emit (events.js:327:22)
at process.emit (C:\Program Files (x86)\node-v12.18.3-win-x64\node_modules\truffle\build\webpack:\node_modules\source-map-support\source-map-support.js:495:1)
at _addListener (events.js:358:14)
at process.addListener (events.js:406:10)
at Runner._addEventListener (C:\Program Files (x86)\node-v12.18.3-win-x64\node_modules\truffle\node_modules\mocha\lib\runner.js:200:10)
at Runner.run (C:\Program Files (x86)\node-v12.18.3-win-x64\node_modules\truffle\node_modules\mocha\lib\runner.js:1033:8)
at Mocha.run (C:\Program Files (x86)\node-v12.18.3-win-x64\node_modules\truffle\node_modules\mocha\lib\mocha.js:1002:17)
at C:\Program Files (x86)\node-v12.18.3-win-x64\node_modules\truffle\build\webpack:\packages\core\lib\test.js:159:1
at new Promise ()
at Object.run (C:\Program Files (x86)\node-v12.18.3-win-x64\node_modules\truffle\build\webpack:\packages\core\lib\test.js:158:1)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
truffle(ganache)>

    it("should have a balance of 1 ether", async () => {
        let instance = await People.new();
        await instance.createPerson("Tim", 30, 180, {
            from: accounts[5], value: web3.utils.toWei("1", "ether")
        });

        let balance = await web3.eth.getBalance(instance.address);

        assert.equal(balance, web3.utils.toWei("1", "ether"), "The balance is not 1 ether");
    });
    it("should be able to withdraw all if is the owner", async () => {
        let instance = await People.new();
        await instance.createPerson("Tim", 30, 180, {
            from: accounts[5], value: web3.utils.toWei("1", "ether")
        });
        
        await truffleAssert.passes(instance.withdrawAll({from: accounts[0]}));
    });
    it("should have a balance of 0 ether", async () => {
        let instance = await People.new();
        await instance.createPerson("Tim", 30, 180, {
            from: accounts[5], value: web3.utils.toWei("1", "ether")
        });
        await instance.withdrawAll({from: accounts[0]});

        let balance = await web3.eth.getBalance(instance.address);

        assert.equal(balance, 0, "The balance is not 0");
    });
1 Like

@Archie_Smyth
looks like you don’t have ganache started,
or if you have it started, you haven’t linked the project to ganache

@Archie_Smyth
Make sure your PORT is same as in Ganache.

to verify, go to truffle-config.js (PORT is 8545 in this case)

 networks: {
    // Useful for testing. The `development` name is special - truffle uses it by default
    // if it's defined here and no other network is specified at the command line.
    // You should run a client (like ganache-cli, geth or parity) in a separate terminal
    // tab if you use this network and you must also set the `host`, `port` and `network_id`
    // options below to some value.
    //
    development: {
     host: "127.0.0.1",     // Localhost (default: none)
     port: 8545,            // Standard Ethereum port (default: none)
     network_id: "*",       // Any network (default: none)
    },
1 Like
contract("People", async function(accounts){

     it("should not be able to delete unless owner", async function() {
          let instance = await People.deployed();
          await truffleAssert.fails(instance.deletePerson({from: accounts[5]}));
     });

     it("should be able to delete since owner", async function() {
          let instance = await People.deployed();
          await truffleAssert.fails(instance.deletePerson({from: accounts[0]}));
     });

});
1 Like

Owner Test Assignment

Click to Reveal Code
const People = artifacts.require("People");
const truffleAssert = require("truffle-assertions");
// The STATE of the contract is preserved through each test
contract("People", async function(accounts){
  it("shouldn't create a person with age over 150 years", async function(){
    let instance = await People.deployed();
    await truffleAssert.fails(instance.createPerson("Bob", 200, 175, {value: web3.utils.toWei("1", "ether")}), truffleAssert.ErrorType.REVERT);
  });
  it("shouldn't create a person without payment", async function(){
    let instance = await People.deployed();
    await truffleAssert.fails(instance.createPerson("Bob", 200, 175, {value: 1000}), truffleAssert.ErrorType.REVERT);
  });
  it("should set senior status correctly", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    let result = await instance.getPerson();
    assert(result.senior === true, "Senior level not set");
  });
  it("should set age correctly", async function(){
    let instance = await People.deployed();
    let result = await instance.getPerson();
    assert(result.age.toNumber() === 65, "Age not set correctly");
  });
  // To test the owner, we need to test functions in the People contract that
  // only the owner should be able to do.
  it("should only let the owner of the contract delete people from the contract", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.passes(instance.deletePerson(accounts[1], {from: accounts[0]}));
  });
  it("shouldn't let anyone except the owner of the contract delete people from the contract", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.fails(instance.deletePerson(accounts[1], {from: accounts[1]}), truffleAssert.ErrorType.REVERT);
  });
  it("should only let the owner of the contract spend its balance", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.passes(instance.withdrawAll({from: accounts[0]}));
  });
  it("shouldn't let anyone except the owner of the contract spend its balance", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.fails(instance.withdrawAll({from: accounts[1]}), truffleAssert.ErrorType.REVERT);
  });
  it("should only let the owner of the contract retrieve the contract owner's address", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.passes(instance.getCreator([0], {from: accounts[0]}));
  });
  it("shouldn't let anyone except the owner of the contract retrieve the contract owner's address", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.fails(instance.getCreator([0], {from: accounts[1]}));
  });
})

I built the tests with “it should” statements and their contrapositives. I think this should prevent errors in the code “from either direction”, if you catch my drift. The output:

Peopletest.js Result

1 Like

Balance Unit Test Assignment

// Check that the create person method is working.
	it("createPerson-03", async function ()
	{
		let theBalance1 = Number(await web3.eth.getBalance(personContract.address));
		theBalance1 += Number(web3.utils.toWei("1", "ether"));

		await personContract.createPerson("Test-03", 65, 190, {value: web3.utils.toWei("1", "ether")});

		// Check the senior flag.
		let thePerson = await personContract.getPerson();
		assert(thePerson.senior === true, "Senior flag not set.");

		// Check the contract balance.
		let theBalance2 = Number(await web3.eth.getBalance(personContract.address));
		assert(theBalance1 === theBalance2, "Expected: " + theBalance1 + " Actual: " + theBalance2);
	});

it("getBalance-01", async function ()
	{
		await personContract.createPerson("Test-06", 65, 190, {from: inAccounts[1], value: web3.utils.toWei("1", "ether")});
		let theBalance = Number(await web3.eth.getBalance(personContract.address));
		assert(theBalance > 0, "Expected: > 0" + " Actual: " + theBalance);

		await personContract.withdrawAll();

		// Check the contract balance.
		theBalance = Number(await web3.eth.getBalance(personContract.address));
		assert(0 === theBalance, "Expected: 0" + " Actual: " + theBalance);
	});
1 Like

Value Assignment

Click to Reveal Code (LONG)
const People = artifacts.require("People");
const truffleAssert = require("truffle-assertions");
// The STATE of the contract is preserved through each test
contract("People", async function(accounts){

    let instance;
  // before function runs ONCE ONLY, before ANY and ALL tests
  before(async function(){
    instance = await People.deployed();
  });

  // after();
  // afterEach();

  it("shouldn't create a person with age over 150 years", async function(){
    // beforeEach function executes here for EVERY test
    await truffleAssert.fails(instance.createPerson("Bob", 200, 175, {value: web3.utils.toWei("1", "ether")}), truffleAssert.ErrorType.REVERT);
  });
  it("shouldn't create a person without payment", async function(){
    await truffleAssert.fails(instance.createPerson("Bob", 200, 175, {value: 1000}), truffleAssert.ErrorType.REVERT);
  });
  it("should set senior status correctly", async function(){
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    let result = await instance.getPerson();
    assert(result.senior === true, "Senior level not set");
  });
  it("should set age correctly", async function(){
    let result = await instance.getPerson();
    assert(result.age.toNumber() === 65, "Age not set correctly");
  });
  // To test the owner, we need to test functions in the People contract that
  // only the owner should be able to do.
  it("should only let the owner of the contract delete people from the contract", async function(){
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.passes(instance.deletePerson(accounts[1], {from: accounts[0]}));
  });
  it("shouldn't let anyone except the owner of the contract delete people from the contract", async function(){
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.fails(instance.deletePerson(accounts[1], {from: accounts[1]}), truffleAssert.ErrorType.REVERT);
  });
  it("should only let the owner of the contract retrieve the contract owner's address", async function(){
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.passes(instance.getCreator([0], {from: accounts[0]}));
  });
  it("shouldn't let anyone except the owner of the contract retrieve the contract owner's address", async function(){
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.fails(instance.getCreator([0], {from: accounts[1]}));
  });
  it("should have the balance increase when a new person is created", async function(){
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    let blockchainBalance = await web3.eth.getBalance(instance.address);
    let contractBalance = await instance.balance();
    assert(contractBalance == blockchainBalance, "The contract balance differs from the blockchain balance");
  });
  it("should only let the owner of the contract spend its balance", async function(){
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});

    let oldContractBalance = parseInt(await instance.balance());
    let oldOwnerBalance = parseInt(await web3.eth.getBalance(accounts[0]));

    let withdrawal = await instance.withdrawAll({from: accounts[0]});
    let newOwnerBalance = parseInt(await web3.eth.getBalance(accounts[0]));

    let blockchainBalance = parseInt(await web3.eth.getBalance(instance.address));
    let newContractBalance = parseInt(await instance.balance());
    assert(newContractBalance == blockchainBalance, "The contract balance differs from the blockchain balance");
    assert(blockchainBalance == 0, "The balance on the blockchain is not zero");
    // See https://www.trufflesuite.com/docs/truffle/getting-started/interacting-with-your-contracts
    // and/or https://web3js.readthedocs.io/en/v1.2.7/web3-eth.html
    // for more info on commands & syntax
    const gasWithdrawal = withdrawal.receipt.gasUsed;
    const withdrawalTx = await web3.eth.getTransaction(withdrawal.tx);
    const gasWithdrawalPrice = withdrawalTx.gasPrice;
    const totalGasCost = gasWithdrawal * gasWithdrawalPrice
    // Inputs - Outputs = Fees
    // --> Inputs - Fees = Outputs
    assert.equal(oldOwnerBalance + oldContractBalance - totalGasCost, newOwnerBalance, "The contract balance has not been withdrawn correctly")
  });
  it("shouldn't let anyone except the owner of the contract spend its balance", async function(){
    await instance.createPerson("Bob", 65, 175, {value: web3.utils.toWei("1", "ether")});
    await instance.createPerson("Carol", 39, 155, {value: web3.utils.toWei("1", "ether")});
    await truffleAssert.fails(instance.withdrawAll({from: accounts[1]}), truffleAssert.ErrorType.REVERT);
  });

})

Definitely the most tricky assignment so far. The penultimate ‘it’ statement regarding only letting the owner of the contract withdraw its balance was coded quite thoroughly. I saw some much shorter solutions throughout the forum, but I wanted to encapsulate everything that Filip mentioned in the assignment video into the test function.

I learnt that the getBalance function returns a string rather than a number (couldn’t think of a reason why, maybe strings take less memory?), so I found out about the parseInt function to change strings into integers.

I also learnt about the functions receipt, gasUsed, getTransaction and gasPrice. When I initially ran the tests, I was finding small discrepancies between the owner’s before and after balances. Then I realised I forgot about the gas fees!

Peopletest.js Final Result

1 Like

@Uyan
Good job keep going :+1:

1 Like

This one took me ages to figure out… :exploding_head:
Owner test assignment:

    // Test if the DeletePerson function is only accassible by the owner.
    it("should not be possible to delete a person if not called by the owner.", async function(){
      let instance = await People.deployed();
      let owneraddres = accounts[0];
      let useraddres = accounts[1];

      await instance.createPerson("DeletablePerson", 50, 190, {from: owneraddres, value: web3.utils.toWei("1", "ether")});

      await truffleAssert.fails(instance.deletePerson(owneraddres,{from: useraddres}), truffleAssert.ErrorType.REVERT);
    });

    // Test if the DeletePerson function deletes a person when used by the owner.
    it("should be possible to delete a person if called by the owner.", async function(){
      let instance = await People.deployed();
      let owneraddres = accounts[0];
      let useraddres = accounts[1];

      await truffleAssert.passes(instance.deletePerson(useraddres,{from: owneraddres}), 'Deleting the person failed.');
    });
1 Like

contract("People", async function(**accounts**){
         let instance;
    it("should not allow non-owner to delete people", async function(){
        let instance = await People.deployed();
        await instance.createPerson( "Bob", 45, 140, {from: accounts[2], value: web3.utils.toWei("1", "ether")});
        await truffleAssert.fails(instance.getCreator(0, {from: accounts[2]}), truffleAssert.ErrorType.REVERT);
    });

    it("should allow the owner to delete people", async function(){
        let instance = await People.deployed();
        await instance.createPerson("Bob", 45, 140, {from: accounts[2], value: web3.utils.toWei("1", "ether")});
        await truffleAssert.passes(instance.deletePerson(accounts[1], {from: accounts[0]}));
    });
 });

I did the actual test of the modifier with a different function of the contract for the second test. I wasn't happy with how much I struggled and cheated so I did so to make sure of my understanding. I normally wouldn't do that for the sake of consistency.



 Value Assignment

    it("should have the recorded balance equal to the balance on chain", async function(){
        let instance = await People.deployed()
        await instance.createPerson("Bob", 35, 160, {value: web3.utils.toWei("1", "ether")});
        let ContractBalance = await instance.getContractBalance.call();
        let ChainBalance = await web3.eth.getBalance(instance.address);
        assert.equal( ContractBalance, ChainBalance );
   });

   it("should allow owner to withdraw All with the balance reverting to 0", async function(){
        let instance = await People.deployed()
        await instance.withdrawAll();
        let ContractBalance = await instance.getContractBalance.call();
        assert.equal( ContractBalance, 0 );
   });

   it("should allow owner to withdraw All and the contract balance should match the on chain balance", async function(){
        let instance = await People.deployed();
        await instance.createPerson("Bob", 35, 160, {value: web3.utils.toWei("1", "ether")});
        await instance.withdrawAll();
        let ContractBalance = await instance.getContractBalance.call();
        let ChainBalance = await web3.eth.getBalance(instance.address);
        assert.equal( ContractBalance, ChainBalance );
  });


 Added this in People.sol
  function getContractBalance() public returns(uint) {
         return balance;
    }

1 Like

Value assignment
This is my solution to the value assignment.

const People = artifacts.require("People");
const truffleAssert = require("truffle-assertions");

contract("People", async function(accounts){
  it("Should not be deleted by non-owner", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Bob", 65, 190, {value: web3.utils.toWei("1", "ether"), from: accounts[1]});
    await truffleAssert.fails(instance.deletePerson(accounts[1], {from: accounts[2]}), truffleAssert.ErrorType.REVERT);
  });
  it("Should be deleted by owner", async function(){
    let instance = await People.deployed();
    await instance.createPerson("John", 65, 190, {value: web3.utils.toWei("1", "ether"), from: accounts[2]});
    await instance.deletePerson(accounts[2], {from: accounts[0]});
    await truffleAssert.fails(instance.getPerson(accounts[2]));
  });

});

1 Like
it("Shouldn't delete the person!", async function(){
		let instance = await People.deployed();
		await instance.deletePerson(accounts[1]);
		let	result = await instance.getPerson();
		assert(result.age.toNumber() === 70);
	});
	it("Should delete the created person", async function(){
		let instance = await People.deployed();
		await instance.deletePerson(accounts[0]);
		let	result = await instance.getPerson();
		assert(result.age.toNumber() === 0);
	});
});
1 Like
it("Should transfer all money from the contarct to the owner address", async function(){
		await truffleAssert.passes(instance.withdrawAll({from: accounts[0]}));
	});
	it("Shouldn't transfer all money from the contarct to the address", async function(){
		await truffleAssert.fails(instance.withdrawAll({from: accounts[1]}), truffleAssert.ErrorType.REVERT);
	});
	it("Should increase the balance correctly!", async function(){
		let contractBalance = await instance.balance();
    	let onChainBalance = await web3.eth.getBalance(People.address);
    	assert(parseInt(contractBalance) === parseInt(onChainBalance));
	});
1 Like

This is my code for the value assignment.

contract("People", async function(accounts){
  
  it("Should increase balance correctly after createPerson", async function(){
    let instance = await People.new();
    await instance.createPerson("Alice", 21, 170, {value: web3.utils.toWei("1.5", "ether"), from: accounts[1]});

    let balanceOnChain = await web3.eth.getBalance(instance.address);
    let balanceInternal = await instance.balance();
    assert(balanceInternal == balanceOnChain && balanceInternal == web3.utils.toWei("1.5", "ether"));
  });
  it("Should not allow withdrawal of balance by non-owner", async function(){
    let instance = await People.new();
    await instance.createPerson("Alice", 21, 170, {value: web3.utils.toWei("1.5", "ether"), from: accounts[1]});
    await truffleAssert.fails(instance.withdrawAll({from: accounts[1]}, truffleAssert.ErrorType.REVERT));
  });
  it("Should allow withdrawal of balance by owner", async function(){
    let instance = await People.new();
    await instance.createPerson("Alice", 21, 170, {value: web3.utils.toWei("1.5", "ether"), from: accounts[1]});
    await truffleAssert.passes(instance.withdrawAll({from: accounts[0]}));
  });
  it("Should increase balance of owner after withdawal", async function(){
    let instance = await People.new();
    await instance.createPerson("Alice", 21, 170, {value: web3.utils.toWei("1.5", "ether"), from: accounts[1]});

    let balanceBefore = await web3.eth.getBalance(accounts[0]);
    let balanceContract = await web3.eth.getBalance(instance.address);
    await instance.withdrawAll({from: accounts[0]});
    let balanceAfter = await web3.eth.getBalance(accounts[0]);
    assert(balanceBefore + balanceContract <= balanceAfter, "Owners balance was not increased after withdrawal contract balance");
  });
  it("Should set balance to zero", async function(){
    let instance = await People.new();
    await instance.createPerson("Alice", 21, 170, {value: web3.utils.toWei("1.5", "ether"), from: accounts[1]});
    
    await instance.withdrawAll({from: accounts[0]});
    let balanceOnChain = await web3.eth.getBalance(instance.address);
    let balanceInternal = await instance.balance();
    assert(balanceOnChain == 0 && balanceInternal == 0, "Contract balance is not set to 0");
  });
});

onlyOwner Assignment:

contract("People", async function(accounts){
  it("shouldn't allow any not contract owner to delete a person", async function(){
    let instance = await People.deployed();
    await instance.createPerson("Hans", 22, 172, {value: web3.utils.toWei("1", "ether"), from: accounts[1]});
    await truffleAssert.fails(instance.deletePerson(accounts[1], {from: accounts[2]}));
  });
    it("should be possible to delete a person by the contract owner", async function(){
    let instance = await People.deployed();
    await instance.deletePerson(accounts[1], {from: accounts[0]});
    let result = await instance.getPerson({from: accounts[1]});
    assert(result.age.toNumber() === 0, "Person is not deleted");
  });
});

Had initially little troubles with the testing program failing miserably, due to the fact not including “accounts” in the function call after inside contract() statement and secondly adding “accounts” in the function call inside the it() statement.
Error caused was: “Error: The send transactions “from” field must be defined!”

it("Should add 1 eth to the balance of contract on createPerson call", async () => {
        let instance = await People.new();
   
        await instance.createPerson("Catdog", 43, 33, {value: web3.utils.toWei("1","ether")});
        assert(await web3.eth.getBalance(instance.address) === web3.utils.toWei("1","ether"));
    });

    it("Should allow owner to withdraw balance from contract on withdrawAll call", async () => {
        let instance = await People.new();
        await truffleAssert.passes(instance.withdrawAll());
    });

    it("Should reduce contract balance to 0 on withdrawAll function call", async () => {
        let instance = await People.new();
        await instance.createPerson("Bob", 33, 13, {value: web3.utils.toWei("1","ether")});
        assert(await web3.eth.getBalance(instance.address) === web3.utils.toWei("1","ether"));

        await instance.withdrawAll();
        assert(await web3.eth.getBalance(instance.address) === web3.utils.toWei("0","ether"));
    });

    it("Should increase owner balance on withdrawAll function call", async () => {
        let instance = await People.new();
        await instance.createPerson("batman", 83, 22, {value: web3.utils.toWei("1","ether")});
       
        let ownerBalance = await web3.eth.getBalance(accounts[0]);
        await instance.withdrawAll();
        assert(await web3.eth.getBalance(accounts[0]) > ownerBalance);
    });
1 Like

Code deletePerson Function:

contract("People", async function (accounts){
  let instance;

  before(async function(){
    instance = await People.deployed();
  });
  
  it("should only contract owner delete", async function(){
    //let instance = await People.deployed();
    await instance.createPerson("Anna", 65, 190, {from: accounts[1], value: web3.utils.toWei("1", "ether")});
    await truffleAssert.passes(instance.deletePerson(accounts[1], {from: accounts[0]}));
    });
  it("shouldn't other user delete", async function(){
    //let instance = await People.deployed();
    await instance.createPerson("Anna", 65, 190, {from: accounts[1], value: web3.utils.toWei("1", "ether")});
    await truffleAssert.fails(instance.deletePerson(accounts[1],{from: accounts[1]}),truffleAssert.ErrorType.REVERT);
  });
});
1 Like

Withdraw Assignment

contract("People", async function(accounts){

  let instance;

  before(async function(){
    instance = await People.deployed();
  });
it("should increase balance by 1 Ether on people creation", async function(){
    let bcBalance_before = await web3.eth.getBalance(instance.address);
    await instance.createPerson("Hans", 22, 172, {value: web3.utils.toWei("1", "ether"), from: accounts[3]});
    let bcBalance_after = await web3.eth.getBalance(instance.address);
    assert(bcBalance_before < bcBalance_after && (bcBalance_after - bcBalance_before) == web3.utils.toWei("1", "ether"));
  });
  it("should have same balance in variable as on chain", async function(){
    let bcBalance = await web3.eth.getBalance(instance.address);
    let contractBalance;
    await instance.balance.call(function(err, result){contractBalance = result});
    assert(bcBalance === contractBalance );
  });
  it("shouldn't be possible to withdraw contract blance from non-owner", async function(){
    truffleAssert.fails(instance.withdrawAll({from: accounts[1]}));
  });
  it("should be possible to withdraw the contract balance to owner", async function(){
    let ownerBalance_before = await web3.eth.getBalance(accounts[0]);
    await instance.withdrawAll()
    let ownnerBalance_after = await web3.eth.getBalance(accounts[0]);
    let contractBalance = await web3.eth.getBalance(instance.address);
    assert(ownerBalance_before < ownnerBalance_after && contractBalance == 0);
  });
});
1 Like

Value Assignment:

bit by bit, but i did it

  it("should be withdraw only by onwer", async function(){
    let instance = await People.new();
    await instance.createPerson("Anna", 65, 190, {from: accounts[1], value: web3.utils.toWei("1", "ether")});
    await truffleAssert.passes(instance.withdrawAll({from: accounts[0]}));
  });
  it("Shouldn't be withdraw by a non-owner",async function(){
    let instance = await People.new();
    await instance.createPerson("Anna", 65, 190, {from: accounts[1], value: web3.utils.toWei("1", "ether")});
    await truffleAssert.fails(instance.withdrawAll({from: accounts[1]}), truffleAssert.ErrorType.REVERT);
  });
  it("Should reset balance to zero after withdrawal", async function(){
    console.log();
    let instance = await People.new();
    await instance.createPerson("Anna", 65, 190, {from: accounts[1], value: web3.utils.toWei("1", "ether")});
    await instance.withdrawAll();
    let balance = await instance.balance(); // contract's balance
    let balanceValue = parseFloat(balance) ;
    console.log("       * Contract's balance: ", balanceValue);
    let balanceReal = await web3.eth.getBalance(instance.address);  // address balance
    console.log("       * Address balance:    ", balanceReal);
    assert(balanceValue == web3.utils.toWei("0","ether") && balanceValue == balanceReal);
  });
  it("Should increase owner's contract balance after withdrawal", async function(){
    console.log();
    let instance = await People.new();
    await instance.createPerson("Anna", 65, 190, {from: accounts[1], value: web3.utils.toWei("1", "ether")});
    let balanceStart = parseFloat(await web3.eth.getBalance(accounts[0]));
    console.log("       * Current Balance Start: ", balanceStart);
    await instance.withdrawAll();
    let balanceEnd = parseFloat(await web3.eth.getBalance(accounts[0]));
    console.log("       * Current Balance End:   ", balanceEnd);
    assert(balanceStart < balanceEnd, "Owners balance was updated (decreased)");
  });

image

1 Like