Skip to content

Instantly share code, notes, and snippets.

@knbknb
Last active May 18, 2023 09:02
Show Gist options
  • Save knbknb/df83e975a3377ea78e5b0930d74689cd to your computer and use it in GitHub Desktop.
Save knbknb/df83e975a3377ea78e5b0930d74689cd to your computer and use it in GitHub Desktop.
JS: 3 Newman Scripts (Postman CLI tool)
const fs = require('fs');
const process = require('process');
const newman = require('newman'); // require newman in your project
// call this as node newman-as-node-module-write-to-disk.js
// simpler: How can machine_name and port_number can be passed dynamically to the Postman tests when using Newman?
// newman run my-collection.json --global-var "machineName=mymachine1234" --global-var "machinePort=8080"
// In your request builder, just use them as normal variables https://{{machineName}}:{‌{machinePort}}.
// call newman.run to pass `options` object and wait for callback
newman.run({
// environment, globals, iterationData...
collection: require('./my.postman_collection.json'),
reporters: 'cli'
}).on('beforeRequest', function (err, args) { // on start of run, log to console
if(err) {
console.error('beforeRequest: collection run encountered an error: ', err);
} else {
let fileName = new Date().toISOString().replace(/:/g, '-').replace(/\.\d+Z/g, '') + '.request.txt';
fs.writeFile(fileName, args.request.body.raw, function(err) {
if (err) console.log(err);
});
// only POST request body contains body.raw
console.log('before request...', args.request.body.raw);
}
}).on('request', function (err, summary) {
if (err || summary.error) {
console.error('collection run encountered an error.');
}
else {
let fileName = new Date().toISOString().replace(/:/g, '-').replace(/\.\d+Z/g, '') + '.response.txt';
fs.writeFile(fileName, summary.response.stream,
function(err) {
if (err) console.log(err);
});
console.log('request completed.', summary.response.code, summary.response.stream.toString());
}
});
var fs = require('fs'),
Collection = require('postman-collection').Collection,
myCollection;
const my_coll = 'mdis-v3-test23-samplemgmt.postman_collection.json';
myCollection = new Collection(JSON.parse
(fs.readFileSync(my_coll).toString()));
console.log(myCollection.toJSON());
let save_path_variables = () => {
/* array of path variables */
const path_variables = JSON.parse(JSON.stringify(pm.request.url));
let idx = 0;
for (prop of path_variables.variable){
if (prop.key === var_name && Number.isInteger(prop.value)){
pm.environment.set(`pathvar_${prop.key}`, prop.value)
}
idx++;
}
}
pm.environment.set("save_path_variables", save_path_variables.toString())
eval(pm.environment.get("save_path_variables").replace("var_name", "'project_id'"))()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment