Skip to content

Instantly share code, notes, and snippets.

@zachlysobey
Last active January 22, 2019 18:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zachlysobey/f3191b3852ac50d40499befe801dae49 to your computer and use it in GitHub Desktop.
Save zachlysobey/f3191b3852ac50d40499befe801dae49 to your computer and use it in GitHub Desktop.
Solidity Testing Patterns
class AbiHelper {
constructor (Contract) {
this._abi = Contract.toJSON().abi
}
abi() {
return this._abi
}
publicMethodNames() {
return this.publicMethods().map(x => x.name)
}
publicMethods() {
return this._abi.filter(x => x.type === 'function')
}
}
module.exports = {
AbiHelper,
}
/**
* utility for creating a functino which will deploy the
* named contract with overridable defaults
* @param name the contract name
* @param defaults map of constructor param names to default values to pass
* @returns Function(overrides)
*/
function buildContractDeployer (name, defaults) {
const Contract = artifacts.require(name)
const { abi } = Contract.toJSON()
const constructorAbi = abi.find(x => x.type === 'constructor')
const constructorInputs = constructorAbi.inputs
return async (overrides = {}) => {
const args = constructorInputs.map(({ name }) => {
const arg = typeof overrides[name] !== 'undefined'
? overrides[name]
: defaults[name]
if (typeof arg === 'undefined') {
throw new Error(`no arg defined for ${name}`)
}
return arg
})
return Contract.new(...args)
}
}
/**
* Usage Example:
*/
const deployMyContract = buildContractDeployer('MyContract', {
name: 'TestMyContract',
symbol: 'TMC',
decimals: '18',
})
contract('MyContract', function() {
it('instantiates a contract with defaults', async () => {
const instance = await deployMyContract()
expect(instance).to.exist
})
it('instantiates a contract with an override', async () => {
const instance = await deployMyContract({ symbol: 'SYM' })
expect(await await instance.name()).to.equal('TestMyContract')
expect(await await instance.symbol()).to.equal('SYM')
expect(await await instance.decimals()).to.equal(18)
})
})
contract('MyContract', (accounts) => {
it('demonstrates naming accounts', async () => {
const [owner, nonOwner] = accounts
const [alice, bob] = accounts
const [contractDeployer, minterRole, endUser] = accounts
})
})
contract('MyContract', () => {
it('tests that a transaction reverts', async () => {
const instance = await MyContract.new()
const txPromise = instance.callThatRejects()
await expect(txPromise).to.be.rejectedWith(
'VM Exception while processing transaction: revert'
)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment