-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
292 lines (264 loc) · 10 KB
/
index.js
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
const util = require('util')
const path = require('path')
const fs = require('fs')
const Mocha = require('mocha')
const { mkdirpSync } = require('mkdirp')
const isJSON = require('is-json')
const slug = require('slug')
const mime = require('mime-types')
const promiseRetry = require('promise-retry')
const { BotDriver, RetryHelper } = require('botium-core')
const expect = require('chai').expect
const addContext = require('mochawesome/addContext')
const { reportUsage } = require('../metrics')
const debug = require('debug')('botium-cli-run')
const outputTypes = [
'dot',
'nyan',
'landing',
'tap',
'json',
'json-stream',
'xunit',
'spec',
'list',
'min',
'doc',
'progress',
'csv',
'mochawesome'
]
const parseReporterOptions = (args) => {
if (!args) return
if (isJSON(args)) {
return JSON.parse(args)
}
return args.split(',').reduce((acc, option) => {
if (option.indexOf('=') > 0) {
const [key, value] = option.split('=')
acc[key] = value
} else {
acc[option] = true
}
return acc
}, {})
}
const parseReporter = (output) => {
return output === 'csv' ? CsvReporter : output
}
class CsvReporter {
constructor (runner) {
Mocha.reporters.Base.call(this, runner)
const quote = (str) => str ? str.replace('"', '""') : ''
runner.on('start', function () {
console.log('STATUS,SUITE,TEST,DURATION,MESSAGE')
})
runner.on('pass', function (test) {
console.log(`"OK","${quote(test.parent && test.parent.title)}","${quote(test.title)}",${test.duration},""`)
})
runner.on('fail', function (test, err) {
console.log(`"NOK","${quote(test.parent && test.parent.title)}","${quote(test.title)}",${test.duration},"${quote(err.message)}"`)
})
}
}
const wrapBotiumError = (err) => {
if (err.cause && err.cause.prettify) {
return new Error(err.message + '\r\n' + err.cause.prettify())
} else {
return new Error(err.message)
}
}
const handler = (argv) => {
debug(`command options: ${util.inspect(argv)}`)
const reporterOptions = parseReporterOptions(argv.reporterOptions)
debug(`Mocha Reporter "${argv.output}", options: ${util.inspect(reporterOptions)}`)
argv.testsuitename = process.env.BOTIUM_TESTSUITENAME || argv.testsuitename
argv.timeout = process.env.BOTIUM_TIMEOUT || argv.timeout
argv.timeout = argv.timeout * 1000
argv.attachments = process.env.BOTIUM_ATTACHMENTS || argv.attachments
if (argv.attachments && !fs.existsSync(argv.attachments)) {
try {
mkdirpSync(argv.attachments)
debug(`Created attachments directory "${argv.attachments}"`)
} catch (err) {
console.log(`Failed to create attachments directory ${argv.attachments}: ${err.message}`)
process.exit(1)
}
}
const driver = new BotDriver()
const compiler = driver.BuildCompiler()
compiler.scriptingEvents.fail = (err) => {
expect.fail(null, null, err)
}
argv.convos.forEach((convodir) => {
compiler.ReadScriptsFromDirectory(convodir, process.env.BOTIUM_FILTER || argv.filter)
})
debug(`ready reading convos (${compiler.convos.length}), expanding convos ...`)
if (process.env.BOTIUM_EXPANDUTTERANCES === '1' || argv.expandutterances) {
debug('expanding utterances ...')
compiler.ExpandUtterancesToConvos()
}
if (process.env.BOTIUM_EXPANDSCRIPTINGMEMORY === '1' || argv.expandscriptingmemory) {
debug('expanding scripting memory ...')
compiler.ExpandScriptingMemoryToConvos()
}
compiler.ExpandConvos()
const usageMetrics = {
metric: 'testexecution',
connector: `${compiler.caps.CONTAINERMODE}`,
testsuitename: argv.testsuitename,
projectname: `${compiler.caps.PROJECTNAME}`,
convoCount: compiler.convos.length,
convoStepCount: compiler.convos.reduce((sum, convo) => sum + convo.conversation.length, 0),
partialConvoCount: Object.keys(compiler.partialConvos).length,
utterancesRefCount: Object.keys(compiler.utterances).length,
utterancesCount: Object.keys(compiler.utterances).reduce((sum, uttName) => sum + compiler.utterances[uttName].utterances.length, 0),
scriptingMemoriesCount: compiler.scriptingMemories.length
}
reportUsage(usageMetrics)
debug(`ready expanding convos and utterances, number of test cases: (${compiler.convos.length}).`)
const mocha = new Mocha({
reporter: parseReporter(argv.output),
reporterOptions
})
const suite = Mocha.Suite.create(mocha.suite, process.env.BOTIUM_TESTSUITENAME || argv.testsuitename)
suite.timeout(argv.timeout)
suite.beforeAll((done) => {
driver.Build()
.then((container) => {
suite.container = container
done()
})
.catch(done)
})
suite.beforeEach((done) => {
suite.container ? suite.container.Start().then(() => done()).catch(done) : done()
})
suite.afterEach((done) => {
suite.container ? suite.container.Stop().then(() => done()).catch(done) : done()
})
suite.afterAll((done) => {
suite.container ? suite.container.Clean().then(() => done()).catch(done) : done()
})
let runner = null
compiler.convos.forEach((convo) => {
debug(`adding test case ${convo.header.name} (from: ${util.inspect(convo.sourceTag)})`)
const test = new Mocha.Test(convo.header.name, (testcaseDone) => {
debug('running testcase ' + convo.header.name)
const attachmentsLog = []
const listenerMe = (container, msg) => {
if (msg.attachments) attachmentsLog.push(...msg.attachments)
}
const listenerBot = (container, msg) => {
if (msg.attachments) attachmentsLog.push(...msg.attachments)
}
const listenerAttachments = (container, attachment) => {
attachmentsLog.push(attachment)
}
driver.on('MESSAGE_SENTTOBOT', listenerMe)
driver.on('MESSAGE_RECEIVEDFROMBOT', listenerBot)
driver.on('MESSAGE_ATTACHMENT', listenerAttachments)
const finish = (transcript, err) => {
if (transcript) {
addContext(runner, { title: 'Conversation Log', value: transcript.prettifyActual() })
}
driver.eventEmitter.removeListener('MESSAGE_SENTTOBOT', listenerMe)
driver.eventEmitter.removeListener('MESSAGE_RECEIVEDFROMBOT', listenerBot)
driver.eventEmitter.removeListener('MESSAGE_ATTACHMENT', listenerAttachments)
if (argv.attachments && attachmentsLog.length > 0) {
debug(`Found ${attachmentsLog.length} attachments, saving to folder ${argv.attachments}`)
attachmentsLog.forEach((a, i) => {
const filename = slug(convo.header.name) + '_' + i + (a.name ? '_' + slug(a.name) : '') + (a.mimeType ? '.' + mime.extension(a.mimeType) : '')
const outputTo = path.join(argv.attachments, filename)
try {
fs.writeFileSync(outputTo, Buffer.from(a.base64, 'base64'))
} catch (err) {
debug(`Failed to write attachment to ${outputTo}: ${err.message || util.inspect(err)}`)
}
})
}
if (err) {
testcaseDone(wrapBotiumError(err))
} else {
testcaseDone()
}
}
const retryHelper = new RetryHelper(suite.container.caps, 'CONVO')
promiseRetry(async (retry, number) => {
try {
const transcript = await convo.Run(suite.container)
debug(convo.header.name + ' ready, calling done function.')
return transcript
} catch (err) {
if (retryHelper.shouldRetry(err)) {
debug(`Running Convo "${convo.header.name}" trial #${number} failed, retry activated`)
await suite.container.Stop()
await suite.container.Start()
debug(`Restarting container for Convo "${convo.header.name}" trial #${number} completed successfully.`)
retry(err)
} else {
debug(`Running Convo "${convo.header.name}" trial #${number} failed finally`)
throw err
}
}
}, retryHelper.retrySettings)
.then((transcript) => {
debug(convo.header.name + ' ready, calling done function.')
finish(transcript)
})
.catch((err) => {
debug(convo.header.name + ' failed: ' + util.inspect(err))
finish(err.transcript, err)
})
})
test.timeout(argv.timeout)
suite.addTest(test)
})
runner = mocha.run((failures) => {
process.on('exit', () => {
process.exit(failures)
})
})
}
module.exports = {
command: 'run [output]',
describe: 'Run Botium convo files and output test report with Mocha test runner',
builder: (yargs) => {
yargs.positional('output', {
describe: 'Output report type (select Mocha reporter)',
choices: outputTypes,
default: 'spec'
})
yargs.option('testsuitename', {
alias: 'n',
describe: 'Name of the Test Suite (also read from env variable "BOTIUM_TESTSUITENAME")',
default: 'Botium Test-Suite'
})
yargs.option('filter', {
describe: 'Filter the convo files to run with a "glob" filter (also read from env variable "BOTIUM_FILTER"), for example "**/*.en.*.txt"'
})
yargs.option('expandutterances', {
describe: 'Expand all utterances (except INCOMPREHENSION) to simple Question/Answer convos (also read from env variable "BOTIUM_EXPANDUTTERANCES" - "1" means yes)',
default: false
})
yargs.option('expandscriptingmemory', {
describe: 'Expand scripting memory tables to separate convos (also read from env variable "BOTIUM_EXPANDSCRIPTINGMEMORY" - "1" means yes)',
default: false
})
yargs.option('attachments', {
describe: 'Directory where to save message attachments, for example screenshots from webdriver (also read from env variable "BOTIUM_ATTACHMENTS")'
})
yargs.option('timeout', {
describe: 'Timeout in seconds for Botium functions (also read from env variable "BOTIUM_TIMEOUT")',
number: true,
default: 60
})
yargs.option('reporter-options', {
describe: 'Options for mocha reporter, either as JSON, or as key-value pairs ("option1=value1,option2=value2,..."). For details see documentation of the used mocha reporter.'
})
},
handler,
parseReporterOptions,
parseReporter,
outputTypes
}