-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmutode.js.html
More file actions
365 lines (322 loc) · 15.1 KB
/
Copy pathmutode.js.html
File metadata and controls
365 lines (322 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>mutode.js - Documentation</title>
<script src="scripts/prettify/prettify.js"></script>
<script src="scripts/prettify/lang-css.js"></script>
<!--[if lt IE 9]>
<script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<link type="text/css" rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css">
<link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css">
</head>
<body>
<input type="checkbox" id="nav-trigger" class="nav-trigger" />
<label for="nav-trigger" class="navicon-button x">
<div class="navicon"></div>
</label>
<label for="nav-trigger" class="overlay"></label>
<nav>
<li class="nav-link nav-home-link"><a href="index.html">Home</a></li><li class="nav-heading">Classes</li><li class="nav-heading"><span class="nav-item-type type-class">C</span><span class="nav-item-name"><a href="Mutode.html">Mutode</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="Mutode.html#run">run</a></span></li><li class="nav-heading">Modules</li><li class="nav-heading"><span class="nav-item-type type-module">M</span><span class="nav-item-name"><a href="module-MutantRunner.html">MutantRunner</a></span></li><li class="nav-heading"><span class="nav-item-type type-module">M</span><span class="nav-item-name"><a href="module-Mutators.html">Mutators</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.booleanLiteralsMutator">booleanLiteralsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.conditionalsBoundaryMutator">conditionalsBoundaryMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.incrementsMutator">incrementsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.invertNegativesMutator">invertNegativesMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.mathMutator">mathMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.negateConditionalsMutator">negateConditionalsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.numericLiteralsMutator">numericLiteralsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.removeArrayElementsMutator">removeArrayElementsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.removeConditionalsMutator">removeConditionalsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.removeFuncCallArgsMutator">removeFuncCallArgsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.removeFuncDeclarationParamsMutator">removeFuncDeclarationParamsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.removeFunctionsMutator">removeFunctionsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.removeLinesMutator">removeLinesMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.removeObjPropsMutator">removeObjPropsMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.removeSwitchCasesMutator">removeSwitchCasesMutator</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="module-Mutators.html#.stringLiteralsMutator">stringLiteralsMutator</a></span></li>
</nav>
<div id="main">
<h1 class="page-title">mutode.js</h1>
<section>
<article>
<pre class="prettyprint source linenums"><code>const async = require('async')
const babylon = require('babylon')
const spawn = require('child_process').spawn
const debug = require('debug')('mutode')
const del = require('del')
const fs = require('fs')
const globby = require('globby')
const mkdirp = require('mkdirp')
const os = require('os')
const path = require('path')
const prettyMs = require('pretty-ms')
const copyDir = require('recursive-copy')
const stripAnsi = require('strip-ansi')
const {promisify} = require('util')
const readFile = promisify(fs.readFile)
/**
* Mutode's main class
*/
class Mutode {
/**
* Create a new Mutode instance
* @param opts {Object}
* @param {array<string>} [opts.paths = ['index.js', 'src/']] - Glob matched paths or files to mutate
* @param {number} [opts.concurrency = # of cpu cores] - Number of concurrent workers
* @param {array<string>} [opts.mutators = All]- Mutators to load (e.g. *deletion*)
* @returns {Mutode} - Returns an instance of mutode
*/
constructor ({paths = [], concurrency = os.cpus().length, mutators = ['*']} = {}) {
if (!Array.isArray(paths)) paths = [paths]
if (!Array.isArray(mutators)) mutators = [mutators]
if (paths.length === 0) paths = ['index.js', 'src/']
debug('Config:\n\tFile paths %o\n\tConcurrency: %s\n\tMutators: %s', paths, concurrency, mutators)
Mutode.mkdir()
this.filePaths = globby.sync(paths)
debug('Globbed files %o', this.filePaths)
if (this.filePaths.length === 0) {
throw new Error('No files found in the specified paths')
}
this.id = `${Math.floor(Date.now() / 10000)}`
this.npmCommand = /^win/.test(process.platform) ? 'npm.cmd' : 'npm'
this.mutators = mutators
this.concurrency = concurrency
this.mutants = 0
this.killed = 0
this.survived = 0
this.discarded = 0
this.coverage = 0
this.workers = {}
for (let i = 0; i < this.concurrency; i++) {
this.workers[i] = true
}
this.mutantsLogFile = fs.createWriteStream(path.resolve(`.mutode/mutants-${this.id}.log`), {flags: 'w'})
this.logFile = fs.createWriteStream(path.resolve(`.mutode/mutode-${this.id}.log`), {flags: 'w'})
this.mutantLog = string => this.mutantsLogFile.write(`${stripAnsi(string.trim())}\n`)
console.logSame = s => {
process.stdout.write(s)
this.logFile.write(stripAnsi(s))
}
console.log = (s = '') => {
process.stdout.write(`${s}\n`)
this.logFile.write(`${stripAnsi(s.toString().trim())}\n`)
}
}
/**
* Run current instance
* @returns {Promise} - Promise that resolves once this instance's execution is completed.
*/
async run () {
if (this.mutants > 0) throw new Error('This instance has already been executed')
console.log(`Mutode ${this.id} running`)
await this.delete()
const startTime = process.hrtime()
try {
await this.copyFirst()
this.mutators = await Mutode.loadMutants(this.mutators)
this.timeout = await this.timeCleanTests()
debug('Setting mutant runner timeout to %s seconds', this.timeout / 1000)
this.copied = this.copy()
await new Promise((resolve, reject) => {
async.eachSeries(this.filePaths, this.fileProcessor(), this.done(resolve, reject))
})
} catch (e) {
debug(e)
throw e
} finally {
await this.delete()
const endTime = process.hrtime(startTime)
const endTimeMS = endTime[0] * 1e3 + endTime[1] / 1e6
console.log(`Mutode ${this.id} finished. Took ${prettyMs(endTimeMS)}`)
console.log()
this.mutantsLogFile.end()
this.logFile.end()
}
}
/**
* Function that returns an async function to process one file binded to the instance scope.
* @private
* @returns {function(filePath)} - Async function that runs instance's mutators and executes generated mutants for one file.
*/
fileProcessor () {
return async filePath => {
debug('Creating mutants for %s', filePath)
const before = this.mutants
const queue = async.queue(async task => {
const i = await this.freeWorker()
debug('Running task in worker %d', i)
await task(i)
this.workers[i] = true
debug('Finished running task in worker %d', i)
}, this.concurrency)
queue.pause()
this.copied.then(() => {
console.log(`Running mutants for ${filePath}`)
queue.resume()
})
const fileContent = (await readFile(filePath)).toString()
const lines = fileContent.split('\n')
let ast
try {
ast = babylon.parse(fileContent)
} catch (e) {
try {
ast = babylon.parse(fileContent, {sourceType: 'module'})
} catch (e) {
console.log(`Couldn't parse AST for file ${filePath}`)
debug(e)
throw e
}
}
for (const mutator of this.mutators) {
debug('Running mutator %s', mutator.name)
const before = this.mutants
await mutator({mutodeInstance: this, filePath, lines, queue, ast})
const generated = this.mutants - before
debug('Mutator %s generated %d mutants', mutator.name, generated)
}
const generated = this.mutants - before
debug('%d mutants generated for %s', generated, filePath)
await new Promise(resolve => {
const resolveWhenDone = () => {
for (let i = 0; i < this.concurrency; i++) {
fs.writeFileSync(`.mutode/mutode-${this.id}-${i}/${filePath}`, fileContent) // Reset file to original content
}
console.log()
setImmediate(resolve)
}
if (queue.length() === 0) {
return this.copied.then(() => {
resolveWhenDone()
})
}
debug('Adding drain function to queue %d', queue.length())
queue.drain = () => {
debug(`Finished %s`, filePath)
resolveWhenDone()
}
})
}
}
/**
* Promise handler that returns a function that runs when mutants execution is completed.
* @private
* @param resolve {function} - Promise resolve handler
* @returns {function} - Function that runs when mutants execution is completed.
*/
done (resolve, reject) {
return err => {
if (err) {
debug(err)
return reject(err)
}
console.log(`Out of ${this.mutants} mutants, ${this.killed} were killed, ${this.survived} survived and ${this.discarded} were discarded`)
this.coverage = +((this.mutants > 0 ? this.killed : 1) / ((this.mutants - this.discarded) || 1) * 100).toFixed(2)
console.log(`Mutant coverage: ${this.coverage}%`)
setImmediate(resolve)
}
}
/**
* Function that returns the index of the first worker that is free.
* @private
*/
async freeWorker () {
for (let i = 0; i < this.concurrency; i++) {
if (this.workers[i]) {
this.workers[i] = false
return i
}
}
}
/**
* Times the AUT's test suite execution.
* @private
* @returns {Promise} - Promise that resolves once AUT's test suite execution is completed.
*/
async timeCleanTests () {
console.log(`Verifying and timing your test suite`)
const start = +new Date()
const child = spawn(this.npmCommand, ['test'], {cwd: path.resolve(`.mutode/mutode-${this.id}-0`)})
child.stderr.on('data', data => {
debug(data.toString())
})
child.stdout.on('data', data => {
debug(data.toString())
})
return new Promise((resolve, reject) => {
child.on('exit', code => {
if (code !== 0) return reject(new Error('Test suite most exit with code 0 with no mutants for Mutode to continue'))
const diff = +new Date() - start
const timeout = Math.max(Math.ceil(diff / 1000) * 2500, 5000)
console.log(`Took ${(diff / 1000).toFixed(2)} seconds to run full test suite\n`)
resolve(timeout)
})
})
}
/**
* Synchronous load of mutators.
* @private
* @returns {Promise} - Promise that resolves with the loaded mutators
*/
static async loadMutants (mutatorsNames) {
console.logSame('Loading mutators... ')
let mutatorsPaths = mutatorsNames.map(m => `mutators/${m}Mutator.js`)
const mutators = []
const mutatorsPath = path.resolve(__dirname, 'mutators/')
mutatorsPaths = await globby(mutatorsPaths, {cwd: __dirname, absolute: true})
for (const mutatorPath of mutatorsPaths) {
debug('Loaded mutator %s', mutatorPath.replace(mutatorsPath + '/', '').replace('Mutator.js', ''))
mutators.push(require(path.resolve(mutatorPath)))
}
console.log('Done\n')
return mutators
}
/**
* Creates a an exact copy of the AUT.
* @private
* @returns {Promise} - Promise that resolves once the copy is created.
*/
async copyFirst () {
console.logSame(`Creating a copy of your module... `)
await copyDir('./', `.mutode/mutode-${this.id}-0`, {dot: true, filter: p => !p.startsWith('.')})
console.log('Done\n')
}
/**
* Creates <i>this.concurrency<i/> exact copies of the AUT.
* @private
* @returns {Promise} - Promise that resolves once the copies are created.
*/
async copy () {
if (this.concurrency === 1) return
console.logSame(`Creating ${this.concurrency - 1} extra copies of your module... `)
for (let i = 1; i < this.concurrency; i++) {
console.logSame(`${i}.. `)
await copyDir('./', `.mutode/mutode-${this.id}-${i}`, {dot: true, filter: p => !p.startsWith('.')})
}
console.log('Done\n')
}
/**
* Creates the <i>.mutode</i> folder to save logs.
* @private
*/
static mkdir () {
mkdirp.sync(path.resolve('.mutode'))
}
/**
* Deletes available copies of the AUT.
* @private
* @returns {Promise} - Promise that resolves once copies have been deleted.
*/
async delete () {
const toDelete = await globby(`.mutode/*`, {dot: true, onlyDirectories: true})
if (toDelete.length === 0) return
console.logSame('Deleting copies...')
for (const path of toDelete) {
await del(path, {force: true})
}
console.log('Done\n')
}
}
/**
* @module Mutators
*/
module.exports = Mutode
</code></pre>
</article>
</section>
</div>
<br class="clear">
<footer>
Generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Sat May 26 2018 21:55:06 GMT-0500 (-05) using the Minami theme.
</footer>
<script>prettyPrint();</script>
<script src="scripts/linenumber.js"></script>
</body>
</html>