Skip to content

Commit

Permalink
Extended pm.request with headers, url, method, name, id, body, body.r…
Browse files Browse the repository at this point in the history
…aw (#138)

* Extended pm.request with headers, url, method, name, id, body, body.raw
  • Loading branch information
thim81 authored Aug 18, 2024
1 parent e5dbfec commit d197c6e
Show file tree
Hide file tree
Showing 4 changed files with 258 additions and 32 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased](https://github.com/apideck-libraries/postman-to-k6/compare/v1.8.7...HEAD)

- Extended pm.request with support for headers, url, method, name, id, body, body.raw

## [1.12.0] - 2024-07-31

- Fix initialization of headers for each K6 request (#98)
Expand Down
9 changes: 3 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -317,16 +317,13 @@ $ postman-to-k6 example/v2/echo.json -o k6-script.js
## Unsupported Features

- Sending requests from scripts using `pm.sendRequest`.
- Controlling request execution order using `postman.setNextRequest`.
- Controlling request execution order using [`postman.setNextRequest`](https://github.com/apideck-libraries/postman-to-k6/discussions/135#discussioncomment-10229573).
- Cookie properties, like `hostOnly`, `session`, and `storeId`.
- Textual response messages:
- `responseCode.name`
- `responseCode.detail`
- Postman methods:
- `pm.response.reason`
- `pm.response.to.have.status(reason)`
- `pm.response.to.not.have.status(reason)`
- Properties returning Postman classes:
- `pm.request.url` `pm.request.headers`
- `pm.request.auth`
- The Hawk authentication method.
- Deprecated `xmlToJson` method.
- Request IDs are changed. Postman doesn't provide them in the export, so we have to generate new ones.
Expand Down
106 changes: 102 additions & 4 deletions lib/shim/core.js
Original file line number Diff line number Diff line change
Expand Up @@ -453,11 +453,52 @@ const pm = Object.freeze({

/* Request information */
request: Object.freeze({
get data() {
return store.request.data;
},
get headers() {
throw new Error('pm.request.headers not supported');
if (
!store.request ||
typeof store.request.headers !== 'object' ||
store.request.headers === null
) {
return []; // Return an empty array if headers are not available or invalid
}

return Object.entries(store.request.headers).map(([key, value]) => ({
key: key,
value: value,
}));
},
get id() {
return store.request.id;
},
get method() {
return store.request.method;
},
get name() {
return store.request.name;
},
get url() {
throw new Error('pm.request.url not supported');
if (store.request.url) {
return parseUrl(store.request.url);
}
},
get auth() {
console.warn('pm.request.auth is not supported by postman-to-k6');
},
get body() {
let body;
if (store.request.body && typeof store.request.body === 'string') {
body = { raw: store.request.body, mode: 'raw' };
} else if (store.request.data && typeof store.request.data === 'object') {
let items = Object.entries(store.request.data).map(([key, value]) => ({
key: key,
value: value,
}));
body = { urlencoded: items, mode: 'urlencoded' };
}
return body;
},
}),

Expand Down Expand Up @@ -908,6 +949,9 @@ const request = Object.freeze({
get url() {
return store.request.url;
},
get body() {
return store.request.body;
},
});

/* responseCode */
Expand Down Expand Up @@ -946,6 +990,49 @@ function parseBodyJson() {
}
}

function parseUrl(url) {
// Use a regular expression to parse the URL
const urlPattern = /^(https?):\/\/([^\/:]+)(?::(\d+))?(\/[^\?]*)?\??([^#]*)#?(.*)?$/;
const match = urlPattern.exec(url);

if (!match) {
return undefined;
}

const protocol = match[1];
const host = match[2].split('.');
const port = match[3] || (protocol === 'http' ? '80' : '443');
const path = match[4] ? match[4].split('/').filter(Boolean) : [];
const queryString = match[5];
const fragment = match[6];

// Parse the query string into an array of objects { key: value }
const queryParams = queryString
? queryString.split('&').map(param => {
const [key, value] = param.split('=');
return {
key: decodeURIComponent(key),
value: decodeURIComponent(value),
};
})
: [];

// Parse path variables (assuming variables are denoted by ":variableName")
const variableParts = path
.filter(part => part.startsWith(':'))
.map(part => part.slice(1));

return {
protocol: protocol,
port: port,
path: path,
host: host,
query: queryParams,
variable: variableParts,
fragment: fragment || '',
};
}

function deepEqual(x, y) {
// From https://stackoverflow.com/a/32922084/10086414
const ok = Object.keys;
Expand Down Expand Up @@ -1028,8 +1115,11 @@ function executeRequest({
post,
}) {
try {
enterRequest(name, id, method, address, data, headers);
// Prepare Postman request data
enterRequest(name, id, method, address, data, headers, options);
// Convert Postman PreRequest
executePrerequest(postman[Pre], pre);
// Prepare Request config
const config = makeRequestConfig(
method,
address,
Expand All @@ -1041,11 +1131,16 @@ function executeRequest({
if (auth) {
auth(config, Var);
}
// Convert to K6 request arguments
const args = makeRequestArgs(config);
// Execute K6 requests
const response = http.request(...args);
if (post) {
// Prepare response data
enterPost(response);
// Convert Postman PostRequest
executePostrequest(postman[Post], post, response);
// Convert Postman Tests
executeTests();
}
return response;
Expand Down Expand Up @@ -1078,6 +1173,7 @@ function makeRequestConfig(method, address, data, headers, options, tags) {
} else {
config.data = {};
}

if (headers) {
for (const key of Object.keys(headers)) {
headers[key] = evaluate(headers[key]);
Expand Down Expand Up @@ -1156,7 +1252,9 @@ function enterRequest(name, id, method, address, data, headers) {
if (address) {
store.request.url = address;
}
if (data && typeof data === 'object') {
if (data && typeof data === 'string') {
store.request.body = data;
} else if (data && typeof data === 'object') {
store.request.data = Object.freeze(Object.assign({}, data));
}
if (headers) {
Expand Down
Loading

0 comments on commit d197c6e

Please sign in to comment.