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

linting for remix-tests fixed

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