Writing Truffle tests with async/await

The documentation and sample projects with Truffle use promise chaining to write the test code.  As someone from the C# world, coming into the JS world it was getting really confusing to keep track (as well as all the variables I’d have to declare outside of the promise chain to use later).

I did a bit of research and found a way to do async/await in Truffle. I have put up a small simple repo by taking the truffle init project sample, and then doing a straight 1:1 conversion of their promise chaining tests over to the async/await format to help illustrate the difference. I really like the async/await version, as it is cleaner to read and much more compact (as you can see in the before/after screenshots below).

You can find the repo at https://github.com/DavidBurela/TruffleAsyncTests

 

before – promise chaining https://github.com/DavidBurela/TruffleAsyncTests/blob/master/test/metacoin.js

image

 

after – with async/await https://github.com/DavidBurela/TruffleAsyncTests/blob/master/test/asyncmetacoin.js

image

 

A shout out to Jim McDonald for pointing me to his GitHub repo where he had implemented async tests to get me started.

Advertisements

Ethereum DevOps with VSTS – easier now with new Truffle installer + npx

Last year I blogged about my first attempt to wrap a DevOps flow around Ethereum development. Since then there have been improvements in the way that Truffle is deployed with npm, the npx command that comes with npm 5.3.0 onwards, VSTS now supporting hosted Linux build agents, but also my familiarity with Linux, npm & Truffle have increased. I have spent a few weeks in my spare time trying to vastly streamline and simplify getting a basic pipeline going that provides: compilation, testing, migrating of solidity contracts using Truffle.

The steps I outline below will work on any build system, such as Jenkins or Team city that can run bash commands. But I have shown VSTS as that is what I am most familiar with.

clip_image001
Screenshot of the final result, with VTSTS showing Truffle test results for each build.

A video where I walk through the entire process end to end.

Example configured project

I have created a repository in GitHub where I have done the below steps. So if you want to just clone it and try it out on your own build server, that will make it easier for you

https://github.com/DavidBurela/truffledevops

1. Configure npm development packages for your Truffle project

Add Truffle, TestRPC, Mocha & Mocha JUnit plugin as DevDependencies in your packages.json. This will allow the build server to later install these packages and then execute Truffle commands.


# don't run npm init if your project already has a packages.json
npm init -y
npm install truffle ethereumjs-testrpc mocha mocha-junit-reporter --save-dev

2. Configure truffle.js

There are 2 main things that are being added here:

a) TestRPC provider as a new network, with the require at the top of the file to import it. This will allow Truffle to just spin up TestRPC just for the context of the command, and then get thrown away once the command finishes. Great for testing migrations, or running tests, and then throwing it all away.

b) Mocha test reporter definition. We leave it as “spec” so that it will display the results in the console window while developing locally. Later on the build server we can change the reporter to JUnit, and the output file is already specified here ready for that.


var TestRPC = require("ethereumjs-testrpc");

module.exports = {
networks: {
development: {
host: "localhost",
port: 8545,
network_id: "*" // Match any network id
},

// add a new network definition that will self host TestRPC
localtest: {
provider: TestRPC.provider(),
network_id:"*"
}
},

// add a section for mocha defaults
mocha: {
reporter: "spec",
reporterOptions: {
mochaFile: 'TEST-truffle.xml'
}
}
};

image

3. Build server settings

This screenshot shows what the end result looks like. It can be summarised as: get the tests, install the npm packages, configure any environment variables, run the Truffle commands, and collect the test results.

clip_image003

a) Get sources

Define where your code is sitting (e.g. VSTS, Github, Bitbucket, etc.)
clip_image004

b) npm install

The default npm install task. Will look in packages.json and install our dev dependencies so later we can run Truffle, TestRPC, etc.
clip_image005

c) Shell script – environment details and config

An inline script that spits out useful environment information to help debug if things go wrong.

It also importantly replaces the line in our truffle.js to change the test reporter to the console UI, to output the results into a .xml file in JUnit format


# output version details for debugging
node -v
npm -v
npx truffle version

# string replace the mocha reporter to junit output
sed -i -e 's/reporter: "spec"/reporter: "mocha-junit-reporter"/g' truffle.js

clip_image006

d) Shell script – truffle commands

Inline script that executes the local version of Truffle with npx. I like have all 3 lines, so if something breaks we can see where it happened.


# check the contracts compile
npx truffle compile

# check migrations execute without issue
npx truffle migrate --network localtest

# run unit tests
npx truffle test --network localtest

clip_image007

e) Publish test results

Default task. I have left the defaults
clip_image008

New releases of Truffle & TestRPC. Now easier to install.

I have mentioned previously that Truffle & TestRPC are my development tools of choice for Ethereum based development.

truffle logo

It is exciting to see that there have been new releases of both Truffle & TestRPC. I have been hanging out in the Truffle Gitter channel, and been fielding lots of questions about installation issues on Windows. As Tim has previously blogged, there have been a number of issues with installation. The installation issues were mostly due to compiling C based libraries, and requiring a number of build tools on the local machine. These issues have now been removed as Truffle & TestRPC are both now built, and then released as a completely pre-packaged release. This also means that installation times have dropped from 10 minutes, to 10 seconds! (Which means I’ll need to go back and update some of my old tutorials )

 

Truffle

Highlights: More reliable installation. Makes it easier for everyone to jump in and start playing!

https://github.com/trufflesuite/truffle/releases/tag/v3.3.0

TestRPC

Highlights: Installs quicker. Reduced memory consumption. Ability to persist the blockchain to disk, meaning you can suspend and then resume if you like  (I’ll still be using it mostly as a throw away in memory style dev environment).

https://github.com/ethereumjs/testrpc/releases/tag/v4.0.0

Whats next?

I’ve been waiting in suspense for these updated installers to drop for many months now. There have been a couple of projects on my backlog that had been blocked until this came out. A short list of what I’ll be working on in the near term are:

Reghack “Down Under” event roundup

Reghack was a 3 day hackfest that ran in Melbourne, Australia https://reghack.org/

The problem statement asked:
Do you have an interest in helping solve regulatory issues in the Financial Services and the Energy Sector in Australia?
How do we use RegTech to make regulatory compliance a strategic advantage that’s a win for the regulator, market participants and the consumer?

The focus of the event was to try and invigorate local innovation in the energy & financial services sectors, by allowing people to come together and explore how Blockchain could be utilised in these areas. The event was the brainchild of Chami Akmeemana https://www.linkedin.com/in/chami1/ who is a director of ConsenSys, the largest Blockchain focused consulting company in the world. Chami came to Melbourne and asked for local community support to help him organise and run the event. I was lucky enough to be tapped by Chami and invited to assist. I helped out by providing sponsorship for the meals via Microsoft, and delivered training to help upskill the community beforehand (more about that below).

The event had around 90 participants, with many more volunteers on the day. In the end 14 teams pitched their ideas which ranged from energy trading systems, ways to authenticate documents, to ways to eliminate GST during B2B transactions.
A big thanks to Chami for organising it all, and to all the volunteers that helped make the event a resounding success.

20170512_204517

Note: The roundup of the teams pitches are at the bottom of this post.

Continue reading

How to install Truffle & TestRPC on Ubuntu or Windows 10 with “Windows subsystem for Linux”

I previously wrote how you can install Truffle & TestRPC on a windows machine, by using the Windows installers for Node & npm.
However I have found it is a much nicer experience to use the Windows Subsystem for Linux which provides a native Ubuntu shell with bash, which allows me to run all the Linux tools natively without issues. These install steps will work on an Ubuntu machine as well.

Prerequisite if running on Windows

  1. Enable Windows subsystem for Linux.
    Follow this short guide on how to enable it https://msdn.microsoft.com/en-us/commandline/wsl/install_guide
    image
  2. After following the steps in the guide above. Simply start the Ubuntu bash shell
    image

Install steps

# Takes a clean Ubuntu image, up to being Ethereum dev ready.
# installing npm from official repo
https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions as Ubuntu default apt-get has a very old version (NodeJS v4.1)
curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash –
sudo apt-get update -y && sudo apt-get upgrade -y

# install system basics
sudo apt-get install -y build-essential nodejs

# upgrade node/npm/npx and then install dev tools
sudo npx dist-upgrade
sudo npm install -g ethereumjs-testrpc truffle

# fix up permission issues. npm5 creates these as root, so user can’t modify by default
sudo chown -R $(whoami) ~/.npm
sudo chown -R $USER:$(id -gn $USER) ~/.config

now you should be able to create a folder, go into it and run `truffle init` to create a new project template.

imageimage

Additional things to do

Now that your machine has it installed, I recommend you follow my other guide to get Visual Studio code configured for Truffle development.

Videos and notes of my Blockchain presentations at Microsoft Ignite Australia

As I previously mentioned, I was scheduled to deliver 2 talks at Ignite Australia. The talks both went well, and I’ve been getting a lot of great feedback about them. Now that the dust has settled and the content is all online I thought I should share the media to make it easier for other to watch and learn from them.

Saved image from Tweetium

Blockchain 101 & Azure Blockchain as a Service

Chris Zhong & I covered off an introduction to Blockchain 1.0 & 2.0. Covering off how Blockchain 1.0 technologies like Bitcoin are able to store state. But the rise of Blockchain 2.0 technologies like Ethereum, is what has gotten people’s attention as they are able to store state and embedded logic within “smart contracts”. I had heaps of fun with this session as I spent days putting together a scenario showing how multiple DApps (Decentralised Apps) could be linked together via on chain smart contracts, to build up an ecosystem of Blockchain apps that are able to leverage each other seamlessly.
A thanks to Chris Zhong for putting together and presenting the section on “Azure Blockchain as a Service”.

image

image

 

Blockchain Development on Azure Blockchain as a Service

Going into Blockchain development blind can leave you stumbling around on the net not knowing where to even begin to look. The purpose of this session was to take the knowledge I’ve picked up from doing Blockchain projects, and the months and months I’ve spent replacing and refining tools down to the easiest development experience, and distil it down for the audience. It was an awareness session “these are all the tools, here is why I use these ones, this is how you create a skeleton of a Blockchain app, interact with it, test it, etc.”. It wasn’t as clean as I would have liked, and subsequent repeat presentations have been smoother, but it is still a great starting point.

RegHack Downunder–Regulatory Blockchain hackfest in Melbourne Australia May 12-14

UPDATE: The event has finished, I have an event writeup available  https://davidburela.wordpress.com/2017/05/15/reghack-down-under-event-roundup/

RegHack details

I’m helping support a 3 day Blockchain regulatory hackfest here in Melbourne Australia on 12-14 of May https://reghack.org/
It is for companies working in the financial & energy sectors. There will be officials from government and regulators there able to answer questions on the day, allowing companies to quickly test out ideas during the event. We are inviting all companies that may have an interest in it (such as banks, financial institutions, energy distributors).

We encourage anyone interested to register and attend. You can either form a team with your workmates before you come along, or join up with people on the day to form a team.

Training events

Throughout the 3 weeks before the event, we’ll be running a series of 3 sessions in conjunction with the Ethereum Melbourne Meetup.

Week 1:

Thursday 27 April
What is a hackfest, how best to prepare for it https://www.meetup.com/Ethereum-Melbourne/events/239404213/

Week 2:

Tuesday 2nd May
Introduction to Ethereum workshop https://www.meetup.com/Ethereum-Melbourne/events/239097996/

Wednesday 3rd May
This is the session I will be running. Showing how to set up your dev environments with Truffle, TestRPC & an Azure BaaS Ethereum testnet https://www.meetup.com/Ethereum-Melbourne/events/239404235/
Week 3:

Wed 10 May
solidity master class https://www.meetup.com/Ethereum-Melbourne/events/239404253/