Skip to content

Commit

Permalink
chore: replace test services (#1060)
Browse files Browse the repository at this point in the history
* Replace first example

* Fix

* Remove all test-api mentions

* Remove all other examples
  • Loading branch information
federicotdn authored Feb 7, 2025
1 parent 25dfac6 commit b26d89a
Show file tree
Hide file tree
Showing 14 changed files with 158 additions and 173 deletions.
6 changes: 0 additions & 6 deletions src/components/ScriptExamplesMenu/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import AWS_AUTH_SCRIPT from './snippets/aws_auth.js?raw';
import BASIC_AUTH_SCRIPT from './snippets/basic_auth.js?raw';
// Browser
// import BROWSER_FILL_FORM_SCRIPT from './snippets/browser_fill_form.js?raw';
import DIGEST_AUTH_SCRIPT from './snippets/digest_auth.js?raw';
// Extracting values/tokens from form fields
import EXTRACT_TOKEN_SCRIPT from './snippets/extract_token_csrf.js?raw';
// Correlation
Expand Down Expand Up @@ -55,11 +54,6 @@ const AUTH_CHOICES = [
script: BASIC_AUTH_SCRIPT,
value: 'basic_auth.js',
},
{
label: 'Digest authentication',
script: DIGEST_AUTH_SCRIPT,
value: 'digest_auth.js',
},
{
label: 'NTLM authentication',
script: NTLM_AUTH_SCRIPT,
Expand Down
4 changes: 2 additions & 2 deletions src/components/ScriptExamplesMenu/snippets/access_cookie.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ export const options = {}

export default function () {
// Since this request redirects the `res.cookies` property won't contain the cookies
const res = http.get(
'https://httpbin.test.k6.io/cookies/set?name1=value1&name2=value2'
const res = http.post(
'https://quickpizza.grafana.com/api/cookies?name1=value1&name2=value2'
)
check(res, {
'status is 200': (r) => r.status === 200,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ export default function () {
fd.append('images', http.file(img2, 'image2.jpg', 'image/jpeg'))
fd.append('text', http.file(txt, 'text.txt', 'text/plain'))

const res = http.post('https://httpbin.test.k6.io/post', fd.body(), {
const res = http.post('https://quickpizza.grafana.com/api/post', fd.body(), {
headers: { 'Content-Type': 'multipart/form-data; boundary=' + fd.boundary },
})
check(res, {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,119 +1,125 @@
import http from 'k6/http'
import { check, group } from 'k6'
import { check, group, fail } from 'k6'

export const options = {}
export const options = {
vus: 1,
iterations: 1,
}

// Create a random string of given length
function randomString(length, charset = 'abcdefghijklmnopqrstuvwxyz') {
function randomString(length, charset = '') {
if (!charset) charset = 'abcdefghijklmnopqrstuvwxyz'
let res = ''
while (length--) {
res += charset[Math.floor(Math.random() * charset.length)]
}
while (length--) res += charset[(Math.random() * charset.length) | 0]
return res
}

// Set your own email or `${randomString(10)}@example.com`;
const USERNAME = `${randomString(10)}@example.com`
const PASSWORD = 'superCroc2019'

const BASE_URL = 'https://test-api.k6.io'
const USERNAME = `${randomString(10)}@example.com` // Set your own email or `${randomString(10)}@example.com`;
const PASSWORD = 'secret'
const BASE_URL = 'https://quickpizza.grafana.com'

// Register a new user and retrieve authentication token for subsequent API requests
export function setup() {
const res = http.post(`${BASE_URL}/user/register/`, {
first_name: 'Crocodile',
last_name: 'Owner',
username: USERNAME,
password: PASSWORD,
})
const res = http.post(
`${BASE_URL}/api/users`,
JSON.stringify({
username: USERNAME,
password: PASSWORD,
})
)

check(res, { 'created user': (r) => r.status === 201 })

const loginRes = http.post(`${BASE_URL}/auth/token/login/`, {
username: USERNAME,
password: PASSWORD,
})
const loginRes = http.post(
`${BASE_URL}/api/users/token/login?set_cookie=true`,
JSON.stringify({
username: USERNAME,
password: PASSWORD,
})
)

const authToken = loginRes.json('access')
check(authToken, { 'logged in successfully': () => authToken !== '' })
const authToken = loginRes.json('token')
check(authToken, { 'logged in successfully': () => authToken.length > 0 })

return authToken
return {token: authToken, cookies: http.cookieJar().cookiesForURL(BASE_URL)}
}

export default (authToken) => {
export default function (data) {
// copy cookies over to this VU
Object.entries(data.cookies).forEach(([k,v]) => { http.cookieJar().set(BASE_URL, k, v) })

// set the authorization header on the session for the subsequent requests
const requestConfigWithTag = (tag) => ({
headers: {
Authorization: `Bearer ${authToken}`,
Authorization: `Bearer ${data.authToken}`,
},
tags: Object.assign(
{},
{
name: 'PrivateCrocs',
name: 'PrivateRatings',
},
tag
),
})

let URL = `${BASE_URL}/my/crocodiles/`
let URL = `${BASE_URL}/api/ratings`

group('01. Create a new crocodile', () => {
group('01. Create a new rating', () => {
const payload = {
name: `Name ${randomString(10)}`,
sex: 'F',
date_of_birth: '2023-05-11',
stars: 2,
pizza_id: 1, // Pizza ID 1 already exists in the database.
}

const res = http.post(
URL,
payload,
JSON.stringify(payload),
requestConfigWithTag({ name: 'Create' })
)

if (check(res, { 'Croc created correctly': (r) => r.status === 201 })) {
URL = `${URL}${res.json('id')}/`
if (check(res, { 'Rating created correctly': (r) => r.status === 201 })) {
URL = `${URL}/${res.json('id')}`
} else {
console.log(`Unable to create a Croc ${res.status} ${res.body}`)
console.log(`Unable to create rating ${res.status} ${res.body}`)
return
}
})

group('02. Fetch private crocs', () => {
group('02. Fetch my ratings', () => {
const res = http.get(
`${BASE_URL}/my/crocodiles/`,
`${BASE_URL}/api/ratings`,
requestConfigWithTag({ name: 'Fetch' })
)
check(res, { 'retrieved crocs status': (r) => r.status === 200 })
check(res.json(), { 'retrieved crocs list': (r) => r.length > 0 })
check(res, { 'retrieve ratings status': (r) => r.status === 200 })
check(res.json(), { 'retrieved ratings list': (r) => r.ratings.length > 0 })
})

group('03. Update the croc', () => {
const payload = { name: 'New name' }
const res = http.patch(
group('03. Update the rating', () => {
const payload = { stars: 5 }
const res = http.put(
URL,
payload,
JSON.stringify({ stars: 5 }),
requestConfigWithTag({ name: 'Update' })
)
const isSuccessfulUpdate = check(res, {
'Update worked': () => res.status === 200,
'Updated name is correct': () => res.json('name') === 'New name',
'Updated stars number is correct': () => res.json('stars') === 5,
})

if (!isSuccessfulUpdate) {
console.log(`Unable to update the croc ${res.status} ${res.body}`)
console.log(`Unable to update the rating ${res.status} ${res.body}`)
return
}
})

group('04. Delete the croc', () => {
group('04. Delete the rating', () => {
const delRes = http.del(URL, null, requestConfigWithTag({ name: 'Delete' }))

const isSuccessfulDelete = check(null, {
'Croc was deleted correctly': () => delRes.status === 204,
'Rating was deleted correctly': () => delRes.status === 204,
})

if (!isSuccessfulDelete) {
console.log(`Croc was not deleted properly`)
console.log('Rating was not deleted properly')
return
}
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import http from 'k6/http'
import { describe, expect } from 'https://jslib.k6.io/k6chaijs/4.3.4.3/index.js'
import { Httpx } from 'https://jslib.k6.io/httpx/0.1.0/index.js'
import {
Expand All @@ -6,96 +7,110 @@ import {
randomString,
} from 'https://jslib.k6.io/k6-utils/1.2.0/index.js'

export const options = {}

// Set your own email
const USERNAME = `user${randomIntBetween(1, 100000)}@example.com`
const PASSWORD = 'superCroc2019'
export const options = {
// for the example, let's run only 1 VU with 1 iteration
vus: 1,
iterations: 1,
}

const session = new Httpx({ baseURL: 'https://test-api.k6.io' })
const USERNAME = `user${randomIntBetween(1, 100000)}@example.com` // Set your own email;
const PASSWORD = 'secretpassword'
const BASE_URL = 'https://quickpizza.grafana.com'
const session = new Httpx({ baseURL: BASE_URL })

// Register a new user and retrieve authentication token for subsequent API requests
export function setup() {
let authToken = null

describe(`setup - create a test user ${USERNAME}`, () => {
const resp = session.post(`/user/register/`, {
first_name: 'Crocodile',
last_name: 'Owner',
username: USERNAME,
password: PASSWORD,
})
const resp = session.post(
`/api/users`,
JSON.stringify({
username: USERNAME,
password: PASSWORD,
})
)

expect(resp.status, 'User create status').to.equal(201)
expect(resp, 'User create valid json response').to.have.validJsonBody()
})

describe(`setup - Authenticate the new user ${USERNAME}`, () => {
const resp = session.post(`/auth/token/login/`, {
username: USERNAME,
password: PASSWORD,
})
const resp = session.post(
`/api/users/token/login?set_cookie=true`,
JSON.stringify({
username: USERNAME,
password: PASSWORD,
})
)

expect(resp.status, 'Authenticate status').to.equal(200)
expect(resp, 'Authenticate valid json response').to.have.validJsonBody()
authToken = resp.json('access')
authToken = resp.json('token')
expect(authToken, 'Authentication token').to.be.a('string')
})

return authToken
return { token: authToken, cookies: http.cookieJar().cookiesForURL(BASE_URL) }
}

export default function (authToken) {
export default function (data) {
// copy cookies over to this VU
Object.entries(data.cookies).forEach(([k, v]) => {
http.cookieJar().set(BASE_URL, k, v)
})

// set the authorization header on the session for the subsequent requests
session.addHeader('Authorization', `Bearer ${authToken}`)
session.addHeader('Authorization', `Bearer ${data.authToken}`)

describe('01. Create a new crocodile', (t) => {
describe('01. Create a new rating', (t) => {
const payload = {
name: `Croc name ${randomString(10)}`,
sex: randomItem(['M', 'F']),
date_of_birth: '2023-05-11',
stars: 2,
pizza_id: 1, // Pizza ID 1 already exists in the database
}

session.addTag('name', 'Create')
const resp = session.post(`/my/crocodiles/`, payload)
const resp = session.post(`/api/ratings`, JSON.stringify(payload))

expect(resp.status, 'Croc creation status').to.equal(201)
expect(resp, 'Croc creation valid json response').to.have.validJsonBody()
expect(resp.status, 'Rating creation status').to.equal(201)
expect(resp, 'Rating creation valid json response').to.have.validJsonBody()

session.newCrocId = resp.json('id')
session.newRatingId = resp.json('id')
})

describe('02. Fetch private crocs', (t) => {
describe('02. Fetch my ratings', (t) => {
session.clearTag('name')
const resp = session.get('/my/crocodiles/')
const resp = session.get('/api/ratings')

expect(resp.status, 'Fetch croc status').to.equal(200)
expect(resp, 'Fetch croc valid json response').to.have.validJsonBody()
expect(resp.json().length, 'Number of crocs').to.be.above(0)
expect(resp.status, 'Fetch ratings status').to.equal(200)
expect(resp, 'Fetch ratings valid json response').to.have.validJsonBody()
expect(resp.json('ratings').length, 'Number of ratings').to.be.above(0)
})

describe('03. Update the croc', (t) => {
describe('03. Update the rating', (t) => {
const payload = {
name: `New croc name ${randomString(10)}`,
stars: 5,
}

const resp = session.patch(`/my/crocodiles/${session.newCrocId}/`, payload)
const resp = session.patch(
`/api/ratings/${session.newRatingId}`,
JSON.stringify(payload)
)

expect(resp.status, 'Croc patch status').to.equal(200)
expect(resp, 'Fetch croc valid json response').to.have.validJsonBody()
expect(resp.json('name'), 'Croc name').to.equal(payload.name)
expect(resp.status, 'Rating patch status').to.equal(200)
expect(resp, 'Fetch rating valid json response').to.have.validJsonBody()
expect(resp.json('stars'), 'Stars').to.equal(payload.stars)

// read "croc" again to verify the update worked
const resp1 = session.get(`/my/crocodiles/${session.newCrocId}/`)
// read rating again to verify the update worked
const resp1 = session.get(`/api/ratings/${session.newRatingId}`)

expect(resp1.status, 'Croc fetch status').to.equal(200)
expect(resp1, 'Fetch croc valid json response').to.have.validJsonBody()
expect(resp1.json('name'), 'Croc name').to.equal(payload.name)
expect(resp1.status, 'Fetch rating status').to.equal(200)
expect(resp1, 'Fetch rating valid json response').to.have.validJsonBody()
expect(resp1.json('stars'), 'Stars').to.equal(payload.stars)
})

describe('04. Delete the croc', (t) => {
const resp = session.delete(`/my/crocodiles/${session.newCrocId}/`)
describe('04. Delete the rating', (t) => {
const resp = session.delete(`/api/ratings/${session.newRatingId}`)

expect(resp.status, 'Croc delete status').to.equal(204)
expect(resp.status, 'Rating delete status').to.equal(204)
})
}
Loading

0 comments on commit b26d89a

Please sign in to comment.