Performance Testing for Google.com
Below is an example of how you could set up performance tests for Google.com that can be integrated into your CI pipeline to check for regressions. I'll provide examples using popular tools like Lighthouse (for web performance), k6 (for load testing), and WebPageTest (for detailed performance analysis).
1. Lighthouse CI
Lighthouse is a great tool for measuring web performance metrics. Here's how to set it up in your CI pipeline:
// lighthouserc.js
module.exports = {
ci: {
collect: {
url: ['https://www.google.com'],
numberOfRuns: 3,
},
assert: {
assertions: {
'first-contentful-paint': ['warn', {maxNumericValue: 1500}],
'largest-contentful-paint': ['error', {maxNumericValue: 2500}],
'cumulative-layout-shift': ['error', {maxNumericValue: 0.1}],
'total-blocking-time': ['error', {maxNumericValue: 300}],
'interactive': ['error', {maxNumericValue: 3500}],
},
},
upload: {
target: 'temporary-public-storage',
},
},
};
Add this to your CI workflow (GitHub Actions example):
# .github/workflows/lighthouse-ci.yml
name: Lighthouse CI
on: [push]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v9
with:
configPath: './lighthouserc.js'
uploadArtifacts: true
2. k6 Load Testing
For load testing, k6 is a developer-friendly tool that can be integrated into your CI:
// google-load-test.js
import http from 'k6/http';
import { check, sleep } from 'k6';
export const options = {
vus: 10, // Virtual Users
duration: '30s',
thresholds: {
http_req_duration: ['p(95)<500'], // 95% of requests should be below 500ms
http_req_failed: ['rate<0.01'], // Less than 1% of requests should fail
},
};
export default function() {
const res = http.get('https://www.google.com');
check(res, {
'status is 200': (r) => r.status === 200,
'response time < 500ms': (r) => r.timings.duration < 500,
});
sleep(1);
}
Add to your CI (GitHub Actions):
# .github/workflows/k6-load-test.yml
name: k6 Load Test
on: [push]
jobs:
k6_load_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run k6 load test
uses: grafana/k6-action@v0.2.0
with:
filename: google-load-test.js
3. WebPageTest API Integration
For more detailed performance analysis:
// webpagetest.js
const WebPageTest = require('webpagetest');
const wpt = new WebPageTest('www.webpagetest.org', process.env.WPT_API_KEY);
const testOptions = {
firstViewOnly: true,
runs: 3,
location: 'ec2-us-east-1:Chrome',
connectivity: '4G',
};
wpt.runTest('https://www.google.com', testOptions, (err, result) => {
if (err) {
console.error('Error running WebPageTest:', err);
process.exit(1);
}
// Define thresholds
const ttfbThreshold = 300;
const loadTimeThreshold = 2000;
const median = result.data.median.firstView;
if (median.TTFB > ttfbThreshold || median.loadTime > loadTimeThreshold) {
console.error('Performance regression detected!');
console.error(`TTFB: ${median.TTFB}ms (threshold: ${ttfbThreshold}ms)`);
console.error(`Load Time: ${median.loadTime}ms (threshold: ${loadTimeThreshold}ms)`);
process.exit(1);
}
console.log('Performance test passed!');
console.log(`TTFB: ${median.TTFB}ms`);
console.log(`Load Time: ${median.loadTime}ms`);
});
4. Custom Performance Metrics with Puppeteer
For custom metrics collection:
// performance-metrics.js
const puppeteer = require('puppeteer');
const fs = require('fs');
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// Enable performance metrics collection
await page.setCacheEnabled(false);
await page.tracing.start({ path: 'trace.json', categories: ['devtools.timeline'] });
// Navigate to Google
const navigationStart = Date.now();
await page.goto('https://www.google.com', { waitUntil: 'networkidle0' });
const navigationEnd = Date.now();
// Collect performance metrics
const metrics = await page.metrics();
const performanceTimings = JSON.parse(
await page.evaluate(() => JSON.stringify(window.performance.timing))
);
await page.tracing.stop();
await browser.close();
// Calculate key metrics
const ttfb = performanceTimings.responseStart - performanceTimings.requestStart;
const domContentLoaded = performanceTimings.domContentLoadedEventEnd - performanceTimings.navigationStart;
const fullLoad = performanceTimings.loadEventEnd - performanceTimings.navigationStart;
const navigationTime = navigationEnd - navigationStart;
// Define thresholds
const thresholds = {
ttfb: 200,
domContentLoaded: 1000,
fullLoad: 2000,
navigationTime: 2500,
jsHeapUsed: 30 * 1024 * 1024, // 30MB
};
// Check for regressions
const results = {
ttfb: { value: ttfb, passed: ttfb <= thresholds.ttfb },
domContentLoaded: { value: domContentLoaded, passed: domContentLoaded <= thresholds.domContentLoaded },
fullLoad: { value: fullLoad, passed: fullLoad <= thresholds.fullLoad },
navigationTime: { value: navigationTime, passed: navigationTime <= thresholds.navigationTime },
jsHeapUsed: { value: metrics.JSHeapUsedSize, passed: metrics.JSHeapUsedSize <= thresholds.jsHeapUsed },
};
// Save results
fs.writeFileSync('performance-results.json', JSON.stringify(results, null, 2));
// Exit with error if any test failed
const allPassed = Object.values(results).every(result => result.passed);
process.exit(allPassed ? 0 : 1);
})();
Integration with CI Pipeline
Here's a complete GitHub Actions workflow that combines these tests:
# .github/workflows/performance-tests.yml
name: Performance Tests
on: [push]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v9
with:
configPath: './lighthouserc.js'
uploadArtifacts: true
load_test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Run k6 load test
uses: grafana/k6-action@v0.2.0
with:
filename: google-load-test.js
custom_metrics:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Setup Node.js
uses: actions/setup-node@v2
with:
node-version: '16'
- name: Install dependencies
run: npm install puppeteer
- name: Run custom performance tests
run: node performance-metrics.js
- name: Upload performance results
uses: actions/upload-artifact@v2
with:
name: performance-results
path: |
performance-results.json
trace.json
Tracking Performance Over Time
To track performance over time, you could:
- Store test results in a database
- Generate trend charts
- Set up alerts for significant regressions
This example provides a foundation for performance testing that you can adapt to your specific application needs.