Commit 28773548 authored by aniket-engg's avatar aniket-engg

linting for remix-tests fixed

parent 84d0bac2
{ {
"extends": "../../.eslintrc", "extends": "../../.eslintrc",
"rules": { "rules": {
"@typescript-eslint/no-explicit-any": "off", "dot-notation": "off",
"@typescript-eslint/no-var-requires": "off", "no-unused-vars": "off"
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"@typescript-eslint/ban-ts-comment": "off"
}, },
"env": { "env": {
"browser": true, "browser": true,
......
...@@ -2,10 +2,10 @@ import fs from './fileSystem' ...@@ -2,10 +2,10 @@ import fs from './fileSystem'
import async from 'async' import async from 'async'
import path from 'path' import path from 'path'
import Log from './logger' import Log from './logger'
const logger = new Log()
const log = logger.logger
import { Compiler as RemixCompiler } from '@remix-project/remix-solidity' import { Compiler as RemixCompiler } from '@remix-project/remix-solidity'
import { SrcIfc, CompilerConfiguration, CompilationErrors } from './types' import { SrcIfc, CompilerConfiguration, CompilationErrors } from './types'
const logger = new Log()
const log = logger.logger
function regexIndexOf (inputString: string, regex: RegExp, startpos = 0) { function regexIndexOf (inputString: string, regex: RegExp, startpos = 0) {
const indexOf = inputString.substring(startpos).search(regex) const indexOf = inputString.substring(startpos).search(regex)
...@@ -29,7 +29,7 @@ function writeTestAccountsContract (accounts: string[]) { ...@@ -29,7 +29,7 @@ function writeTestAccountsContract (accounts: string[]) {
* @param path file path to check * @param path file path to check
*/ */
function isRemixTestFile(path: string) { function isRemixTestFile (path: string) {
return ['tests.sol', 'remix_tests.sol', 'remix_accounts.sol'].some(name => path.includes(name)) return ['tests.sol', 'remix_tests.sol', 'remix_accounts.sol'].some(name => path.includes(name))
} }
...@@ -44,14 +44,13 @@ function isRemixTestFile(path: string) { ...@@ -44,14 +44,13 @@ function isRemixTestFile(path: string) {
* @param isRoot True, If file is a root test contract file which is getting processed, not an imported file * @param isRoot True, If file is a root test contract file which is getting processed, not an imported file
*/ */
function processFile(filePath: string, sources: SrcIfc, isRoot = false) { function processFile (filePath: string, sources: SrcIfc, isRoot = false) {
const importRegEx = /import ['"](.+?)['"];/g const importRegEx = /import ['"](.+?)['"];/g
let group: RegExpExecArray| null = null let group: RegExpExecArray| null = null
const isFileAlreadyInSources: boolean = Object.keys(sources).includes(filePath) const isFileAlreadyInSources: boolean = Object.keys(sources).includes(filePath)
// Return if file is a remix test file or already processed // Return if file is a remix test file or already processed
if(isRemixTestFile(filePath) || isFileAlreadyInSources) if (isRemixTestFile(filePath) || isFileAlreadyInSources) { return }
return
let content: string = fs.readFileSync(filePath, { encoding: 'utf-8' }) let content: string = fs.readFileSync(filePath, { encoding: 'utf-8' })
const testFileImportRegEx = /^(import)\s['"](remix_tests.sol|tests.sol)['"];/gm const testFileImportRegEx = /^(import)\s['"](remix_tests.sol|tests.sol)['"];/gm
...@@ -61,7 +60,7 @@ function processFile(filePath: string, sources: SrcIfc, isRoot = false) { ...@@ -61,7 +60,7 @@ function processFile(filePath: string, sources: SrcIfc, isRoot = false) {
const includeTestLibs = '\nimport \'remix_tests.sol\';\n' const includeTestLibs = '\nimport \'remix_tests.sol\';\n'
content = includeTestLibs.concat(content) content = includeTestLibs.concat(content)
} }
sources[filePath] = {content} sources[filePath] = { content }
importRegEx.exec('') // Resetting state of RegEx importRegEx.exec('') // Resetting state of RegEx
// Process each 'import' in file content // Process each 'import' in file content
...@@ -85,7 +84,7 @@ const isBrowser = !(typeof (window) === 'undefined' || userAgent.indexOf(' elect ...@@ -85,7 +84,7 @@ const isBrowser = !(typeof (window) === 'undefined' || userAgent.indexOf(' elect
* TODO: replace this with remix's own compiler code * TODO: replace this with remix's own compiler code
*/ */
export function compileFileOrFiles(filename: string, isDirectory: boolean, opts: any, compilerConfig: CompilerConfiguration, cb): void { export function compileFileOrFiles (filename: string, isDirectory: boolean, opts: any, compilerConfig: CompilerConfiguration, cb): void {
let compiler: any let compiler: any
const accounts: string[] = opts.accounts || [] const accounts: string[] = opts.accounts || []
const sources: SrcIfc = { const sources: SrcIfc = {
...@@ -95,7 +94,7 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts: ...@@ -95,7 +94,7 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts:
} }
const filepath: string = (isDirectory ? filename : path.dirname(filename)) const filepath: string = (isDirectory ? filename : path.dirname(filename))
try { try {
if(!isDirectory && fs.existsSync(filename)) { if (!isDirectory && fs.existsSync(filename)) {
if (filename.split('.').pop() === 'sol') { if (filename.split('.').pop() === 'sol') {
processFile(filename, sources, true) processFile(filename, sources, true)
} else { } else {
...@@ -111,27 +110,25 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts: ...@@ -111,27 +110,25 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts:
processFile(foundpath, sources, true) processFile(foundpath, sources, true)
} }
}) })
if(testFileCount > 0) { if (testFileCount > 0) {
log.info(`${testFileCount} Solidity test file${testFileCount===1?'':'s'} found`) log.info(`${testFileCount} Solidity test file${testFileCount === 1 ? '' : 's'} found`)
} } else {
else { log.error('No Solidity test file found. Make sure your test file ends with \'_test.sol\'')
log.error(`No Solidity test file found. Make sure your test file ends with '_test.sol'`)
process.exit() process.exit()
} }
} }
} catch (e) { // eslint-disable-line no-useless-catch } catch (e) { // eslint-disable-line no-useless-catch
throw e throw e
} finally { } finally {
async.waterfall([ async.waterfall([
function loadCompiler(next) { function loadCompiler (next) {
compiler = new RemixCompiler() compiler = new RemixCompiler()
if(compilerConfig) { if (compilerConfig) {
const {currentCompilerUrl, evmVersion, optimize, runs} = compilerConfig const { currentCompilerUrl, evmVersion, optimize, runs } = compilerConfig
evmVersion ? compiler.set('evmVersion', evmVersion) : null if (evmVersion) compiler.set('evmVersion', evmVersion)
optimize ? compiler.set('optimize', optimize) : null if (optimize) compiler.set('optimize', optimize)
runs ? compiler.set('runs', runs) : null if (runs) compiler.set('runs', runs)
if(currentCompilerUrl) { if (currentCompilerUrl) {
compiler.loadRemoteVersion(currentCompilerUrl) compiler.loadRemoteVersion(currentCompilerUrl)
compiler.event.register('compilerLoaded', this, function (version) { compiler.event.register('compilerLoaded', this, function (version) {
next() next()
...@@ -145,7 +142,7 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts: ...@@ -145,7 +142,7 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts:
next() next()
} }
}, },
function doCompilation(next) { function doCompilation (next) {
// @ts-ignore // @ts-ignore
compiler.event.register('compilationFinished', this, (success, data, source) => { compiler.event.register('compilationFinished', this, (success, data, source) => {
next(null, data) next(null, data)
...@@ -160,7 +157,7 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts: ...@@ -160,7 +157,7 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts:
if (!isBrowser) require('signale').fatal(errors) if (!isBrowser) require('signale').fatal(errors)
return cb(new CompilationErrors(errors)) return cb(new CompilationErrors(errors))
} }
cb(err, result.contracts, result.sources) //return callback with contract details & ASTs cb(err, result.contracts, result.sources) // return callback with contract details & ASTs
}) })
} }
} }
...@@ -173,7 +170,7 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts: ...@@ -173,7 +170,7 @@ export function compileFileOrFiles(filename: string, isDirectory: boolean, opts:
* @param opts Options * @param opts Options
* @param cb Callback * @param cb Callback
*/ */
export function compileContractSources(sources: SrcIfc, compilerConfig: CompilerConfiguration, importFileCb: any, opts: any, cb): void { export function compileContractSources (sources: SrcIfc, compilerConfig: CompilerConfiguration, importFileCb: any, opts: any, cb): void {
let compiler, filepath: string let compiler, filepath: string
const accounts: string[] = opts.accounts || [] const accounts: string[] = opts.accounts || []
// Iterate over sources keys. Inject test libraries. Inject test library import statements. // Iterate over sources keys. Inject test libraries. Inject test library import statements.
...@@ -194,7 +191,7 @@ export function compileContractSources(sources: SrcIfc, compilerConfig: Compiler ...@@ -194,7 +191,7 @@ export function compileContractSources(sources: SrcIfc, compilerConfig: Compiler
async.waterfall([ async.waterfall([
function loadCompiler (next) { function loadCompiler (next) {
const {currentCompilerUrl, evmVersion, optimize, runs, usingWorker} = compilerConfig const { currentCompilerUrl, evmVersion, optimize, runs, usingWorker } = compilerConfig
compiler = new RemixCompiler(importFileCb) compiler = new RemixCompiler(importFileCb)
compiler.set('evmVersion', evmVersion) compiler.set('evmVersion', evmVersion)
compiler.set('optimize', optimize) compiler.set('optimize', optimize)
...@@ -212,7 +209,7 @@ export function compileContractSources(sources: SrcIfc, compilerConfig: Compiler ...@@ -212,7 +209,7 @@ export function compileContractSources(sources: SrcIfc, compilerConfig: Compiler
}) })
compiler.compile(sources, filepath) compiler.compile(sources, filepath)
} }
], function (err: Error | null | undefined , result: any) { ], function (err: Error | null | undefined, result: any) {
const error: Error[] = [] const error: Error[] = []
if (result.error) error.push(result.error) if (result.error) error.push(result.error)
const errors = (result.errors || error).filter((e) => e.type === 'Error' || e.severity === 'error') const errors = (result.errors || error).filter((e) => e.type === 'Error' || e.severity === 'error')
......
...@@ -11,19 +11,19 @@ import { compilationInterface } from './types' ...@@ -11,19 +11,19 @@ import { compilationInterface } from './types'
* @param callback Callback * @param callback Callback
*/ */
export function deployAll(compileResult: compilationInterface, web3: Web3, withDoubleGas: boolean, callback) { export function deployAll (compileResult: compilationInterface, web3: Web3, withDoubleGas: boolean, callback) {
const compiledObject = {} const compiledObject = {}
const contracts = {} const contracts = {}
let accounts: string[] = [] let accounts: string[] = []
async.waterfall([ async.waterfall([
function getAccountList(next) { function getAccountList (next) {
web3.eth.getAccounts((_err, _accounts) => { web3.eth.getAccounts((_err, _accounts) => {
accounts = _accounts accounts = _accounts
next() next()
}) })
}, },
function getContractData(next) { function getContractData (next) {
for (const contractFile in compileResult) { for (const contractFile in compileResult) {
for (const contractName in compileResult[contractFile]) { for (const contractName in compileResult[contractFile]) {
const contract = compileResult[contractFile][contractName] const contract = compileResult[contractFile][contractName]
...@@ -48,7 +48,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD ...@@ -48,7 +48,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD
} }
next() next()
}, },
function determineContractsToDeploy(next) { function determineContractsToDeploy (next) {
const contractsToDeploy: string[] = ['Assert'] const contractsToDeploy: string[] = ['Assert']
const allContracts = Object.keys(compiledObject) const allContracts = Object.keys(compiledObject)
...@@ -62,7 +62,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD ...@@ -62,7 +62,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD
} }
next(null, contractsToDeploy) next(null, contractsToDeploy)
}, },
function deployContracts(contractsToDeploy: string[], next) { function deployContracts (contractsToDeploy: string[], next) {
const deployRunner = (deployObject, contractObject, contractName, filename, callback) => { const deployRunner = (deployObject, contractObject, contractName, filename, callback) => {
deployObject.estimateGas().then((gasValue) => { deployObject.estimateGas().then((gasValue) => {
const gasBase = Math.ceil(gasValue * 1.2) const gasBase = Math.ceil(gasValue * 1.2)
...@@ -92,7 +92,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD ...@@ -92,7 +92,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD
const encodeDataFinalCallback = (error, contractDeployData) => { const encodeDataFinalCallback = (error, contractDeployData) => {
if (error) return nextEach(error) if (error) return nextEach(error)
const contractObject = new web3.eth.Contract(contract.abi) const contractObject = new web3.eth.Contract(contract.abi)
const deployObject = contractObject.deploy({arguments: [], data: '0x' + contractDeployData.dataHex}) const deployObject = contractObject.deploy({ arguments: [], data: '0x' + contractDeployData.dataHex })
deployRunner(deployObject, contractObject, contractName, contract.filename, (error) => { nextEach(error) }) deployRunner(deployObject, contractObject, contractName, contract.filename, (error) => { nextEach(error) })
} }
...@@ -102,7 +102,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD ...@@ -102,7 +102,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD
const abi = compiledObject[libData.data.contractName].abi const abi = compiledObject[libData.data.contractName].abi
const code = compiledObject[libData.data.contractName].code const code = compiledObject[libData.data.contractName].code
const libraryObject = new web3.eth.Contract(abi) const libraryObject = new web3.eth.Contract(abi)
const deployObject = libraryObject.deploy({arguments: [], data: '0x' + code}) const deployObject = libraryObject.deploy({ arguments: [], data: '0x' + code })
deployRunner(deployObject, libraryObject, libData.data.contractName, contract.filename, callback) deployRunner(deployObject, libraryObject, libData.data.contractName, contract.filename, callback)
} }
...@@ -110,7 +110,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD ...@@ -110,7 +110,7 @@ export function deployAll(compileResult: compilationInterface, web3: Web3, withD
const params = '' // we suppose that the test contract does not have any param in the constructor const params = '' // we suppose that the test contract does not have any param in the constructor
execution.txFormat.encodeConstructorCallAndDeployLibraries(contractName, contract.raw, compileResult, params, funAbi, encodeDataFinalCallback, encodeDataStepCallback, encodeDataDeployLibraryCallback) execution.txFormat.encodeConstructorCallAndDeployLibraries(contractName, contract.raw, compileResult, params, funAbi, encodeDataFinalCallback, encodeDataStepCallback, encodeDataDeployLibraryCallback)
}, function (err) { }, function (err) {
if(err) next(err) if (err) next(err)
next(null, contracts) next(null, contracts)
}) })
} }
......
// Extend fs // Extend fs
const fs: any = require('fs')
import path from 'path' import path from 'path'
const fs: any = require('fs')
// https://github.com/mikeal/node-utils/blob/master/file/lib/main.js // https://github.com/mikeal/node-utils/blob/master/file/lib/main.js
fs.walkSync = function (start: string, callback) { fs.walkSync = function (start: string, callback) {
......
import colors from 'colors' import colors from 'colors'
import winston, { Logger, LoggerOptions } from 'winston' import winston, { Logger, LoggerOptions } from 'winston'
import timestamp from 'time-stamp'; import timestamp from 'time-stamp'
import supportsColor from 'color-support' import supportsColor from 'color-support'
function hasFlag (flag: string) { function hasFlag (flag: string) {
...@@ -42,7 +42,8 @@ class Log { ...@@ -42,7 +42,8 @@ class Log {
) )
}) })
} }
setVerbosity (v: LoggerOptions["level"]): void {
setVerbosity (v: LoggerOptions['level']): void {
this.logger.configure({ this.logger.configure({
level: v, level: v,
transports: [new winston.transports.Console()], transports: [new winston.transports.Console()],
......
...@@ -7,9 +7,9 @@ import fs from './fileSystem' ...@@ -7,9 +7,9 @@ import fs from './fileSystem'
import { Provider } from '@remix-project/remix-simulator' import { Provider } from '@remix-project/remix-simulator'
import { CompilerConfiguration } from './types' import { CompilerConfiguration } from './types'
import Log from './logger' import Log from './logger'
import colors from 'colors'
const logger = new Log() const logger = new Log()
const log = logger.logger const log = logger.logger
import colors from 'colors'
// parse verbosity // parse verbosity
function mapVerbosity (v: number) { function mapVerbosity (v: number) {
...@@ -26,10 +26,10 @@ function mapVerbosity (v: number) { ...@@ -26,10 +26,10 @@ function mapVerbosity (v: number) {
function mapOptimize (v: string) { function mapOptimize (v: string) {
const optimize = { const optimize = {
'true': true, true: true,
'false': false false: false
} }
return optimize[v]; return optimize[v]
} }
const version = require('../package.json').version const version = require('../package.json').version
...@@ -52,7 +52,6 @@ commander ...@@ -52,7 +52,6 @@ commander
.option('-r, --runs <number>', 'set runs (e.g: 150, 250 etc)') .option('-r, --runs <number>', 'set runs (e.g: 150, 250 etc)')
.option('-v, --verbose <level>', 'set verbosity level (0 to 5)', mapVerbosity) .option('-v, --verbose <level>', 'set verbosity level (0 to 5)', mapVerbosity)
.action(async (testsPath) => { .action(async (testsPath) => {
// Check if path exists // Check if path exists
if (!fs.existsSync(testsPath)) { if (!fs.existsSync(testsPath)) {
log.error(testsPath + ' not found') log.error(testsPath + ' not found')
...@@ -63,7 +62,7 @@ commander ...@@ -63,7 +62,7 @@ commander
const isDirectory = fs.lstatSync(testsPath).isDirectory() const isDirectory = fs.lstatSync(testsPath).isDirectory()
// If path is for a file, file name must have `_test.sol` suffix // If path is for a file, file name must have `_test.sol` suffix
if(!isDirectory && !testsPath.endsWith('_test.sol')) { if (!isDirectory && !testsPath.endsWith('_test.sol')) {
log.error('Test filename should end with "_test.sol"') log.error('Test filename should end with "_test.sol"')
process.exit() process.exit()
} }
...@@ -77,14 +76,14 @@ commander ...@@ -77,14 +76,14 @@ commander
log.info('verbosity level set to ' + commander.verbose.blue) log.info('verbosity level set to ' + commander.verbose.blue)
} }
let compilerConfig = {} as CompilerConfiguration const compilerConfig = {} as CompilerConfiguration
if (commander.compiler) { if (commander.compiler) {
const compVersion = commander.compiler const compVersion = commander.compiler
const baseURL = 'https://binaries.soliditylang.org/wasm/' const baseURL = 'https://binaries.soliditylang.org/wasm/'
const response: AxiosResponse = await axios.get(baseURL + 'list.json') const response: AxiosResponse = await axios.get(baseURL + 'list.json')
const { releases, latestRelease } = response.data const { releases, latestRelease } = response.data
const compString = releases[compVersion] const compString = releases[compVersion]
if(!compString) { if (!compString) {
log.error(`No compiler found in releases with version ${compVersion}`) log.error(`No compiler found in releases with version ${compVersion}`)
process.exit() process.exit()
} else { } else {
...@@ -104,8 +103,8 @@ commander ...@@ -104,8 +103,8 @@ commander
} }
if (commander.runs) { if (commander.runs) {
if(!commander.optimize) { if (!commander.optimize) {
log.error(`Optimization should be enabled for runs`) log.error('Optimization should be enabled for runs')
process.exit() process.exit()
} }
compilerConfig.runs = commander.runs compilerConfig.runs = commander.runs
......
...@@ -3,7 +3,7 @@ import fs from './fileSystem' ...@@ -3,7 +3,7 @@ import fs from './fileSystem'
import { runTest } from './testRunner' import { runTest } from './testRunner'
import { TestResultInterface, ResultsInterface, CompilerConfiguration, compilationInterface, ASTInterface, Options, AstNode } from './types' import { TestResultInterface, ResultsInterface, CompilerConfiguration, compilationInterface, ASTInterface, Options, AstNode } from './types'
import colors from 'colors' import colors from 'colors'
import Web3 from 'web3'; import Web3 from 'web3'
import { compileFileOrFiles } from './compiler' import { compileFileOrFiles } from './compiler'
import { deployAll } from './deployer' import { deployAll } from './deployer'
...@@ -18,7 +18,7 @@ import { deployAll } from './deployer' ...@@ -18,7 +18,7 @@ import { deployAll } from './deployer'
*/ */
// eslint-disable-next-line @typescript-eslint/no-empty-function // eslint-disable-next-line @typescript-eslint/no-empty-function
export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3, compilerConfig: CompilerConfiguration, finalCallback: any = () => {}, opts?: Options) { export function runTestFiles (filepath: string, isDirectory: boolean, web3: Web3, compilerConfig: CompilerConfiguration, finalCallback: any = () => {}, opts?: Options) {
opts = opts || {} opts = opts || {}
compilerConfig = compilerConfig || {} as CompilerConfiguration compilerConfig = compilerConfig || {} as CompilerConfiguration
const sourceASTs: any = {} const sourceASTs: any = {}
...@@ -53,14 +53,13 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3, ...@@ -53,14 +53,13 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3,
next(null) next(null)
}) })
}, },
function compile(next) { function compile (next) {
compileFileOrFiles(filepath, isDirectory, { accounts }, compilerConfig, next) compileFileOrFiles(filepath, isDirectory, { accounts }, compilerConfig, next)
}, },
function deployAllContracts (compilationResult: compilationInterface, asts: ASTInterface, next) { function deployAllContracts (compilationResult: compilationInterface, asts: ASTInterface, next) {
// Extract AST of test contract file source // Extract AST of test contract file source
for(const filename in asts) { for (const filename in asts) {
if(filename.endsWith('_test.sol')) if (filename.endsWith('_test.sol')) { sourceASTs[filename] = asts[filename].ast }
sourceASTs[filename] = asts[filename].ast
} }
deployAll(compilationResult, web3, false, (err, contracts) => { deployAll(compilationResult, web3, false, (err, contracts) => {
if (err) { if (err) {
...@@ -72,7 +71,7 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3, ...@@ -72,7 +71,7 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3,
function determineTestContractsToRun (compilationResult: compilationInterface, contracts: any, next) { function determineTestContractsToRun (compilationResult: compilationInterface, contracts: any, next) {
const contractsToTest: string[] = [] const contractsToTest: string[] = []
const contractsToTestDetails: any[] = [] const contractsToTestDetails: any[] = []
const gatherContractsFrom = function(filename: string) { const gatherContractsFrom = function (filename: string) {
if (!filename.endsWith('_test.sol')) { if (!filename.endsWith('_test.sol')) {
return return
} }
...@@ -94,14 +93,14 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3, ...@@ -94,14 +93,14 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3,
} }
next(null, contractsToTest, contractsToTestDetails, contracts) next(null, contractsToTest, contractsToTestDetails, contracts)
}, },
function runTests(contractsToTest: string[], contractsToTestDetails: any[], contracts: any, next) { function runTests (contractsToTest: string[], contractsToTestDetails: any[], contracts: any, next) {
let totalPassing = 0 let totalPassing = 0
let totalFailing = 0 let totalFailing = 0
let totalTime = 0 let totalTime = 0
const errors: any[] = [] const errors: any[] = []
const _testCallback = function (err: Error | null | undefined, result: TestResultInterface) { const _testCallback = function (err: Error | null | undefined, result: TestResultInterface) {
if(err) throw err; if (err) throw err
if (result.type === 'contract') { if (result.type === 'contract') {
signale.name(result.value.white) signale.name(result.value.white)
} else if (result.type === 'testPass') { } else if (result.type === 'testPass') {
...@@ -128,7 +127,7 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3, ...@@ -128,7 +127,7 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3,
} }
_resultsCallback(null, result, cb) _resultsCallback(null, result, cb)
}) })
} catch(e) { } catch (e) {
console.error(e) console.error(e)
} }
}, function (err) { }, function (err) {
...@@ -149,7 +148,7 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3, ...@@ -149,7 +148,7 @@ export function runTestFiles(filepath: string, isDirectory: boolean, web3: Web3,
console.log(' ' + (index + 1) + ') ' + colors.bold(error.context + ': ') + error.value) console.log(' ' + (index + 1) + ') ' + colors.bold(error.context + ': ') + error.value)
console.log('') console.log('')
console.log(colors.red('\t error: ' + error.errMsg)) console.log(colors.red('\t error: ' + error.errMsg))
console.log(colors.green('\t expected value to be '+ error.assertMethod + ' to: ' + error.expected)) console.log(colors.green('\t expected value to be ' + error.assertMethod + ' to: ' + error.expected))
console.log(colors.red('\t returned: ' + error.returned)) console.log(colors.red('\t returned: ' + error.returned))
}) })
console.log('') console.log('')
......
import async, { ErrorCallback } from 'async' import async, { ErrorCallback } from 'async'
require('colors')
import { compileContractSources } from './compiler' import { compileContractSources } from './compiler'
import { deployAll } from './deployer' import { deployAll } from './deployer'
import { runTest } from './testRunner' import { runTest } from './testRunner'
import Web3 from 'web3'; import Web3 from 'web3'
import { Provider } from '@remix-project/remix-simulator' import { Provider } from '@remix-project/remix-simulator'
import { FinalResult, SrcIfc, compilationInterface, ASTInterface, Options, import {
TestResultInterface, AstNode, CompilerConfiguration } from './types' FinalResult, SrcIfc, compilationInterface, ASTInterface, Options,
TestResultInterface, AstNode, CompilerConfiguration
} from './types'
require('colors')
const createWeb3Provider = async function () { const createWeb3Provider = async function () {
const web3 = new Web3() const web3 = new Web3()
...@@ -28,7 +30,7 @@ const createWeb3Provider = async function () { ...@@ -28,7 +30,7 @@ const createWeb3Provider = async function () {
* @param importFileCb Import file callback * @param importFileCb Import file callback
* @param opts Options * @param opts Options
*/ */
export async function runTestSources(contractSources: SrcIfc, compilerConfig: CompilerConfiguration, testCallback, resultCallback, finalCallback: any, importFileCb, opts: Options) { export async function runTestSources (contractSources: SrcIfc, compilerConfig: CompilerConfiguration, testCallback, resultCallback, finalCallback: any, importFileCb, opts: Options) {
opts = opts || {} opts = opts || {}
const sourceASTs: any = {} const sourceASTs: any = {}
const web3 = opts.web3 || await createWeb3Provider() const web3 = opts.web3 || await createWeb3Provider()
...@@ -45,24 +47,21 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co ...@@ -45,24 +47,21 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co
compileContractSources(contractSources, compilerConfig, importFileCb, { accounts }, next) compileContractSources(contractSources, compilerConfig, importFileCb, { accounts }, next)
}, },
function deployAllContracts (compilationResult: compilationInterface, asts: ASTInterface, next) { function deployAllContracts (compilationResult: compilationInterface, asts: ASTInterface, next) {
for(const filename in asts) { for (const filename in asts) {
if(filename.endsWith('_test.sol')) if (filename.endsWith('_test.sol')) { sourceASTs[filename] = asts[filename].ast }
sourceASTs[filename] = asts[filename].ast
} }
deployAll(compilationResult, web3, false, (err, contracts) => { deployAll(compilationResult, web3, false, (err, contracts) => {
if (err) { if (err) {
// If contract deployment fails because of 'Out of Gas' error, try again with double gas // If contract deployment fails because of 'Out of Gas' error, try again with double gas
// This is temporary, should be removed when remix-tests will have a dedicated UI to // This is temporary, should be removed when remix-tests will have a dedicated UI to
// accept deployment params from UI // accept deployment params from UI
if(err.message.includes('The contract code couldn\'t be stored, please check your gas limit')) { if (err.message.includes('The contract code couldn\'t be stored, please check your gas limit')) {
deployAll(compilationResult, web3, true, (error, contracts) => { deployAll(compilationResult, web3, true, (error, contracts) => {
if (error) next([{message: 'contract deployment failed after trying twice: ' + error.message, severity: 'error'}]) // IDE expects errors in array if (error) next([{ message: 'contract deployment failed after trying twice: ' + error.message, severity: 'error' }]) // IDE expects errors in array
else next(null, compilationResult, contracts) else next(null, compilationResult, contracts)
}) })
} else } else { next([{ message: 'contract deployment failed: ' + err.message, severity: 'error' }]) } // IDE expects errors in array
next([{message: 'contract deployment failed: ' + err.message, severity: 'error'}]) // IDE expects errors in array } else { next(null, compilationResult, contracts) }
} else
next(null, compilationResult, contracts)
}) })
}, },
function determineTestContractsToRun (compilationResult: compilationInterface, contracts: any, next) { function determineTestContractsToRun (compilationResult: compilationInterface, contracts: any, next) {
...@@ -80,12 +79,12 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co ...@@ -80,12 +79,12 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co
} }
next(null, contractsToTest, contractsToTestDetails, contracts) next(null, contractsToTest, contractsToTestDetails, contracts)
}, },
function runTests(contractsToTest: string[], contractsToTestDetails: any[], contracts: any, next) { function runTests (contractsToTest: string[], contractsToTestDetails: any[], contracts: any, next) {
let totalPassing = 0 let totalPassing = 0
let totalFailing = 0 let totalFailing = 0
let totalTime = 0 let totalTime = 0
const errors: any[] = [] const errors: any[] = []
// eslint-disable-next-line handle-callback-err
const _testCallback = function (err: Error | null | undefined, result: TestResultInterface) { const _testCallback = function (err: Error | null | undefined, result: TestResultInterface) {
if (result.type === 'testFailure') { if (result.type === 'testFailure') {
errors.push(result) errors.push(result)
...@@ -94,7 +93,7 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co ...@@ -94,7 +93,7 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co
} }
const _resultsCallback = function (_err, result, cb) { const _resultsCallback = function (_err, result, cb) {
resultCallback(_err, result, () => {}) //eslint-disable-line @typescript-eslint/no-empty-function resultCallback(_err, result, () => {}) // eslint-disable-line @typescript-eslint/no-empty-function
totalPassing += result.passingNum totalPassing += result.passingNum
totalFailing += result.failureNum totalFailing += result.failureNum
totalTime += result.timePassed totalTime += result.timePassed
...@@ -118,7 +117,7 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co ...@@ -118,7 +117,7 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co
totalPassing: 0, totalPassing: 0,
totalFailing: 0, totalFailing: 0,
totalTime: 0, totalTime: 0,
errors: [], errors: []
} }
finalResults.totalPassing = totalPassing || 0 finalResults.totalPassing = totalPassing || 0
...@@ -127,7 +126,7 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co ...@@ -127,7 +126,7 @@ export async function runTestSources(contractSources: SrcIfc, compilerConfig: Co
finalResults.errors = [] finalResults.errors = []
errors.forEach((error, _index) => { errors.forEach((error, _index) => {
finalResults.errors.push({context: error.context, value: error.value, message: error.errMsg}) finalResults.errors.push({ context: error.context, value: error.value, message: error.errMsg })
}) })
next(null, finalResults) next(null, finalResults)
......
This diff is collapsed.
...@@ -64,7 +64,7 @@ export interface CompilationErrors { ...@@ -64,7 +64,7 @@ export interface CompilationErrors {
} }
export class CompilationErrors extends Error { export class CompilationErrors extends Error {
constructor(errors: Array<any>) { constructor (errors: Array<any>) {
const mapError = errors.map((e) => { return e.formattedMessage || e.message }) const mapError = errors.map((e) => { return e.formattedMessage || e.message })
super(mapError.join('\n')) super(mapError.join('\n'))
this.errors = errors this.errors = errors
...@@ -74,9 +74,9 @@ export class CompilationErrors extends Error { ...@@ -74,9 +74,9 @@ export class CompilationErrors extends Error {
/** sources object with name of the file and content **/ /** sources object with name of the file and content **/
//////////// /// /////////
// SOURCE // // SOURCE //
//////////// /// /////////
export interface CompilationSource { export interface CompilationSource {
/** Identifier of the source (used in source maps) */ /** Identifier of the source (used in source maps) */
id: number id: number
...@@ -162,9 +162,9 @@ export interface CompiledContract { ...@@ -162,9 +162,9 @@ export interface CompiledContract {
} }
} }
///////// /// //////
// ABI // // ABI //
///////// /// //////
export type ABIDescription = FunctionDescription | EventDescription export type ABIDescription = FunctionDescription | EventDescription
export interface FunctionDescription { export interface FunctionDescription {
...@@ -227,9 +227,9 @@ export type ABITypeParameter = ...@@ -227,9 +227,9 @@ export type ABITypeParameter =
| 'tuple[]' | 'tuple[]'
| string // Fallback | string // Fallback
/////////////////////////// /// ////////////////////////
// NATURAL SPECIFICATION // // NATURAL SPECIFICATION //
/////////////////////////// /// ////////////////////////
// Userdoc // Userdoc
export interface UserDocumentation { export interface UserDocumentation {
...@@ -267,9 +267,9 @@ export interface DevMethodDoc { ...@@ -267,9 +267,9 @@ export interface DevMethodDoc {
} }
} }
////////////// /// ///////////
// BYTECODE // // BYTECODE //
////////////// /// ///////////
export interface BytecodeObject { export interface BytecodeObject {
/** The bytecode as a hex string. */ /** The bytecode as a hex string. */
object: string object: string
......
...@@ -41,7 +41,7 @@ ...@@ -41,7 +41,7 @@
"workspace-schematic": "nx workspace-schematic", "workspace-schematic": "nx workspace-schematic",
"dep-graph": "nx dep-graph", "dep-graph": "nx dep-graph",
"help": "nx help", "help": "nx help",
"lint:libs": "nx run-many --target=lint --projects=remix-analyzer,remix-astwalker,remix-debug,remix-lib,remix-simulator,remix-solidity,remixd,remix-ui-tree-view,remix-ui-modal-dialog,remix-ui-toaster,remix-ui-file-explorer,remix-ui-debugger-ui", "lint:libs": "nx run-many --target=lint --projects=remix-analyzer,remix-astwalker,remix-debug,remix-lib,remix-simulator,remix-solidity,remix-tests,remixd,remix-ui-tree-view,remix-ui-modal-dialog,remix-ui-toaster,remix-ui-file-explorer,remix-ui-debugger-ui",
"build:libs": "nx run-many --target=build --parallel=false --with-deps=true --projects=remix-analyzer,remix-astwalker,remix-debug,remix-lib,remix-simulator,remix-solidity,remix-tests,remix-url-resolver,remixd", "build:libs": "nx run-many --target=build --parallel=false --with-deps=true --projects=remix-analyzer,remix-astwalker,remix-debug,remix-lib,remix-simulator,remix-solidity,remix-tests,remix-url-resolver,remixd",
"test:libs": "nx run-many --target=test --projects=remix-analyzer,remix-astwalker,remix-debug,remix-lib,remix-simulator,remix-solidity,remix-tests,remix-url-resolver,remixd", "test:libs": "nx run-many --target=test --projects=remix-analyzer,remix-astwalker,remix-debug,remix-lib,remix-simulator,remix-solidity,remix-tests,remix-url-resolver,remixd",
"publish:libs": "npm run build:libs & lerna publish --skip-git & npm run bumpVersion:libs", "publish:libs": "npm run build:libs & lerna publish --skip-git & npm run bumpVersion:libs",
......
...@@ -347,7 +347,7 @@ ...@@ -347,7 +347,7 @@
"linter": "eslint", "linter": "eslint",
"config": "libs/remix-tests/.eslintrc", "config": "libs/remix-tests/.eslintrc",
"tsConfig": ["libs/remix-tests/tsconfig.lib.json"], "tsConfig": ["libs/remix-tests/tsconfig.lib.json"],
"exclude": ["**/node_modules/**", "libs/remix-tests/tests/**/*"] "exclude": ["**/node_modules/**", "libs/remix-tests/tests/**/*", "**/dist/**"]
} }
}, },
"test": { "test": {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment