No results for

Powered byAlgolia

Advanced API flow

suggest edits
advanced-example.js
1import http from 'k6/http';
2import { check, group, sleep, fail } from 'k6';
3
4export let options = {
5 stages: [{ target: 70, duration: '30s' }],
6 thresholds: {
7 http_req_duration: ['p(95)<500', 'p(99)<1500'],
8 'http_req_duration{name:PublicCrocs}': ['avg<400'],
9 'http_req_duration{name:Create}': ['avg<600', 'max<1000'],
10 },
11};
12
13function randomString(length) {
14 const charset = 'abcdefghijklmnopqrstuvwxyz';
15 let res = '';
16 while (length--) res += charset[(Math.random() * charset.length) | 0];
17 return res;
18}
19
20const USERNAME = `${randomString(10)}@example.com`; // Set your own email or `${randomString(10)}@example.com`;
21const PASSWORD = 'superCroc2019';
22const BASE_URL = 'https://test-api.k6.io';
23
24export function setup() {
25 // register a new user and authenticate via a Bearer token.
26 let res = http.post(`${BASE_URL}/user/register/`, {
27 first_name: 'Crocodile',
28 last_name: 'Owner',
29 username: USERNAME,
30 password: PASSWORD,
31 });
32
33 check(res, { 'created user': (r) => r.status === 201 });
34
35 let loginRes = http.post(`${BASE_URL}/auth/token/login/`, {
36 username: USERNAME,
37 password: PASSWORD,
38 });
39
40 let authToken = loginRes.json('access');
41 check(authToken, { 'logged in successfully': () => authToken !== '' });
42
43 return authToken;
44}
45
46export default (authToken) => {
47 const requestConfigWithTag = (tag) => ({
48 headers: {
49 Authorization: `Bearer ${authToken}`,
50 },
51 tags: Object.assign(
52 {},
53 {
54 name: 'PrivateCrocs',
55 },
56 tag,
57 ),
58 });
59
60 group('Public endpoints', () => {
61 // call some public endpoints in a batch
62 let responses = http.batch([
63 [
64 'GET',
65 `${BASE_URL}/public/crocodiles/1/`,
66 null,
67 { tags: { name: 'PublicCrocs' } },
68 ],
69 [
70 'GET',
71 `${BASE_URL}/public/crocodiles/2/`,
72 null,
73 { tags: { name: 'PublicCrocs' } },
74 ],
75 [
76 'GET',
77 `${BASE_URL}/public/crocodiles/3/`,
78 null,
79 { tags: { name: 'PublicCrocs' } },
80 ],
81 [
82 'GET',
83 `${BASE_URL}/public/crocodiles/4/`,
84 null,
85 { tags: { name: 'PublicCrocs' } },
86 ],
87 ]);
88
89 const ages = Object.values(responses).map((res) => res.json('age'));
90
91 // Functional test: check that all the public crocodiles are older than 5
92 check(ages, {
93 'Crocs are older than 5 years of age': Math.min(...ages) > 5,
94 });
95 });
96
97 group('Create and modify crocs', () => {
98 let URL = `${BASE_URL}/my/crocodiles/`;
99
100 group('Create crocs', () => {
101 const payload = {
102 name: `Name ${randomString(10)}`,
103 sex: 'M',
104 date_of_birth: '2001-01-01',
105 };
106
107 const res = http.post(
108 URL,
109 payload,
110 requestConfigWithTag({ name: 'Create' }),
111 );
112
113 if (check(res, { 'Croc created correctly': (r) => r.status === 201 })) {
114 URL = `${URL}${res.json('id')}/`;
115 } else {
116 console.log(`Unable to create a Croc ${res.status} ${res.body}`);
117 return;
118 }
119 });
120
121 group('Update croc', () => {
122 const payload = { name: 'New name' };
123 const res = http.patch(
124 URL,
125 payload,
126 requestConfigWithTag({ name: 'Update' }),
127 );
128 const isSuccessfulUpdate = check(res, {
129 'Update worked': () => res.status === 200,
130 'Updated name is correct': () => res.json('name') === 'New name',
131 });
132
133 if (!isSuccessfulUpdate) {
134 console.log(`Unable to update the croc ${res.status} ${res.body}`);
135 return;
136 }
137 });
138
139 const delRes = http.del(
140 URL,
141 null,
142 requestConfigWithTag({ name: 'Delete' }),
143 );
144
145 const isSuccessfulDelete = check(null, {
146 'Croc was deleted correctly': () => delRes.status === 204,
147 });
148
149 if (!isSuccessfulDelete) {
150 console.log(`Croc was not deleted properly`);
151 return;
152 }
153 });
154
155 sleep(1);
156};