Script API
The complete list of globals available to ::: pre and ::: post scripts, with their exact behavior. For a gentler introduction, read Scripts and tests first. The script editors suggest these globals and their members as you type, see autocompletion.
| Global | Pre-request | Post-response | Purpose |
|---|---|---|---|
req | Read and write | Read only | The request |
res | Not defined | Read only | The response |
vars | Read and write | Read and write | Variables of this run |
env | Read and write | Read and write | Session and environment variables |
test | Yes | Yes | Record a test |
expect | Yes | Yes | Assertions |
console | Yes | Yes | Output to the Console tab |
util | Yes | Yes | UUIDs, time, random values, encoders |
req
The request. In a pre-request script it is the request about to be sent, before {{ }} markers are replaced. In a post-response script it is the request exactly as it was sent: variables replaced, query string appended and automatic Content-Type included.
| Member | Type | Description |
|---|---|---|
req.method | string | The method, such as "GET". |
req.url | string | The URL. |
req.body | string | The body text. A form body reads as key=value&key2=value2, not yet percent-encoded. A request without a body reads as "". |
req.headers.get(name) | string or undefined | The value of the first enabled header with that name, ignoring case. |
req.headers.set(name, value) | Replaces the value of the header with that name (ignoring case, keeping its original spelling), or adds it. | |
req.headers.remove(name) | Removes every enabled header with that name, ignoring case. |
- In a pre-request script, assigning
req.method,req.urlorreq.bodychanges what is sent. Values are converted withString(value). - Assigning
req.bodyon a request whose file has no body section has no effect: the script cannot choose a body type. Add an empty::: body json(or another type) to the file first. - Disabled headers are invisible to the script and are kept unchanged in the request.
- Query parameters, scripts and docs are not visible to scripts. To change a query parameter, edit
req.url. - The Auth tab is applied after the pre-request script, so the header or parameter it adds is not in
reqthere, and variables the script sets withvars.set()reach its fields. The post-response script sees it inreq, as it was sent. - In a post-response script, every write throws, for example
req.url is read-only in a post scriptorheaders are read-only in a post script.
res
The response. Defined only in post-response scripts.
| Member | Type | Description |
|---|---|---|
res.status | number | The status code, such as 200. |
res.headers.get(name) | string or undefined | The value of the first header with that name, ignoring case. set and remove throw. |
res.body | string | The body as text, decoded as UTF-8. Invalid bytes are replaced. |
res.json() | any | JSON.parse(res.body). Throws if the body is not valid JSON. |
res.timeMs | number | Total time in milliseconds, from opening the connection to reading the last byte. |
res.size | number | Body size in bytes. |
res.json() parses the body on every call. In a script that reads many fields, parse once: const body = res.json();
vars
Variables that live for one run of one request. They have the highest priority when {{ }} markers are replaced.
| Member | Description |
|---|---|
vars.get(name) | The value, or undefined. Names are case sensitive. |
vars.set(name, value) | Sets a variable. The value is converted with String(value). |
Variables set in the pre-request script are used to fill the request and are readable in the post-response script of the same run. They are never written to disk and no other request sees them. There is no vars.unset.
env
The session environment: variables set by scripts since Postino started, on top of the active environment's files.
| Member | Description |
|---|---|
env.get(name) | The session value if a script set one, otherwise the value from the active environment (.local.env over .env), as written in the file, without expanding the variables it refers to, otherwise undefined. Names are case sensitive. |
env.set(name, value) | Sets a session variable. The value is converted with String(value). |
env.unset(name) | Removes the session variable, so the value from the environment files, if any, applies again. |
- Changes are applied after the script finishes, in the order they were made. They are visible to every later request until you quit Postino.
- They are never written to an
.envfile. The environment editor lists them as session. - In a load test, each virtual user has its own copy of the session, so a token set by one user's login is used by that same user's next requests.
test(name, fn)
Runs fn right away. If it returns, the test passes. If it throws, the test fails with the error's message (or String(error) when something other than an Error is thrown). Either way the script continues with the next statement.
test("has a next page cursor", () => {
const cursor = res.json().next;
if (!cursor) {
throw new Error("no cursor in the response");
}
env.set("cursor", cursor);
});Tests are synchronous. A function that returns a promise is considered passed when it returns.
expect(value)
Returns a set of matchers. A matcher throws when its condition does not hold, which fails the surrounding test(). expect(value).not returns the same matchers with the condition inverted.
| Matcher | Passes when | Failure message |
|---|---|---|
toBe(expected) | value === expected | expected 404 to be 200 |
toEqual(expected) | JSON.stringify(value) === JSON.stringify(expected) | expected {"a":1} to equal {"a":2} |
toBeTruthy() | Boolean(value) is true | expected "" to be truthy |
toBeFalsy() | !value is true | expected 1 to be falsy |
toContain(item) | value is a string containing item, or an array containing it (===) | expected "abc" to contain "z". Throws toContain needs a string or an array for other types. |
toMatch(pattern) | String(value) matches the regular expression, or the string turned into one | expected "x" to match /\d+/ |
toBeGreaterThan(n) | value > n | expected 3 to be greater than 5 |
toBeLessThan(n) | value < n | expected 900 to be less than 500 |
toHaveProperty(name) | value has an own property name | expected {} to have property "id" |
With .not, the message includes the word not: expected 200 not to be 200.
toEqual compares JSON text, so the order of keys matters: {a: 1, b: 2} does not equal {b: 2, a: 1}. Compare fields one by one when the order is not guaranteed.
console
console.log(), console.info(), console.warn() and console.error() each add one line to the Console tab, tagged with the level, the time and the script line of the call. Arguments are joined with a space; strings are printed as they are, anything else with JSON.stringify, falling back to String(value).
util
The template functions, callable from code. Same implementation, same results, same error messages.
| Function | Returns |
|---|---|
util.uuid() | string, a random UUID v4 |
util.now() | number, milliseconds since the Unix epoch |
util.isoDate() | string, the current UTC time in RFC 3339 |
util.randomInt(min, max) | number, an integer between min and max, both included |
util.randomString(len) | string of letters and digits, at most 1,048,576 characters. Throws on a longer or negative length |
util.base64Encode(str) | string |
util.base64Decode(str) | string. Throws on invalid Base64 or non UTF-8 output |
util.urlEncode(str) | string, percent-encoded |
A bad call, such as an unknown function, the wrong number of arguments or the wrong type, throws an Error.
Execution rules
| Rule | Detail |
|---|---|
| Engine | QuickJS, standard ECMAScript. |
| Isolation | A new runtime for every script run. Nothing survives between runs except env changes. |
| Not available | Network, files, timers, modules, require, import, fetch, setTimeout, crypto. |
| Memory | 32 MiB per run. |
| Time | 5 seconds per run. |
| Empty script | Skipped without starting the engine. |
| Error in pre-request | The run stops. Nothing is sent. |
| Error in post-response | Reported. The response, the tests and the console lines produced so far are kept. |