S7_snap7_Stremer_n_Recorder/testing/playwright-mcp-global.js

191 lines
5.7 KiB
JavaScript

#!/usr/bin/env node
/**
* Global Playwright MCP-like Automation Script
* This script can be used across multiple projects
*/
import { chromium, firefox, webkit } from 'playwright';
import { program } from 'commander';
import fs from 'fs/promises';
import path from 'path';
program
.name('playwright-mcp')
.description('Playwright MCP-like automation tool for web applications')
.version('1.0.0');
program
.command('test')
.description('Run automated tests')
.option('-b, --browser <type>', 'Browser type (chromium, firefox, webkit)', 'chromium')
.option('-h, --headless', 'Run in headless mode', false)
.option('-u, --url <url>', 'Base URL to test', 'http://localhost:3000')
.action(async (options) => {
const { browser, headless, url } = options;
console.log(`Running tests with ${browser} browser on ${url}`);
// Your test logic here
await runTests({ browser, headless, url });
});
program
.command('capture')
.description('Capture screenshots of application')
.option('-b, --browser <type>', 'Browser type', 'chromium')
.option('-u, --url <url>', 'URL to capture', 'http://localhost:3000')
.option('-o, --output <dir>', 'Output directory', './screenshots')
.action(async (options) => {
await captureScreenshots(options);
});
program
.command('monitor')
.description('Monitor application performance')
.option('-b, --browser <type>', 'Browser type', 'chromium')
.option('-u, --url <url>', 'URL to monitor', 'http://localhost:3000')
.option('-d, --duration <seconds>', 'Monitoring duration', '60')
.action(async (options) => {
await monitorPerformance(options);
});
async function runTests({ browser, headless, url }) {
const browserInstance = await launchBrowser(browser, { headless });
const context = await browserInstance.newContext();
const page = await context.newPage();
try {
await page.goto(url);
await page.waitForLoadState('networkidle');
// Basic connectivity test
const title = await page.title();
console.log(`Page title: ${title}`);
// Check for common elements
const links = await page.locator('a').count();
const buttons = await page.locator('button').count();
console.log(`Found ${links} links and ${buttons} buttons`);
// Performance metrics
const metrics = await page.evaluate(() => {
const navigation = performance.getEntriesByType('navigation')[0];
return {
loadTime: navigation.loadEventEnd - navigation.loadEventStart,
domContentLoaded: navigation.domContentLoadedEventEnd - navigation.domContentLoadedEventStart,
firstPaint: performance.getEntriesByName('first-paint')[0]?.startTime || 0
};
});
console.log('Performance metrics:', metrics);
} catch (error) {
console.error('Test failed:', error);
} finally {
await context.close();
await browserInstance.close();
}
}
async function captureScreenshots({ browser, url, output }) {
const browserInstance = await launchBrowser(browser, { headless: true });
const context = await browserInstance.newContext();
const page = await context.newPage();
try {
await page.goto(url);
await page.waitForLoadState('networkidle');
// Create output directory
await fs.mkdir(output, { recursive: true });
// Full page screenshot
await page.screenshot({
path: path.join(output, 'full-page.png'),
fullPage: true
});
// Viewport screenshot
await page.screenshot({
path: path.join(output, 'viewport.png')
});
console.log(`Screenshots saved to ${output}`);
} catch (error) {
console.error('Screenshot capture failed:', error);
} finally {
await context.close();
await browserInstance.close();
}
}
async function monitorPerformance({ browser, url, duration }) {
const browserInstance = await launchBrowser(browser, { headless: true });
const context = await browserInstance.newContext();
const page = await context.newPage();
const metrics = [];
const startTime = Date.now();
const durationMs = parseInt(duration) * 1000;
try {
await page.goto(url);
// Monitor performance every 5 seconds
const interval = setInterval(async () => {
const currentMetrics = await page.evaluate(() => {
return {
timestamp: Date.now(),
memory: performance.memory ? {
usedJSHeapSize: performance.memory.usedJSHeapSize,
totalJSHeapSize: performance.memory.totalJSHeapSize,
jsHeapSizeLimit: performance.memory.jsHeapSizeLimit
} : null,
timing: performance.timing
};
});
metrics.push(currentMetrics);
console.log(`Memory usage: ${(currentMetrics.memory?.usedJSHeapSize / 1024 / 1024).toFixed(2)} MB`);
}, 5000);
// Stop monitoring after duration
setTimeout(() => {
clearInterval(interval);
}, durationMs);
// Wait for monitoring to complete
await new Promise(resolve => setTimeout(resolve, durationMs));
// Save metrics
await fs.writeFile('performance-monitor.json', JSON.stringify(metrics, null, 2));
console.log('Performance monitoring completed. Data saved to performance-monitor.json');
} catch (error) {
console.error('Performance monitoring failed:', error);
} finally {
await context.close();
await browserInstance.close();
}
}
async function launchBrowser(type, options = {}) {
const browsers = {
chromium: chromium,
firefox: firefox,
webkit: webkit
};
const defaultOptions = {
headless: false,
slowMo: 100
};
return await browsers[type].launch({ ...defaultOptions, ...options });
}
// Parse command line arguments
program.parse();