+ - 0:00:00
Notes for current slide
Notes for next slide
  • In our previous session, we learnt how to write smart contracts using solidity as well as explored using smart contract development tools
  • One of those tools was truffle, which we used to compile and deploy our smart contracts with
  • Tonight we will continue using truffle, but this time we'll focus on using it to write tests for our smart Contracts

DApps Dev Club S01E05 deck QR code

scan me! - you'll need to follow the links

bit.do/dadc-s01e05

1 / 72

Decentralised Applications Development Club

DApps Dev Club

Testing Smart Contracts

23/04/2019 30/04/2019

2 / 72
  • In our previous session, we learnt how to write smart contracts using solidity as well as explored using smart contract development tools
  • One of those tools was truffle, which we used to compile and deploy our smart contracts with
  • Tonight we will continue using truffle, but this time we'll focus on using it to write tests for our smart Contracts

DApps Dev Club S01E05 deck QR code

scan me! - you'll need to follow the links

bit.do/dadc-s01e05

3 / 72
  • This is where you can find our discord link. It's on our homepage - dappsdev.org - near the top, before the blog posts

Install these!

Note: Make sure you don't have Python 3 on your PATH

$ python --version
Python 3.6.5 :: Anaconda, Inc. # node-gyp may fail
5 / 72
  • In the info page about this session, I asked all of you to install a bunch of stuff
  • and here's that list again
  • We should have this all installed on our computers already, from the previous session
  • can I have a show of hands, for how many have actually installed all of these things?
  • ok so for the rest, did any of you encounter any issues while trying to install it?
  • and if you haven't quite gotten around to it yet, well let's get that out of the way before we start, while we're waiting for people to trickle in, might as well put the time to good use
  • ok so if anyone here has had trouble installing node, solc, truffle, or ganache, please raise your hands, and I'll try my best to help you to troubleshoot in the next few minutes
  • Also, a quick note, for some of you who had trouble from the previous session, we discovered that if you had python 3 on your path instead of python 2, as shown here, you might not be able to install truffle or some of the other tools, because node-gyp assumes python 2 only.
  • Also, for those of you who are joining us in our DApps Dev Club session for the very first time - welcome!
  • We are a technical book club, and we run our sessions twice per month - and a book club implies a book, well this is the book
  • Mastering Ethereum by Andreas Antonopoulos & Gavin Wood
  • This is the line up for tonight's session
  • We'll start off by introducing our partners, and ourselves
  • Then do a quick recap of the previous session
  • Then we'll cover mocha which is a Javascript test runner/ framework - it is general purpose, and has nothing to do with smart contracts
  • Then we'll go over to truffle which has its own test runner, which, you'll see soon, wraps around mocha - so it's mostly the same - but adds a few extra things that make it convenient to test smart contracts with
    • We'll use truffle to test smart contracts in a few commonly encountered different ways.
  • And finally we'll wrap up with a recap, plus information about our next session

Partners

8 / 72
  • Before we begin, let us thank all of our partners who made this session possible

Partners

LLI

Lifelong Learning Institute

9 / 72
  • In our previous session, we mentioned that the Lifelong Learning Institute is partnering with us. And we even had Dr Leong, who is the Principal Manager at LLI, to tell us a bit about what they do, their Learning Circles program, and SkillsFuture.

Partners

LLI

10 / 72
  • In our previous session, we mentioned that the Lifelong Learning Institute is partnering with us. And we even had Dr Leong, who is the Principal Manager at LLI, to tell us a bit about what they do, their Learning Circles program, and SkillsFuture.

Partners

LLI

Chainstack

Chainstack

Acronis

11 / 72

Partners

LLI

Chainstack

BitTemple

BitTemple

12 / 72

Partners

LLI

Chainstack

BitTemple

NBC'19

National Blockchain Challenge '19

13 / 72

Partners

LLI

Chainstack

BitTemple

NBC'19

Spartan

Spartan Group

14 / 72

Partners

LLI

Chainstack

BitTemple

NBC'19

Spartan

StartupToken

StartupToken meetup

15 / 72

Partners

LLI

Chainstack

BitTemple

NBC'19

Spartan

StartupToken

EngineersSG

Engineers.SG

16 / 72

Partners

LLI

Chainstack

BitTemple

NBC'19

Spartan

StartupToken

EngineersSG

CryptoJobsList

CryptoJobsList

17 / 72

Intro

18 / 72
  • Before we go into the the topics, for the benefit of those who are attending the their first session today

Intro

DADC

DApps Dev Club

  • Decentralised Applications Development Club
  • Format inspired by the technical book club from SingaporeJS
19 / 72
  • The DApps Dev Club meets twice a month, and this is our 4th session
    • In each session, we plan to discuss about 3 or four different topics, selected from the Mastering Ethereum book
  • We are a technical book club, so in each session, when we meet up together, we'll be discussing select parts from this book, plus working through things together
    • I should mention that while this is not a common format, it isn't completely new - in fact it is inspired by the book club that the SingaporeJS meetup runs
    • In the first couple of sessions, it was mostly me talking, but the rest of the sessions are going to be hands-on

Let me hit you with some knowledge

20 / 72

-

Intro

DADC/2

21 / 72
  • The nexus for all the club happenings are on this website, dappsdev.org
    • The main thing to look out for on the website are the news feed, which you can subscribe to via the RSS feed, or check back on manually
    • The other thing to look out for on the website is the sessions page, which is a calendar for all of the events
  • Apart from meeting in person, we can also have discussions online
    • We have a discord server for that, and you can join using the link found on our website
  • As mentioned earlier, the book which we're covering together is Mastering Ethereum, which is written by by Andreas Antonopoulos & Gavin Wood
  • Andreas Antonopoulos is the author of the Mastering Bitcoin book, and Gavin wrote most of the initial implementation of Ethereum itself.

Intro

DADC

Book

Kenneth

  • CTO of Baypay
  • Also runs the Blockchain&DApps meetup

Kenneth Hu

23 / 72
  • Kenneth is the CTO of Baypay
  • He knows the Ethereum stack inside out
  • He also runs a blockchain events across Taiwan, Malaysia, and Singapore

Intro

DADC

Book

Kenneth

Brendan

  • Started DApps Dev Club
  • NodeJS developer
24 / 72
  • I'm Brendan, and I work as a software engineer
  • Spend most of my time doing NodeJs
  • Met Kenneth through the EthSG hackathon last year
  • We decided to collaborate and create a series of educational blockchain meetups, and here we are

Intro

DADC

Book

Kenneth

Brendan

You!

  • No blockchain knowledge required
  • No solidity or smart contract knowledge required
  • Basic Javascript needed in session #05
25 / 72
  • So, how about you? These sessions are designed with a particular audience in mind.
  • If you know nothing about blockchain, or about smart contracts, that's perfect
  • However, if you don't know some basic JS, you'll need to pick that up to follow along in the later sessions.
    • I've already posted some resources that you can use to learn JS - it's in the latest post on dappsdev.org now, or come talk to me, or ask around in our discord
  • Bring your laptops to the sessions, as you'll be able to participate in the hands on parts of the sessions

wen ico? wen moon?

Ya Basic - The Good Place

26 / 72
  • I think most of us by now have encountered someone on a Telegram group, who joins, and within seconds says "wen ico? wen moon?" (with that exact spelling)
  • If you're that person, these sessions are not for you. We're not going to be building an ERC20, or learning how to trade or speculate on them.
  • What we're about here is focussed on developing decentralised applications
  • This is a great show by the way, it takes real skill to take a subject matter that dry and make it entertaining

Intro

DADC

Book

Kenneth

Brendan

You!

Noticed

27 / 72
  • Session #02 was held at Chainstack as well, and they tweeted about it
  • And it looks like DApps Dev Club has been noticed by an author of the book we're using as our reference material for our sessions!

/intro

28 / 72
  • Q&A
  • (check if any of the sponsors have arrived after their slot, backtrack to them)
  • (attendance)

Recap #04

29 / 72
  • Let's recap what we did in the previous session

Recap #04

Tools

  • Installed and used new tools:
    • solc
    • ganache
    • truffle
30 / 72
  • ...

Recap #04

Tools

Soldiity

  • Solidity-by-feature
    • contract structure
    • primitive types
    • dynamic types
    • functions
    • function modifiers
    • events
31 / 72
  • ...

/recap

32 / 72
  • Q&A
  • ...

Mocha

33 / 72
  • OK, so now we are going to start this session proper
  • And we're going to do that by introducing mocha
  • This section will have absolutely nothing to do with smart contracts, EVM, etc
  • Just pure javascript
  • Once we've covered the basics of Mocha on it's own, we'll then transition to using mocha within truffle, and that's when we start using web3.js, interacting with smart contracts, etc
  • This session has a record number of hands-on parts - six in total, which is two more than we've done in any other session - so depending on how we go, we might not get through all of them
  • With that in mind, I have enlisted the help of a few generous volunteers who are familiar/ comfortable with Javascript, and have volunteered to help people in tonight's session with stuff when we get stuck
    • Can we have a show of hands please!
  • We will not be teaching Javascript itself - the programming language that is - in these sessions, so if you're not that familiar with it, or get stuck at any point, please don't be afraid to ask for help

Mocha

What

  • A test runner for Javascript
  • Can execute "spec" files either in browser, or in NodeJs
    • We'll be using NodeJs only
  • Executes tests, outputs reports
34 / 72
  • Could I have a show of hands who here has written some implementation, and also written a specification that tests that implementation before? (in any language)
  • How about those who have done that for Javascript specifically? (can I have another show of hands)
  • Which test runners did you use? (popular responses expected: mocha, jasmine, jest)
  • So some of you have written tests before, and some of you have even used mocha before, so you may want to spend the time during this next section helping out the people around you
  • Let's now define what a test runner is

Mocha

What

Impl

  • Implementation is code that you write
  • Executes when the program is being used
  • You are implementing the features of your software
  • impl
35 / 72
  • Next, let's define some terminology which we'll be running into quite a bit
  • First up we have "implementation"

Mocha

What

Impl

Spec

  • Specification is also code that you write
  • Does not execute when the program is being used
  • Instead it executes the implementation
  • You are specifying the features of your software
  • spec
36 / 72
  • and we also have "specification"

Mocha

What

Impl

Spec

Runner

  • A test runner is a developer tool
  • runner executes specification executes implementation
  • runner observes behaviour produces report
  • Mocha is a test runner
37 / 72
  • and we also have the "runner", also known as the "test framework"
  • mocha executes your specification code, which in turn executes your implementation in specific ways
  • while this is happening, mocha is set up such that it observes the behaviour in certain ways
    • mainly: did the test crash? did any assertions fail? what was the return value?
  • and once all of the specifications have completed running, or they have timed out and mocha decides to terminate them, it produces a report, which summarises all of the results from the specifications that you have written
    • generally this will be
    • summary statistics of how many tests there were in total, and how many passed or failed
    • plus: detailed output about any of the tests that have failed
  • mocha has a plugin or addons system, where you can install your own custom reporter that do things differently from the default.

Mocha

What

Impl

Spec

Runner

Other

38 / 72
  • When you talk abut testing, there are also these other terms that come up quite frequently, and I would be in remiss not to mention them at least
  • However, for the scope of our session tonight, we don't need to care about these
  • In lieu of that, H/W, for those who are interested in going deeper, I have included some links for further reading

Mocha

What

Impl

Spec

Runner

Other

Hands-on

39 / 72
  • alright it is time for our first hands-on part for tonight's session!
  • before we start though, quick show of hands, who here has completed the mocha getting started guide? (use this to gauge how fast to go)

/mocha

40 / 72
  • OK, so now we're done with our very quick introduction to testing vanilla javascript using mocha. Just a quick recap:
  • we created a new NodeJs project, and pushed it onto github. BTW all of you should copy the project URL and paste it into the #sessions channel of our chat group! why not do that now?
  • next we wrote an implementation file in Javascript, for a very simple add function
  • next we wrote the specification file, also in Javascript, using describe and it blocks provided by mocha, and assert from NodeJs core.
  • then we ran the tests using mocha
  • then we intentionally "broke" our code in various ways, and discussed the implementation and specification correctness quadrants
  • some of us who happened to finish faster than the rest got to explore property based testing. those of you who didn't get to that, not to worry! we aren't going to need that at all for the rest of tonight's session - property based testing was really just to keep the fast ones from getting too bored! 😉
  • Q&A

Data Storage

41 / 72
  • Alright, let's move on to the next section where we are going to get back to DApp development. This is where we'll start putting our new or perhaps refreshed mocha skills to use, but to test out smart contracts that are written in Solidity, instead of testing our vanilla Javascript, instead!
  • truffle has its own test runner

42 / 72
  • Who here loves a good joke about recursion?
  • I put a can in yo' can!

Data Storage

Macro/1

  • truffle has its own test runner
  • this test runner is
    • 99% mocha
    • 1% things that are specific to truffle
43 / 72
  • Before we get into that, let's take a moment to know what's in store
  • Firstly we won't be using mocha as the test runner, we'll be using truffle's own test runner instead
  • But truffle's test runner is almost 100% the same as mocha - in fact it really is a wrapper around mocha - there are just a few tiny things that are different which you'll need to know and we will get to later

Data Storage

Macro/2

  • Tasks:
    • test data storage
    • test state transitions
    • test events
    • mock the smart contract
44 / 72
  • And here are the various things that we will be doing with our tests, which are specific to smart contracts
  • Note that there are a few other types of things that you can test in addition to this, but these are the most common categories of things that need to be done in tests for smart contracts, and therefore the most useful ones to learn!

Data Storage

Macro

Set up

45 / 72
  • Here we'll be setting up our a truffle project for testing
  • We'll need to grab a copy of the truffle project that you would have created from the previous session, and use that as the starting point
  • We'll also need a copy of ganache set up and running as well
  • Let's get cracking!

Data Storage

Macro

Set up

46 / 72
  • (hopefully the previous one was very quick)
  • Now we're going to do the proper hands-on for this section which is to test data storage
  • Here we'll be writing some very simple tests, and all they do is perform assertions on the initial stae of the smart contract
  • Let's get cracking!

/data-storage

47 / 72
  • OK, so now we have our very first test running
  • Q&A

State Machines

48 / 72
  • The next thing we'd like to cover are state machines and state transitions

State Machines

FSM

A finite-state machine (FSM) or finite-state automaton (FSA, plural: automata), finite automaton, or simply a state machine, is a mathematical model of computation. It is an abstract machine that can be in exactly one of a finite number of states at any given time. The FSM can change from one state to another in response to some external inputs; the change from one state to another is called a transition. An FSM is defined by a list of its states, its initial state, and the conditions for each transition.

— Wikipedia

49 / 72
  • Here's the definition of a state machine, taken off Wikipedia
  • There's a lot of theory there, but the main take away is that in the context of software development, in some cases, you can think of a program as a series of states, and the program's implementation governs how it moves from one state to another.

State Machines

FSM

Transitions

A Scilla smart contract (and in general most smart contracts that you see today) are stateful systems. This basically means that a smart contract at any point of time can be said to be in a particular "state". This "state" for instance can be a set of variables (and its current value) or say map (in the case of ERC20 token contract) that stores which user owns how many tokens. A state transition is a function that allows users to change the state of the contract. For instance, the transfer state transition function will allow users to transfer tokens from one user to another and hence changing the map.

— Amrit Kumar

50 / 72
  • When a state machine moves from state to another, that is called a state transition
  • There is another crypto network (not Ethereum) called Zilliqa, which is developed by a company here is Singapore, and they have their own smart contract language called Scilla.
  • So, roughly speaking, Scilla is to Zilliqa as Solidity is to Ethereum
  • The interesting thing about Scilla is that it explicitly makes you write their smart contracts as state machines, and instead of calling their functions functions, they call them transitions, because that's what they really are in that context.
  • I asked Amrit Kumar who is one of the co-authors of Scilla, and also one of the lead developers at Zilliqa, to define a state transition, and here we have it

State Machines

FSM

Transitions

Key Q's

  • Can you model your smart contract as a state machine?
  • What are the state transitions that you need in your smart contract?
  • What is the connection to event logs?
51 / 72
  • Now let's answer these questions:
  • Can you model your smart contract as a state machine?
    • Yes you can, but only if you keep that in mind, or as a goal, while writing your smart contract
    • The analogy I'll offer is perhaps from older programming languages such as BASIC and such which had GOTO statements. You always had the option of using GOTOs, but some software engineers thought that they were something to be avoided, and wrote functionally equivalent code without GOTO statements.
  • What are the state transitions that you need in your smart contract?
    • Think about what data your smart contract stores. Think about what cause that data to be changed Think about what thing need to be checked before allowing those changes. When you know all of those, you can model your states and your state transitions.
  • What is the connection to event logs?
    • There is a theory that whenever you change some state, you store a log of those changes, containing enough info to be able to rebuild the entire state from scratch.
    • Recall in session #02 where we talked about distributed computing and how databases use transaction logs to restore known state with consensus when one or more nodes have failed.

State Machines

FSM

Transitions

Key Q's

Hands-on

52 / 72
  • Now it's time for another hands on
  • We'll be performing some state transitions, and then checking that they have indeed done what we expected them to do

/state-machines

53 / 72
  • So let's do a quick recap:
  • First we discussed what state machines and state transitions were, and looked at how Solidity functions can be modelled as, or thought of as, state transitions
  • Next we wrote a test that invokes the addCar() function, and asserted that it did indeed add a new Car object, and that the right values were stored in the contract
  • Then we took a look at a few different approaches towards asserting the return value of a function that performs a state transition
  • Finally we explored writing more than one test, and hopefully discovered the truffle clean room environment, and learned about how to group/ structure tests within a specification file
  • Q&A

Events

54 / 72
  • Next up we have events

55 / 72

Events

Logs

  • Events -> Structured Logs
  • On an immutable ledger
56 / 72
  • In solidity when you emit an event, you are adding a structured log to an immutable ledger (the blockchain)
  • In a centralised app server, you might be accustomed to performing console.log(), or otherwise output to STDOUT, and you pipe that to a file on disk, and look through that when you wish to discover how your server has (mis)behaved
  • If you know that a human is the only one who will be reading the logs, that's fine, however, if you want your logs to be machine-parseable too, instead of writing arbitrary stuff into your log files, every line that you output should be in some standardised format. For example, a common one that I see in NodeJs servers is JSON objects that are serialised one per line
  • Ethereum makes use of structured logs as well, but instead of outputting to STDOUT and piping that into a file, it stores them on an immutable ledger that is distributed amongst all the nodes running in the network.
  • Read the linked section from the Mastering Ethereum book, in chapter 7, as this goes into more implementation-level details about this
  • Time to move on to our next hands-on part, where we're going to test events

/events

58 / 72
  • Recap:
  • we introduced, and made use of, a new mocha feature, which is the before block, in order to set up the state of the contract prior to running tests
  • this time we added both a "happy path" test, and a failure scenario test.
  • Q&A

Mocking

59 / 72
  • Next we'll take a look at mocks for Solidity

Mocking

What

  • Is not make fun of type
  • Is the imitate type
60 / 72
  • In English, the word mock can mean either to make fun of someone, or to imitate them.
  • In the context of software specification and testing, mocking refers to the latter, to imitate

61 / 72

Mocking

What

Why

  • Test with mostly the same behaviour
62 / 72
  • Why do we need mocks?
  • The key is that we want some part of your software to be tested
  • But... for various reasons that are out of your control, you cannot test test that part of the software directly
  • You have to modify its behaviour is some small and specific way in order for you to be able to write and execute the tests that you need
  • This is where mocks come in, you create a new version of that piece of software that behaves as it were an exact copy, with the exception of the bits that need to be different

Mocking

What

Why

Hands-on

63 / 72
  • so now it's time for our next hands-on where we're going to create mock for our Cars smart contract

/mocking

64 / 72
  • Recap:
  • We modified the implementation of smart contract to add a new rule, which enforces that cars are not allowed to honk at certain times of the day.
  • Then we ran our tests and found out that the test now pass or fail, depending on the time of day it happens to be IRL when the tests are run
    • This is actually a very common scenario for introducing mocks to test specifications, not just in smart contracts
  • Then we wrote a mocked version of our cars smart contract, which allows the test to override the IRL value, and instead set the time of the day that will be used by the test
  • Then we modified the tests to run against the mocked version of the Cars contract instead of the regular one.
  • Then we wrote a new test to specifically test the mocked scenario which was a new possible failure scenario
  • Q&A

Next

65 / 72
  • ...

Next

Recap

-

66 / 72

-

Next

Recap

S01E06

67 / 72
  • So our next session will be on the 2nd Tuesday of the month, at Chainstack, check out the details on the sessions page on our website
  • Show the sessions page

Next

Recap

S01E05

Hands-on

68 / 72

-

Next

Recap

S01E05

Hands-on

Setup

69 / 72

-

Next

Recap

S01E05

Hands-on

Setup

Q&A

Questions?

70 / 72
  • Before we wrap up, do you have any questions?
  • Is you think of some questions later, or already have them, but prefer to type instead, head over to our discord, the link is right there!

Thanks!

Lifelong Learning Institute & SkillsFutureSG, Chainstack & Acronis, BitTemple, NBC'19, Spartan, StartupToken, EngineersSG, CryptoJobsList, and Blockchain&DApps

71 / 72

DApps Dev Club

dappsdev.org

72 / 72
  • be sure to check out the sessions page for updates, and join our discord
  • Q&A
  • any other announcements?

Decentralised Applications Development Club

DApps Dev Club

Testing Smart Contracts

23/04/2019 30/04/2019

2 / 72
  • In our previous session, we learnt how to write smart contracts using solidity as well as explored using smart contract development tools
  • One of those tools was truffle, which we used to compile and deploy our smart contracts with
  • Tonight we will continue using truffle, but this time we'll focus on using it to write tests for our smart Contracts
Paused

Help

Keyboard shortcuts

, , Pg Up, k Go to previous slide
, , Pg Dn, Space, j Go to next slide
Home Go to first slide
End Go to last slide
Number + Return Go to specific slide
b / m / f Toggle blackout / mirrored / fullscreen mode
c Clone slideshow
p Toggle presenter mode
t Restart the presentation timer
?, h Toggle this help
Esc Back to slideshow