Postman Script: Difference between revisions

From Chorke Wiki
Jump to navigation Jump to search
 
(38 intermediate revisions by the same user not shown)
Line 11: Line 11:
  '''local      :''' pm.variables.unset("key");
  '''local      :''' pm.variables.unset("key");
|}
|}
==Script Request==
<source lang="js">
// GET Request
pm.sendRequest(activityInstanceURL, function (err, response) {
    activityInstance = response.json();
    // console.info(activityInstance);
});
</source>
<source lang="js">
//  POST Request
var payload = {
        'processInstanceIdIn': [processId],
        'sorting'            : [{
            'sortBy'  : 'variableName',
            'sortOrder': 'asc'
        }]
    },
    options = {
        url  :  variableInstanceURL,
        method: 'POST',
        header: {
            'Accept'      : '*/*',
            'Cookie'        : cookie,
            'Content-Type': 'application/json'
        },
        body  : {
            mode: 'raw',
            raw : JSON.stringify(payload)
        }
    };
pm.sendRequest(options, function (err, response) {
    variables = response.json();
    //console.log(variables);
});
</source>


==Before Request==
==Before Request==
<source lang="js">
let envBasedId = parseInt(pm.environment.get("env-based-id"));
var payload    = JSON.parse(pm.request.body.raw);
payload.id    = envBasedId;
let raw = JSON.stringify(payload);
pm.request.body.raw = raw;
</source>
<source lang="js">
<source lang="js">
var moment = require("moment"),
var moment = require("moment"),
Line 24: Line 72:
     };
     };
init(console, pm, moment, new Date());
init(console, pm, moment, new Date());
</source>
<source lang="js">
var moment    = require("moment"),
    format    = 'DD/MMM/YYYY',
    today    = new Date(),
    startDate = moment(today).format(format),
    endDate  = moment(today).add(1, 'years').format(format),
    keys      = {startDate: 'startDate', endDate: 'endDate'},
    preRequest= function(cli){
        pm.variables.set(keys.startDate, startDate);
        pm.variables.set(keys.endDate, endDate);
       
        cli.info(`${keys.startDate}: ${startDate}`);
        cli.info(`${keys.endDate}: ${endDate}`);
    },
    init      = function(cli){
        preRequest(cli)
    };
init(console);
</source>
</source>


==After Request==
==After Request==
<source lang="js">
pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
</source>
<source lang="js">
pm.test("Request & Response id match", function () {
    let envBasedId = parseInt(pm.environment.get("env-based-id"));
    pm.expect(pm.response.json().id).to.eql(envBasedId);
});
</source>
<source lang="js">
<source lang="js">
pm.test("Successful Quotation", function () {
pm.test("Successful Quotation", function () {
Line 95: Line 176:
init(console, pm, moment);
init(console, pm, moment);
</source>
</source>
==Playground==
{|
| valign="top" |
<source lang="js">
pm.request.body.formdata
pm.request.body.options
pm.request.body.raw
pm.request.header
pm.request.method
pm.request.body
pm.request.url
</source>
| valign="top" |
<source lang="js">
pm.request.body.mode = "raw";
pm.request.body.raw  = JSON.stringify({
    id      : 1,
    name    : "Chorke, Inc.",
    license  : "Incorporation",
    trademark: "Chorke"
});
</source>
| valign="top" |
<source lang="js">
pm.request.body.mode    = "formdata";
pm.request.body.formdata = [
    {type: "text", key: "name", value: "Chorke, Inc."      },
    {type: "file", key: "logo",  src: "/file/path/name.ext"},
    {type: "file", key: "sign", value: {name: "sign.png",
    type: "application/pdf", content: atob("<base64>")    }}
];
</source>
|-
| colspan="3" |
----
|-
| valign="top" |
| valign="top" |
| valign="top" |
|}
==Knowledge==
{|
| valign="top" |
npm install -g newman
npm install -g moment
npm install -g path
npm install -g fs
| valign="top" |
<source lang="js">
pm.test("Check values", () => {
    pm.expect(pm.response.json().id).to.not.eql(null);
    pm.expect(pm.response.json().category.name).to.not.eql("");
});
</source>
| valign="top" |
<source lang="js">
pm.test("XSRF token checking", () => {
    pm.expect(pm.cookies.get('XSRF-TOKEN')).to.not.eql(null);
    pm.environment.set('xsrf-token' pm.cookies.get('XSRF-TOKEN'));
});
</source>
|-
| colspan="3" |
----
|-
| valign="top" |
| valign="top" |
| valign="top" |
|}


==References==
==References==
{|
{|
| valign="top" |
| valign="top" |
* [https://momentjscom.readthedocs.io/en/latest/moment/03-manipulating/02-subtract/ Postman Subtract time using Moment.js]
* [https://momentjscom.readthedocs.io/en/latest/moment/03-manipulating/02-subtract/ Postman subtract time using Moment.js]
* [https://stackoverflow.com/questions/29861699/ Postman formate date using Moment.js]
* [https://stackoverflow.com/questions/29861699/ Postman formate date using Moment.js]
* [https://learning.postman.com/docs/writing-scripts/pre-request-scripts/ Postman Writing pre-request scripts]
* [https://learning.postman.com/docs/writing-scripts/pre-request-scripts/ Postman writing pre-request scripts]
* [https://stackoverflow.com/questions/49637741/ Postman add time using Moment.js]
* [https://stackoverflow.com/questions/49637741/ Postman add time using Moment.js]
* [https://learning.postman.com/docs/writing-scripts/script-references/test-examples/ Postman Test script examples]
* [https://learning.postman.com/docs/writing-scripts/script-references/test-examples/ Postman test script examples]
* [https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/ Postman JavaScript reference]
* [https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/ Postman JavaScript reference]
* [https://learning.postman.com/docs/writing-scripts/script-references/variables-list/ Postman dynamic variables]
* [https://learning.postman.com/docs/writing-scripts/script-references/variables-list/ Postman dynamic variables]
* [https://learning.postman.com/docs/sending-requests/variables/#variable-scopes Postman Variable Scopes]
* [https://learning.postman.com/docs/sending-requests/variables/#variable-scopes Postman variable scopes]
* [https://learning.postman.com/docs/writing-scripts/test-scripts/ Postman Writing tests]
* [https://learning.postman.com/docs/writing-scripts/test-scripts/ Postman writing tests]
* [https://learning.postman.com/docs/writing-scripts/intro-to-scripts/ Scripting in Postman]
* [https://learning.postman.com/docs/writing-scripts/intro-to-scripts/ Scripting in Postman]


| valign="top" |
| valign="top" |
* [https://learning.postman.com/labs/postman-flows/getting-started/working-with-access-tokens/ Postman Flows » Durables » Working with access tokens]
* [https://learning.postman.com/labs/postman-flows/getting-started/running-requests-in-sequence/ Postman Flows » Running Requests in Sequence]
* [https://learning.postman.com/docs/sending-requests/variables/#defining-variables-in-scripts Defining variables with scope in scripts]
* [https://learning.postman.com/docs/sending-requests/variables/#defining-variables-in-scripts Defining variables with scope in scripts]
* [https://learning.postman.com/docs/sending-requests/variables/#sharing-and-persisting-data Postman sharing and persisting data]
* [https://learning.postman.com/docs/sending-requests/variables/#sharing-and-persisting-data Postman sharing and persisting data]
* [https://handlebarsjs.com/guide/ Postman Visualize » Handlebars]
* [https://learning.postman.com/docs/sending-requests/visualizer/ Postman visualizing response]
* [https://github.com/postmanlabs/postman-app-support/issues/3033 Postman » Write to a file]
* [https://github.com/postmanlabs/newman Postman » Newman]
* [[NPM]]
* [[Yarn]]
| valign="top" |
* [https://community.postman.com/t/how-to-add-file-in-a-pre-request-script-using-form-data/18236 Postman » Add file in a Pre-request script]
* [https://medium.com/hackernoon/automatically-set-csrf-token-in-postman-django-tips-c9ec8eb9eb5b Postman » Automatically Set CSRF Token]
* [https://stackoverflow.com/questions/16015548/ Postman » Multipart/form-data request]
* [https://community.postman.com/t/how-to-verify-my-value-is-greater-than-or-not/24689/2 Postman » Verify value is Greater than]
* [https://community.postman.com/t/console-response-header-value-how-to-retrieve/26207/6 Postman » Retrieve Response Header]
* [https://community.postman.com/t/stop-request-from-sending-if-pre-request-test-fails/2066  Postman » Pre-request Test Fails]
* [https://www.baeldung.com/postman-send-csrf-token Postman » Sending CSRF Token]
* [https://stackoverflow.com/questions/50715532/ Postman » JSON POST Request]
* [https://stackoverflow.com/questions/27182701/ Postman » Handle CSRF token]
|-
| colspan="3" |
----
|-
| valign="top" |
* [[JavaScript Proprietary Library Example]]
* [[JavaScript Ali Express Discounted Cart]]
* [[JSON Schema Validation]]
* [https://github.com/jgraph/drawio-desktop DrawIO Desktop]
* [[Maven]]
* [[Rhino]]
* [[ExtJS]]
* [[J2V8]]
* [[Ant]]
* [[Ivy]]
| valign="top" |
* [[How to build Proprietary JavaScript Library]]
* [[HTTP Security]]
* [[Nashorn]]
* [[Base64]]
* [[JQ Tool]]
* [[XPath]]
| valign="top" |


|}
|}

Latest revision as of 00:37, 7 February 2024

global     : pm.globals.set("key", "value");
collection : pm.collectionVariables.set("key", "value");
environment: pm.environment.set("key", "value");
local      : pm.variables.set("key", "value");
global     : pm.globals.unset("key");
collection : pm.collectionVariables.unset("key");
environment: pm.environment.unset("key");
local      : pm.variables.unset("key");

Script Request

// GET Request
pm.sendRequest(activityInstanceURL, function (err, response) {
    activityInstance = response.json();
    // console.info(activityInstance);
});
//  POST Request
var payload = {
        'processInstanceIdIn': [processId],
        'sorting'            : [{
            'sortBy'   : 'variableName',
            'sortOrder': 'asc'
        }]
    },
    options = {
        url   :  variableInstanceURL, 
        method: 'POST',
        header: {
            'Accept'      : '*/*',
            'Cookie'        : cookie,
            'Content-Type': 'application/json'
        },
        body  : {
            mode: 'raw',
            raw : JSON.stringify(payload)
        }
    };

pm.sendRequest(options, function (err, response) {
    variables = response.json();
    //console.log(variables);
});

Before Request

let envBasedId = parseInt(pm.environment.get("env-based-id"));
var payload    = JSON.parse(pm.request.body.raw);
payload.id     = envBasedId;

let raw = JSON.stringify(payload);
pm.request.body.raw = raw;
var moment = require("moment"),
    init   = function(cli, ide, eon, today, birthDateMin, birthDateMax){
        birthDateMin = eon(today).subtract(18, 'years').add(1, 'days').format("DD/MM/YYYY");
        birthDateMax = eon(today).subtract(66, 'years').format("DD/MM/YYYY");
        ide.variables.set('adult.birth.date.invalid.min', birthDateMin);
        ide.variables.set('adult.birth.date.invalid.max', birthDateMax);
        cli.info(`adult.birth.date.invalid.min: ${birthDateMin}`);
        cli.info(`adult.birth.date.invalid.max: ${birthDateMax}`);
    };
init(console, pm, moment, new Date());
var moment    = require("moment"),
    format    = 'DD/MMM/YYYY',
    today     = new Date(),
    startDate = moment(today).format(format),
    endDate   = moment(today).add(1, 'years').format(format),
    keys      = {startDate: 'startDate', endDate: 'endDate'},
    preRequest= function(cli){
        pm.variables.set(keys.startDate, startDate);
        pm.variables.set(keys.endDate, endDate);
        
        cli.info(`${keys.startDate}: ${startDate}`);
        cli.info(`${keys.endDate}: ${endDate}`);
    },
    init      = function(cli){
        preRequest(cli)
    };
init(console);

After Request

pm.test("Status code is 200", function () {
    pm.response.to.have.status(200);
});
pm.test("Request & Response id match", function () {
    let envBasedId = parseInt(pm.environment.get("env-based-id"));
    pm.expect(pm.response.json().id).to.eql(envBasedId);
});
pm.test("Successful Quotation", function () {
    pm.response.to.have.status(200);
    pm.expect(pm.response.json().message).to.eql("Quotation has been created successfully.");
    pm.collectionVariables.set("quotationRefId", pm.response.json().refId);
});

OOP Script

var moment = require("moment"),
    init   = function(console, postman, moment, birthDate, debug){
        birthDate = new AdultBirthDate(console, postman, moment);
        birthDate.setUserVars(debug);
    };

const CHRONO_UNIT = { YEARS : 'years', DAYS  : 'days' },
      DATE_FORMAT = { DD_MM_YYY: 'DD/MM/YYYY' },
      USER_VARS   = { BIRTH_DATE: {
        VALID   : {
            MAX: 'adult.birth.date.valid.max',
            MIN: 'adult.birth.date.valid.min'
        },
        INVALID : {
            MAX: 'adult.birth.date.invalid.max',
            MIN: 'adult.birth.date.invalid.min'
        }
    }};

class AdultBirthDate {
    constructor(console, postman, moment){
        this.cli = console;
        this.ide = postman;
        this.eon = moment;
    }
    
    get validMinDate(){
        return this.eon(new Date()).subtract(18, CHRONO_UNIT.YEARS).format(DATE_FORMAT.DD_MM_YYY);
    }
    get validMaxDate(){
        return this.eon(new Date()).subtract(66, CHRONO_UNIT.YEARS).add(1, CHRONO_UNIT.DAYS).format(DATE_FORMAT.DD_MM_YYY);
    }
    get invalidMinDate(){
        return this.eon(new Date()).subtract(18, CHRONO_UNIT.YEARS).add(1, CHRONO_UNIT.DAYS).format(DATE_FORMAT.DD_MM_YYY);
    }
    get invalidMaxDate(){
        return this.eon(new Date()).subtract(66, CHRONO_UNIT.YEARS).format(DATE_FORMAT.DD_MM_YYY);
    }

    setUserVars(debug){
        debug && this.info();
        this.ide.variables.set(USER_VARS.BIRTH_DATE.VALID.MAX,   this.validMaxDate);
        this.ide.variables.set(USER_VARS.BIRTH_DATE.VALID.MIN,   this.validMinDate);
        this.ide.variables.set(USER_VARS.BIRTH_DATE.INVALID.MAX, this.invalidMaxDate);
        this.ide.variables.set(USER_VARS.BIRTH_DATE.INVALID.MIN, this.invalidMinDate);
    }

    info(message){
        message  = `${USER_VARS.BIRTH_DATE.VALID.MAX}  : ${this.validMaxDate}\n`;
        message += `${USER_VARS.BIRTH_DATE.VALID.MIN}  : ${this.validMinDate}\n`;
        message += `${USER_VARS.BIRTH_DATE.INVALID.MAX}: ${this.invalidMaxDate}\n`;
        message += `${USER_VARS.BIRTH_DATE.INVALID.MIN}: ${this.invalidMinDate}`;
        this.cli.info(message);
    }
}

init(console, pm, moment);

Playground

pm.request.body.formdata
pm.request.body.options
pm.request.body.raw
pm.request.header
pm.request.method
pm.request.body
pm.request.url
pm.request.body.mode = "raw";
pm.request.body.raw  = JSON.stringify({
    id       : 1,
    name     : "Chorke, Inc.",
    license  : "Incorporation",
    trademark: "Chorke"
});
pm.request.body.mode     = "formdata";
pm.request.body.formdata = [
    {type: "text", key: "name", value: "Chorke, Inc."       },
    {type: "file", key: "logo",   src: "/file/path/name.ext"},
    {type: "file", key: "sign", value: {name: "sign.png",
     type: "application/pdf", content: atob("<base64>")    }}
];

Knowledge

npm install -g newman
npm install -g moment
npm install -g path
npm install -g fs
pm.test("Check values", () => {
    pm.expect(pm.response.json().id).to.not.eql(null);
    pm.expect(pm.response.json().category.name).to.not.eql("");
});
pm.test("XSRF token checking", () => {
    pm.expect(pm.cookies.get('XSRF-TOKEN')).to.not.eql(null);
    pm.environment.set('xsrf-token' pm.cookies.get('XSRF-TOKEN'));
});

References