Skip to content

Commit 3b88f3d

Browse files
committed
Archive k6 v0.44.0 JS API docs
1 parent 77a4fbc commit 3b88f3d

File tree

336 files changed

+16138
-1
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

336 files changed

+16138
-1
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
title: "Init context"
3+
excerpt: 'The init context (aka "init code") is code in the global context that has access to a few functions not accessible during main script execution.'
4+
---
5+
6+
Before the k6 starts the test logic, code in the _init context_ prepares the script.
7+
A few functions are available only in init context.
8+
For details about the runtime, refer to the [Test lifecycle](/using-k6/test-lifecycle).
9+
10+
| Function | Description |
11+
| ----------------------------------------------------------------------------------- | --------------------- |
12+
| [open( filePath, [mode] )](/javascript-api/init-context/open) | Opens a file and reads all the contents into memory. |
Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
---
2+
head_title: 'JavaScript API: open'
3+
title: 'open( filePath, [mode] )'
4+
description: 'Opens a file and reads all the contents into memory.'
5+
excerpt: 'Opens a file and reads all the contents into memory.'
6+
---
7+
8+
Opens a file, reading all its contents into memory for use in the script.
9+
10+
> #### Use [SharedArray](/javascript-api/k6-data/sharedarray/) for CSV and JSON files
11+
> `open()` often consumes a large amount of memory because every VU keeps a separate copy of the file in memory.
12+
> To reduce the memory consumption, we strongly advise the usage of [SharedArray](/javascript-api/k6-data/sharedarray/) for CSV, JSON and other files intended for script parametrization.
13+
14+
<blockquote mod='attention' title='Function available only in init context'>
15+
16+
This function can only be called from the init context (aka _init code_), code in the global context that is, outside of the main export default function { ... }.
17+
18+
By restricting it to the init context, we can easily determine what local files are needed to run the test and thus what we need to bundle up when distributing the test to multiple nodes in a clustered/distributed test.
19+
20+
See the example further down on this page. For a more in-depth description, see [Test lifecycle](/using-k6/test-lifecycle).
21+
22+
</blockquote>
23+
24+
| Parameter | Type | Description |
25+
| --------- | ------ | ------------------ |
26+
| filePath | string | The path to the file, absolute or relative, that will be read into memory. The file will only be loaded once, even when running with several VUs. |
27+
| mode | string | By default, the contents of the file are read as text, but if you specify `b`, the file will be read as binary data instead. |
28+
29+
### Returns
30+
31+
| Type | Description |
32+
| ---- | ----------- |
33+
| string / ArrayBuffer | The contents of the file, returned as string or ArrayBuffer (if `b` was specified as the mode). |
34+
35+
36+
<CodeGroup labels={["users.json"]}>
37+
38+
```json
39+
[
40+
{
41+
"username": "user1",
42+
"password": "password1"
43+
},
44+
{
45+
"username": "user2",
46+
"password": "password2"
47+
},
48+
{
49+
"username": "user3",
50+
"password": "password3"
51+
}
52+
]
53+
```
54+
55+
</CodeGroup>
56+
57+
<CodeGroup labels={["Loading JSON data with SharedArray to parameterize test"]}>
58+
59+
```javascript
60+
import { SharedArray } from 'k6/data';
61+
import { sleep } from 'k6';
62+
63+
const data = new SharedArray('users', function () {
64+
// here you can open files, and then do additional processing or generate the array with data dynamically
65+
const f = JSON.parse(open('./users.json'));
66+
return f; // f must be an array[]
67+
});
68+
69+
export default () => {
70+
const randomUser = data[Math.floor(Math.random() * data.length)];
71+
console.log(`${randomUser.username}, ${randomUser.password}`);
72+
sleep(3);
73+
};
74+
```
75+
76+
</CodeGroup>
77+
78+
<CodeGroup labels={["Loading JSON data without SharedArray"]}>
79+
80+
```javascript
81+
import { sleep } from 'k6';
82+
83+
const users = JSON.parse(open('./users.json')); // consider using SharedArray for large files
84+
85+
export default function () {
86+
const user = users[__VU - 1];
87+
console.log(`${user.username}, ${user.password}`);
88+
sleep(3);
89+
}
90+
```
91+
92+
</CodeGroup>
93+
94+
<CodeGroup labels={["Loading a binary file and POSTing it as a multipart request"]}>
95+
96+
```javascript
97+
import http from 'k6/http';
98+
import { sleep } from 'k6';
99+
100+
const binFile = open('/path/to/file.bin', 'b');
101+
102+
export default function () {
103+
const data = {
104+
field: 'this is a standard form field',
105+
file: http.file(binFile, 'test.bin'),
106+
};
107+
const res = http.post('https://example.com/upload', data);
108+
sleep(3);
109+
}
110+
```
111+
112+
</CodeGroup>
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
title: 'k6'
3+
excerpt: 'The k6 module contains k6-specific functionality.'
4+
---
5+
6+
The k6 module contains k6-specific functionality.
7+
8+
| Function | Description |
9+
| ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
10+
| [check(val, sets, [tags])](/javascript-api/k6/check) | Runs one or more checks on a value and generates a pass/fail result but does not throw errors or otherwise interrupt execution upon failure. |
11+
| [fail([err])](/javascript-api/k6/fail) | Throws an error, failing and aborting the current VU script iteration immediately. |
12+
| [group(name, fn)](/javascript-api/k6/group) | Runs code inside a group. Used to organize results in a test. |
13+
| [randomSeed(int)](/javascript-api/k6/randomseed) | Set seed to get a reproducible pseudo-random number using `Math.random`. |
14+
| [sleep(t)](/javascript-api/k6/sleep) | Suspends VU execution for the specified duration. |
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
---
2+
title: 'check( val, sets, [tags] )'
3+
description: 'Runs one or more checks on a value and generates a pass/fail result but does not throw errors or otherwise interrupt execution upon failure.'
4+
excerpt: 'Runs one or more checks on a value and generates a pass/fail result but does not throw errors or otherwise interrupt execution upon failure.'
5+
---
6+
7+
Run checks on a value. A check is a test condition that can give a truthy or
8+
falsy result. The `sets` parameter contains one or more checks, and the `check()`
9+
function will return `false` if any of them fail.
10+
11+
Note that checks are not _asserts_ in their traditional sense - a failed assertion
12+
will throw an error, while a check will always return with a pass or a failure.
13+
Failure conditions can then instead be controlled by thresholds, for more power and flexibility.
14+
15+
| Parameter | Type | Description |
16+
| --------------- | ------ | ---------------------------------------- |
17+
| val | any | Value to test. |
18+
| sets | object | Tests (checks) to run on the value. |
19+
| tags (optional) | object | Extra tags to attach to metrics emitted. |
20+
21+
### Returns
22+
23+
| Type | Description |
24+
| ------- | ------------------------------------------------------- |
25+
| boolean | `true` if all checks have succeeded, `false` otherwise. |
26+
27+
### Examples
28+
29+
Using `check()` to verify that an HTTP response code was 200:
30+
31+
<CodeGroup labels={[]}>
32+
33+
```javascript
34+
import http from 'k6/http';
35+
import { check } from 'k6';
36+
37+
export default function () {
38+
const res = http.get('https://httpbin.test.k6.io');
39+
check(res, {
40+
'response code was 200': (res) => res.status == 200,
41+
});
42+
}
43+
```
44+
45+
</CodeGroup>
46+
47+
Using `check()` with a custom tag to verify that an HTTP response code was 200 and that body was 1234 bytes. The `checkOutput` can be used for any condition in your script logic:
48+
49+
<CodeGroup labels={[]}>
50+
51+
```javascript
52+
import http from 'k6/http';
53+
import { check, fail } from 'k6';
54+
55+
export default function () {
56+
const res = http.get('https://httpbin.test.k6.io');
57+
const checkOutput = check(
58+
res,
59+
{
60+
'response code was 200': (res) => res.status == 200,
61+
'body size was 1234 bytes': (res) => res.body.length == 1234,
62+
},
63+
{ myTag: "I'm a tag" }
64+
);
65+
66+
if (!checkOutput) {
67+
fail('unexpected response');
68+
}
69+
}
70+
```
71+
72+
</CodeGroup>
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
---
2+
title: 'fail( [err] )'
3+
description: 'Throws an error, failing and aborting the current VU script iteration immediately.'
4+
excerpt: 'Throws an error, failing and aborting the current VU script iteration immediately.'
5+
---
6+
7+
Immediately throw an error, aborting the current iteration.
8+
9+
`fail()` does not abort the test, nor does it make the test exit with non-0 status.
10+
If you are looking to fail the test by halting the execution, use [test.abort()](/javascript-api/k6-execution/#test) instead
11+
12+
`fail()` is a simple convenience wrapper on top of JavaScript's `throw()`,
13+
because the latter cannot be used as `[expr] || throw`, which is a convenient way to write k6 test code.
14+
15+
| Parameter | Type | Description |
16+
| -------------- | ------ | ------------------------------------------ |
17+
| err (optional) | string | Error message that gets printed to stderr. |
18+
19+
### Example
20+
21+
Aborting the current script iteration if a check fails:
22+
23+
<CodeGroup labels={[]}>
24+
25+
```javascript
26+
import http from 'k6/http';
27+
import { check, fail } from 'k6';
28+
29+
export default function () {
30+
const res = http.get('https://k6.io');
31+
if (
32+
!check(res, {
33+
'status code MUST be 200': (res) => res.status == 200,
34+
})
35+
) {
36+
fail('status code was *not* 200');
37+
}
38+
}
39+
```
40+
41+
</CodeGroup>
Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
---
2+
title: 'group( name, fn )'
3+
description: 'Runs code inside a group. Used to organize results in a test.'
4+
excerpt: 'Runs code inside a group. Used to organize results in a test.'
5+
---
6+
7+
Run code inside a group. Groups are used to organize results in a test.
8+
9+
| Parameter | Type | Description |
10+
| --------- | -------- | ------------------------------------------------------ |
11+
| name | string | Name of the group. |
12+
| fn | function | Group body - code to be executed in the group context. |
13+
14+
### Returns
15+
16+
| Type | Description |
17+
| ---- | ------------------------- |
18+
| any | The return value of _fn_. |
19+
20+
<Blockquote mod="warning" title="Working with async functions">
21+
22+
Avoid using `group` with async functions or asynchronous code.
23+
If you do, k6 might apply tags in a way that is unreliable or unintuitive.
24+
25+
If you start promise chains or even use `await` within `group`, some code within the group will be waited for and tagged with the proper `group` tag, but others won't be.
26+
27+
To avoid confusion, `async` functions are forbidden as `group()` arguments. This still lets users make and chain promises within a group, but doing so is unsupported and not recommended.
28+
29+
For more information, refer to [k6 #2728](https://github.com/grafana/k6/issues/2728), which tracks possible solutions and provides detailed explanations.
30+
31+
</Blockquote>
32+
33+
### Example
34+
35+
<CodeGroup labels={[]}>
36+
37+
```javascript
38+
import { group } from 'k6';
39+
40+
export default function () {
41+
group('visit product listing page', function () {
42+
// ...
43+
});
44+
group('add several products to the shopping cart', function () {
45+
// ...
46+
});
47+
group('visit login page', function () {
48+
// ...
49+
});
50+
group('authenticate', function () {
51+
// ...
52+
});
53+
group('checkout process', function () {
54+
// ...
55+
});
56+
}
57+
```
58+
59+
</CodeGroup>
60+
61+
The above code will present the results separately depending on the group execution.
62+
63+
Learn more on [Groups and Tags](/using-k6/tags-and-groups).
64+
65+
64.6 KB
Loading
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
---
2+
title: 'randomSeed( int )'
3+
description: 'Set seed to get a reproducible pseudo-random number using `Math.random`.'
4+
excerpt: 'Set seed to get a reproducible pseudo-random number using `Math.random`.'
5+
---
6+
7+
Set seed to get a reproducible pseudo-random number using `Math.random`.
8+
9+
| Parameter | Type | Description |
10+
| --------- | ------- | --------------- |
11+
| int | integer | The seed value. |
12+
13+
### Example
14+
15+
Use `randomSeed` to get the same random number in all the iterations.
16+
17+
<CodeGroup labels={[]}>
18+
19+
```javascript
20+
import { randomSeed } from 'k6';
21+
22+
export const options = {
23+
vus: 10,
24+
duration: '5s',
25+
};
26+
27+
export default function () {
28+
randomSeed(123456789);
29+
const rnd = Math.random();
30+
console.log(rnd);
31+
}
32+
```
33+
34+
</CodeGroup>

0 commit comments

Comments
 (0)