Skip to content

Instantly share code, notes, and snippets.

@sphinxid
Created April 19, 2025 09:52
Show Gist options
  • Save sphinxid/c19a0eadef797d24fcbb2d3ac449595a to your computer and use it in GitHub Desktop.
Save sphinxid/c19a0eadef797d24fcbb2d3ac449595a to your computer and use it in GitHub Desktop.
k6 script to do load test on wordpress page. it will try to gather all the wordpress urls from the sitemaps then do a random visit to those urls. (20% traffic to home and 80% traffic to those random urls)
import http from 'k6/http';
import { check, sleep } from 'k6';
import { parseHTML } from 'k6/html';
// CHANGE THIS TO YOUR WORDPRESS URL
const BASE_URL = 'https://wordpress.com/blog/';
const SITEMAP_INDEX_URL = `${BASE_URL}/sitemap.xml`;
export const options = {
scenarios: {
ramping_vus: {
executor: 'ramping-vus',
startVUs: 100,
stages: [
{ target: 100, duration: '0s' },
{ target: 1000, duration: '10m' },
],
gracefulRampDown: '0s',
},
},
thresholds: {
http_req_duration: ['p(95)<2000'], // 95% of requests should be below 2s
},
};
function isSitemapIndex(xml) {
// Detect if XML is a sitemap index by checking for <sitemapindex>
return xml.includes('<sitemapindex');
}
function parseSitemapIndex(xml) {
const doc = parseHTML(xml);
const locs = [];
doc.find('sitemap > loc').toArray().forEach((el) => {
locs.push(el.text());
});
return locs;
}
function parseSitemapUrls(xml) {
const doc = parseHTML(xml);
const urls = [];
doc.find('url > loc').toArray().forEach((el) => {
urls.push(el.text());
});
return urls;
}
function fetchAllUrlsFromSitemap(url) {
let urls = [];
const res = http.get(url);
if (!res || res.status !== 200) {
return urls;
}
const xml = res.body;
if (isSitemapIndex(xml)) {
// Recursively follow sitemap indexes
const subSitemaps = parseSitemapIndex(xml);
subSitemaps.forEach((subUrl) => {
urls = urls.concat(fetchAllUrlsFromSitemap(subUrl));
});
} else {
urls = urls.concat(parseSitemapUrls(xml));
}
return urls;
}
export function setup() {
const allUrls = fetchAllUrlsFromSitemap(SITEMAP_INDEX_URL);
// Exclude only the homepage, include all other URLs (posts, pages, categories, tags, etc.)
const filtered = allUrls.filter((url) => url !== BASE_URL + '/');
console.log('All URLs from all nested sitemaps:', allUrls);
console.log('Filtered URLs (excluding homepage):', filtered);
return { urls: filtered };
}
export default function (data) {
const { urls } = data;
const rand = Math.random();
let targetUrl;
if (rand < 0.2 || urls.length === 0) {
targetUrl = BASE_URL + '/';
} else {
targetUrl = urls[Math.floor(Math.random() * urls.length)];
//console.log(`Visiting: ${targetUrl}`);
}
const res = http.get(targetUrl);
check(res, {
'status is 200': (r) => r.status === 200,
});
sleep(Math.random() * 2 + 1); // sleep 1-3s
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment