-
Notifications
You must be signed in to change notification settings - Fork 0
/
putter.js
executable file
·256 lines (222 loc) · 8.02 KB
/
putter.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
// The Main file for this project.
// Uses Commander to parse command lines and figure out what to do.
// Basic usage: given a postman .json file, parse out only the bits
// we actually used in CS 261 and execute them, recording passes and fails.
import axios from 'axios';
import http from 'http';
// file system work with promises
import fs from 'fs/promises';
import { substituteString, convertHeaders } from './variables.js';
import { createVM, sandbox } from './vm.js';
// chalk prints pretty colors for console
import chalk from 'chalk';
chalk.level = 1; // keep it simple
// helper functions
const log = console.log;
const error = chalk.redBright;
const warning = chalk.yellow;
const success = chalk.greenBright;
// commander does our command-line interface
import {Command} from 'commander';
const program = new Command();
let verboseMode = false;
let addressOverride = undefined;
let httpsOverride = false;
let portOverride = undefined;
async function getVersion() {
try {
const packageJSON = JSON.parse(await fs.readFile('./package.json'));
return packageJSON.version;
} catch(e) {
console.log(`Failed to read packageJSON: ${e}`);
return "error";
}
}
program
.name('putter')
.version(await getVersion())
.description('run unit tests for CS261 assignments');
program
.command('run')
.argument('<string>', 'file to run')
.option('--verbose', 'verbose output')
.option('--address <value>', 'override URL address')
.option('--port <value>', 'override URL port')
.option('--https', 'use https')
.action((filename, options) => {
verboseMode = options.verbose;
if (verboseMode) {
log(error("VERBOSE MODE!"));
}
if (options.address) {
addressOverride = options.address;
log(error(`Overriding Address to be ${addressOverride}`));
}
httpsOverride = options.https;
if (httpsOverride) {
log(error("Forcing HTTPS instead of HTTP"));
}
portOverride = options.port;
if (portOverride) {
log(error(`Forcing Port ${portOverride} instead of default`));
}
log(`processing ${filename}`);
fs.readFile(filename)
.then(async data => {
let postObj = JSON.parse(data);
log(`Loaded file ${chalk.green(postObj.info.name)}`);
await doRun(postObj);
})
.catch(err => {
log(error(`Failed to process input file: ${err}\n${err.stack}`));
process.exit(1);
});
});
// given a postman json object, run all the tests in it
async function doRun(postObj) {
loadVariables(postObj);
for(let folderIdx=0; folderIdx < postObj.item.length; folderIdx++) {
let folder = postObj.item[folderIdx];
log(`Folder: ${folder.name}`);
for(let itemIdx = 0; itemIdx < folder.item.length; itemIdx++) {
let item = folder.item[itemIdx];
process.stdout.write(`\tItem: ${item.name}...`);
await doPreRequestEvent(folder, item);
let response = await doRequest(folder, item);
evaluateTests(folder, item, response);
log(success("passed!"));
}
}
// if we're here, we were successful!
log(success(`Test run successful! Ran ${sandbox.pm.testCounter} tests.`));
}
// process the 'variable' section, loading some values
// into our sandbox global space
function loadVariables(postObj) {
log("Loading Variables...");
for(let i = 0; i < postObj.variable.length; i++) {
let kv = postObj.variable[i];
if (verboseMode) {
console.log(chalk.blue(JSON.stringify(kv)));
}
sandbox.pm.environment.set(kv.key, kv.value);
}
// TODO overrides from command line options here
if (addressOverride) {
log(`Setting {{address}} to ${addressOverride}`);
sandbox.pm.environment.set("address", addressOverride);
}
if (portOverride) {
log(`Setting port to ${portOverride}`);
sandbox.pm.environment.set("port", portOverride);
}
log("Variables processed");
}
// execute all the 'prerequest' events found in this item
async function doPreRequestEvent(folder, item) {
for (let i=0; i < item.event.length; i++) {
let event = item.event[i];
if (event.listen != "prerequest") {
// not the event type we're looking for
continue;
}
let script = event.script.exec.join('\n');
if (script.length > 0) {
if (verboseMode) {
log(warning("PreRequestEvent Script:"))
log(warning(script));
log(warning("--------"));
log(warning("about to run pre-request"));
}
// runs the event code:
await createVM().run(script);
if (verboseMode) {
log(warning("done running pre-request"));
printEnvironment();
}
}
}
}
function printEnvironment() {
log(success("Status of Environment:"));
sandbox.pm.environment.forEach((v, k) => {
log(success(`${k} = ${v}`));
})
log(success("-==========-"));
}
// run an HTTP Request against a target, in a sandbox
// keep track of all the results for testing later!
async function doRequest(folder, item) {
let req = item.request;
// build url
let url = req.url.raw;
if (httpsOverride) {
url = url.replace("http://", "https://")
}
url = substituteString(url, sandbox.pm.environment);
if (verboseMode) {
console.log(`request url is ${url}`);
}
// build post body?
let body = {};
if (req.body) {
body = substituteString(req.body.raw, sandbox.pm.environment);
}
// populate headers
let headers = convertHeaders(req.header);
// execute and get response
try {
return await axios({
method: req.method,
url: url,
data: body,
headers: headers,
validateStatus: (s) => {
return s < 500; // 5xx errors will throw an error and bail on the whole thing
},
httpAgent: new http.Agent({ keepAlive: false })
});
} catch(err) {
log(error(`${req.method} request to ${url} failed: ${err}`));
process.exit(1);
}
}
async function evaluateTests(folder, item, resp) {
// fill in some values in our pm object so that the test script
// can use them when evaluating its code
sandbox.pm.response.actualStatusValue = resp.status;
sandbox.pm.response.jsonData = resp.data;
// so, this is sorta lame: some of the original postman scripts
// convert json string to object explicitly, ..but axios already
// does that. So, we give those scripts a json string, which will
// be turned back into another object. /shrug
// Basically, this is to avoid having to make ANY changes to the
// original postman files, so that I can compare the results from
// postman vs. this program without any changes.
sandbox.responseBody = JSON.stringify(resp.data);
for(let i=0; i < item.event.length; i++) {
let event = item.event[i];
if (event.listen !== "test") {
continue;
}
let script = event.script.exec.join('\n');
if (script.length > 0) {
if (verboseMode) {
console.log(chalk.cyan("Test Script:"))
console.log(chalk.cyan(script));
console.log(chalk.cyan("--------"));
}
try {
await createVM().run(script);
} catch(err) {
printEnvironment();
log(error(`Test "${folder.name} - ${item.name}": tests failed! Quitting!`));
log(error(err));
log(error(`Ran ${sandbox.pm.testCounter} tests, with errors`));
process.exit(1);
}
}
}
}
// execute
program.parse();