json-test-runner.ts 1.44 KB
Newer Older
1 2
/* External Imports */
import { ethers } from 'hardhat'
3
import { Contract } from 'ethers'
4

5 6
import { expect } from '../../setup'

7
const bigNumberify = (arr: any[]) => {
8 9
  return arr.map((el: any) => {
    if (typeof el === 'number') {
10
      return ethers.BigNumber.from(el)
11
    } else if (typeof el === 'string' && /^\d+n$/gm.test(el)) {
12
      return ethers.BigNumber.from(el.slice(0, el.length - 1))
13
    } else if (typeof el === 'string' && el.length > 2 && el.startsWith('0x')) {
14
      return ethers.BigNumber.from(el.toLowerCase())
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
    } else if (Array.isArray(el)) {
      return bigNumberify(el)
    } else {
      return el
    }
  })
}

export const runJsonTest = (contractName: string, json: any): void => {
  let contract: Contract
  before(async () => {
    contract = await (await ethers.getContractFactory(contractName)).deploy()
  })

  for (const [functionName, functionTests] of Object.entries(json)) {
    describe(functionName, () => {
      for (const [key, test] of Object.entries(functionTests)) {
        it(`should run test: ${key}`, async () => {
          if (test.revert) {
            await expect(contract.functions[functionName](...test.in)).to.be
              .reverted
          } else {
37 38 39 40
            const result = await contract.functions[functionName](...test.in)
            expect(JSON.stringify(bigNumberify(result))).to.deep.equal(
              JSON.stringify(bigNumberify(test.out))
            )
41 42 43 44 45 46
          }
        })
      }
    })
  }
}