Skip to content

Commit 65ff6c9

Browse files
authored
Replace legacy testing services from README and examples (#4517)
1 parent 8799c81 commit 65ff6c9

File tree

6 files changed

+89
-172
lines changed

6 files changed

+89
-172
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ export const options = {
7474

7575
// Simulated user behavior
7676
export default function () {
77-
let res = http.get("https://test-api.k6.io/public/crocodiles/1/");
77+
let res = http.get("https://quickpizza.grafana.com");
7878
// Validate response status
7979
check(res, { "status was 200": (r) => r.status == 200 });
8080
sleep(1);

Diff for: examples/experimental/redis.js

+54-58
Original file line numberDiff line numberDiff line change
@@ -1,87 +1,83 @@
1-
import { check } from "k6";
2-
import http from "k6/http";
3-
import redis from "k6/experimental/redis";
4-
import exec from "k6/execution";
5-
import { textSummary } from "https://jslib.k6.io/k6-summary/0.0.1/index.js";
1+
import { check } from 'k6';
2+
import http from 'k6/http';
3+
import redis from 'k6/experimental/redis';
4+
import exec from 'k6/execution';
5+
import { textSummary } from 'https://jslib.k6.io/k6-summary/0.0.2/index.js';
6+
67
export const options = {
78
scenarios: {
89
redisPerformance: {
9-
executor: "shared-iterations",
10+
executor: 'shared-iterations',
1011
vus: 10,
1112
iterations: 200,
12-
exec: "measureRedisPerformance",
13+
exec: 'measureRedisPerformance',
1314
},
1415
usingRedisData: {
15-
executor: "shared-iterations",
16+
executor: 'shared-iterations',
1617
vus: 10,
1718
iterations: 200,
18-
exec: "measureUsingRedisData",
19+
exec: 'measureUsingRedisData',
1920
},
2021
},
2122
};
22-
// Get the redis instance(s) address and password from the environment
23-
const redis_addrs = __ENV.REDIS_ADDRS || "";
24-
const redis_password = __ENV.REDIS_PASSWORD || "";
23+
2524
// Instantiate a new redis client
26-
const redisClient = new redis.Client({
27-
addrs: redis_addrs.split(",") || new Array("localhost:6379"), // in the form of 'host:port', separated by commas
28-
password: redis_password,
29-
});
30-
// Prepare an array of crocodile ids for later use
25+
const redisClient = new redis.Client(`redis://localhost:6379`);
26+
27+
// Prepare an array of rating ids for later use
3128
// in the context of the measureUsingRedisData function.
32-
const crocodileIDs = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
33-
export function measureRedisPerformance() {
29+
const ratingIDs = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
30+
31+
export async function measureRedisPerformance() {
3432
// VUs are executed in a parallel fashion,
3533
// thus, to ensure that parallel VUs are not
3634
// modifying the same key at the same time,
3735
// we use keys indexed by the VU id.
3836
const key = `foo-${exec.vu.idInTest}`;
39-
redisClient
40-
.set(`foo-${exec.vu.idInTest}`, 1)
41-
.then(() => redisClient.get(`foo-${exec.vu.idInTest}`))
42-
.then((value) => redisClient.incrBy(`foo-${exec.vu.idInTest}`, value))
43-
.then((_) => redisClient.del(`foo-${exec.vu.idInTest}`))
44-
.then((_) => redisClient.exists(`foo-${exec.vu.idInTest}`))
45-
.then((exists) => {
46-
if (exists !== 0) {
47-
throw new Error("foo should have been deleted");
48-
}
49-
});
37+
38+
await redisClient.set(key, 1);
39+
await redisClient.incrBy(key, 10);
40+
const value = await redisClient.get(key);
41+
if (value !== '11') {
42+
throw new Error('foo should have been incremented to 11');
43+
}
44+
45+
await redisClient.del(key);
46+
if ((await redisClient.exists(key)) !== 0) {
47+
throw new Error('foo should have been deleted');
48+
}
5049
}
51-
export function setup() {
52-
redisClient.sadd("crocodile_ids", ...crocodileIDs);
50+
51+
export async function setup() {
52+
await redisClient.sadd('rating_ids', ...ratingIDs);
5353
}
54-
export function measureUsingRedisData() {
55-
// Pick a random crocodile id from the dedicated redis set,
54+
55+
export async function measureUsingRedisData() {
56+
// Pick a random rating id from the dedicated redis set,
5657
// we have filled in setup().
57-
redisClient
58-
.srandmember("crocodile_ids")
59-
.then((randomID) => {
60-
const url = `https://test-api.k6.io/public/crocodiles/${randomID}`;
61-
const res = http.get(url);
62-
check(res, {
63-
"status is 200": (r) => r.status === 200,
64-
"content-type is application/json": (r) =>
65-
r.headers["content-type"] === "application/json",
66-
});
67-
return url;
68-
})
69-
.then((url) => redisClient.hincrby("k6_crocodile_fetched", url, 1));
58+
const randomID = await redisClient.srandmember('rating_ids');
59+
const url = `https://quickpizza.grafana.com/api/ratings/${randomID}`;
60+
const res = await http.asyncRequest('GET', url, {
61+
headers: { Authorization: 'token abcdef0123456789' },
62+
});
63+
64+
check(res, { 'status is 200': (r) => r.status === 200 });
65+
66+
await redisClient.hincrby('k6_rating_fetched', url, 1);
7067
}
71-
export function teardown() {
72-
redisClient.del("crocodile_ids");
68+
69+
export async function teardown() {
70+
await redisClient.del('rating_ids');
7371
}
72+
7473
export function handleSummary(data) {
7574
redisClient
76-
.hgetall("k6_crocodile_fetched")
77-
.then((fetched) =>
78-
Object.assign(data, { k6_crocodile_fetched: fetched })
79-
)
80-
.then((data) =>
81-
redisClient.set(`k6_report_${Date.now()}`, JSON.stringify(data))
82-
)
83-
.then(() => redisClient.del("k6_crocodile_fetched"));
75+
.hgetall('k6_rating_fetched')
76+
.then((fetched) => Object.assign(data, { k6_rating_fetched: fetched }))
77+
.then((data) => redisClient.set(`k6_report_${Date.now()}`, JSON.stringify(data)))
78+
.then(() => redisClient.del('k6_rating_fetched'));
79+
8480
return {
85-
stdout: textSummary(data, { indent: " ", enableColors: true }),
81+
stdout: textSummary(data, { indent: ' ', enableColors: true }),
8682
};
8783
}

Diff for: examples/experimental/websockets/test-api.k6.io.js

-58
This file was deleted.

Diff for: examples/experimental/ws.js

+32-53
Original file line numberDiff line numberDiff line change
@@ -1,76 +1,55 @@
1-
import {
2-
randomString,
3-
randomIntBetween,
4-
} from "https://jslib.k6.io/k6-utils/1.1.0/index.js";
5-
import { WebSocket } from "k6/experimental/websockets";
6-
import {
7-
setTimeout,
8-
clearTimeout,
9-
setInterval,
10-
clearInterval,
11-
} from "k6/timers";
1+
import { randomString, randomIntBetween } from 'https://jslib.k6.io/k6-utils/1.1.0/index.js';
2+
import { WebSocket } from 'k6/experimental/websockets';
123

13-
let chatRoomName = "publicRoom"; // choose your chat room name
14-
let sessionDuration = randomIntBetween(5000, 60000); // user session between 5s and 1m
4+
const sessionDuration = randomIntBetween(1000, 3000); // user session between 1s and 3s
155

16-
export default function() {
6+
export default function () {
177
for (let i = 0; i < 4; i++) {
188
startWSWorker(i);
199
}
2010
}
2111

2212
function startWSWorker(id) {
23-
let url = `wss://test-api.k6.io/ws/crocochat/${chatRoomName}/`;
24-
let ws = new WebSocket(url);
25-
ws.binaryType = "arraybuffer";
26-
ws.addEventListener("open", () => {
27-
ws.send(
28-
JSON.stringify({
29-
event: "SET_NAME",
30-
new_name: `Croc ${__VU}:${id}`,
31-
})
32-
);
33-
34-
ws.addEventListener("message", (e) => {
35-
let msg = JSON.parse(e.data);
36-
if (msg.event === "CHAT_MSG") {
37-
console.log(
38-
`VU ${__VU}:${id} received: ${msg.user} says: ${msg.message}`
39-
);
40-
} else if (msg.event === "ERROR") {
13+
// create a new websocket connection
14+
const ws = new WebSocket(`wss://quickpizza.grafana.com/ws`);
15+
ws.binaryType = 'arraybuffer';
16+
17+
ws.addEventListener('open', () => {
18+
// change the user name
19+
ws.send(JSON.stringify({ event: 'SET_NAME', new_name: `VU ${__VU}:${id}` }));
20+
21+
// listen for messages/errors and log them into console
22+
ws.addEventListener('message', (e) => {
23+
const msg = JSON.parse(e.data);
24+
if (msg.event === 'CHAT_MSG') {
25+
console.log(`VU ${__VU}:${id} received: ${msg.user} says: ${msg.message}`);
26+
} else if (msg.event === 'ERROR') {
4127
console.error(`VU ${__VU}:${id} received:: ${msg.message}`);
4228
} else {
43-
console.log(
44-
`VU ${__VU}:${id} received unhandled message: ${msg.message}`
45-
);
29+
console.log(`VU ${__VU}:${id} received unhandled message: ${msg.message}`);
4630
}
4731
});
4832

49-
let intervalId = setInterval(() => {
50-
ws.send(
51-
JSON.stringify({
52-
event: "SAY",
53-
message: `I'm saying ${randomString(5)}`,
54-
})
55-
);
56-
}, randomIntBetween(2000, 8000)); // say something every 2-8seconds
33+
// send a message every 2-8 seconds
34+
const intervalId = setInterval(() => {
35+
ws.send(JSON.stringify({ event: 'SAY', message: `I'm saying ${randomString(5)}` }));
36+
}, randomIntBetween(2000, 8000)); // say something every 2-8 seconds
5737

58-
let timeout1id = setTimeout(function() {
38+
// after a sessionDuration stop sending messages and leave the room
39+
const timeout1id = setTimeout(function () {
5940
clearInterval(intervalId);
60-
console.log(
61-
`VU ${__VU}:${id}: ${sessionDuration}ms passed, leaving the chat`
62-
);
63-
ws.send(JSON.stringify({ event: "LEAVE" }));
41+
console.log(`VU ${__VU}:${id}: ${sessionDuration}ms passed, leaving the chat`);
42+
ws.send(JSON.stringify({ event: 'LEAVE' }));
6443
}, sessionDuration);
6544

66-
let timeout2id = setTimeout(function() {
67-
console.log(
68-
`Closing the socket forcefully 3s after graceful LEAVE`
69-
);
45+
// after a sessionDuration + 3s close the connection
46+
const timeout2id = setTimeout(function () {
47+
console.log(`Closing the socket forcefully 3s after graceful LEAVE`);
7048
ws.close();
7149
}, sessionDuration + 3000);
7250

73-
ws.addEventListener("close", () => {
51+
// when connection is closing, clean up the previously created timers
52+
ws.addEventListener('close', () => {
7453
clearTimeout(timeout1id);
7554
clearTimeout(timeout2id);
7655
console.log(`VU ${__VU}:${id}: disconnected`);

Diff for: examples/http_2.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import http from "k6/http";
22
import { check } from "k6";
33

44
export default function () {
5-
check(http.get("https://test-api.k6.io/"), {
5+
check(http.get("https://quickpizza.grafana.com"), {
66
"status is 200": (r) => r.status == 200,
77
"protocol is HTTP/2": (r) => r.proto == "HTTP/2.0",
88
});

Diff for: examples/http_get.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import http from 'k6/http';
22

33
export default function () {
4-
http.get('https://test-api.k6.io/');
4+
http.get('https://quickpizza.grafana.com');
55
};

0 commit comments

Comments
 (0)