// frontend/src/components/Dashboard.jsx
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import {
LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
BarChart, Bar, PieChart, Pie, Cell
} from 'recharts';
function Dashboard() {
const [stats, setStats] = useState({
testCaseCount: 0,
xpathCount: 0,
runHistory: [],
passRate: 0,
testResults: {
passed: 0,
failed: 0,
skipped: 0
},
categoryBreakdown: []
});
useEffect(() => {
const fetchDashboardData = async () => {
try {
const response = await axios.get('/api/dashboard/stats');
setStats(response.data);
} catch (error) {
console.error('Error fetching dashboard data:', error);
}
};
fetchDashboardData();
// Set up auto-refresh every 5 minutes
const intervalId = setInterval(fetchDashboardData, 300000);
return () => clearInterval(intervalId);
}, []);
const COLORS = ['#00C49F', '#FF8042', '#FFBB28'];
return (
<div className="dashboard">
<h1>QA Dashboard</h1>
<div className="stat-cards">
<div className="stat-card">
<h3>Test Cases</h3>
<p className="stat-value">{stats.testCaseCount}</p>
</div>
<div className="stat-card">
<h3>XPath Elements</h3>
<p className="stat-value">{stats.xpathCount}</p>
</div>
<div className="stat-card">
<h3>Pass Rate</h3>
<p className="stat-value">{stats.passRate}%</p>
</div>
</div>
<div className="chart-row">
<div className="chart-container">
<h2>Test Execution History</h2>
<LineChart width={600} height={300} data={stats.runHistory}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="date" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="passRate" stroke="#8884d8" />
<Line type="monotone" dataKey="testCount" stroke="#82ca9d" />
</LineChart>
</div>
<div className="chart-container">
<h2>Current Test Results</h2>
<PieChart width={400} height={300}>
<Pie
data={[
{ name: 'Passed', value: stats.testResults.passed },
{ name: 'Failed', value: stats.testResults.failed },
{ name: 'Skipped', value: stats.testResults.skipped }
]}
cx="50%"
cy="50%"
labelLine={false}
outerRadius={80}
fill="#8884d8"
dataKey="value"
>
{stats.testResults && Object.values(stats.testResults).map((entry, index) => (
<Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />
))}
</Pie>
<Tooltip />
<Legend />
</PieChart>
</div>
</div>
<div className="chart-container full-width">
<h2>Tests by Category</h2>
<BarChart width={800} height={300} data={stats.categoryBreakdown}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="category" />
<YAxis />
<Tooltip />
<Legend />
<Bar dataKey="count" fill="#8884d8" />
<Bar dataKey="passCount" fill="#82ca9d" />
</BarChart>
</div>
</div>
);
}
export default Dashboard;
// frontend/src/components/Scheduler.jsx
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function Scheduler() {
const [testCases, setTestCases] = useState([]);
const [selectedTests, setSelectedTests] = useState([]);
const [scheduleConfig, setScheduleConfig] = useState({
frequency: 'daily',
time: '00:00',
days: [],
runOnDemand: false
});
const [schedules, setSchedules] = useState([]);
useEffect(() => {
const fetchData = async () => {
try {
const [testResponse, schedulesResponse] = await Promise.all([
axios.get('/api/test-cases'),
axios.get('/api/schedules')
]);
setTestCases(testResponse.data);
setSchedules(schedulesResponse.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchData();
}, []);
const handleTestSelection = (testId) => {
if (selectedTests.includes(testId)) {
setSelectedTests(selectedTests.filter(id => id !== testId));
} else {
setSelectedTests([...selectedTests, testId]);
}
};
const handleDaySelection = (day) => {
if (scheduleConfig.days.includes(day)) {
setScheduleConfig({
...scheduleConfig,
days: scheduleConfig.days.filter(d => d !== day)
});
} else {
setScheduleConfig({
...scheduleConfig,
days: [...scheduleConfig.days, day]
});
}
};
const createSchedule = async () => {
if (selectedTests.length === 0) {
alert('Please select at least one test case');
return;
}
try {
await axios.post('/api/schedules', {
testIds: selectedTests,
config: scheduleConfig,
name: `Schedule ${schedules.length + 1}`,
createdAt: new Date()
});
alert('Schedule created successfully!');
// Refresh schedules
const response = await axios.get('/api/schedules');
setSchedules(response.data);
// Reset form
setSelectedTests([]);
setScheduleConfig({
frequency: 'daily',
time: '00:00',
days: [],
runOnDemand: false
});
} catch (error) {
console.error('Error creating schedule:', error);
alert('Failed to create schedule');
}
};
const runNow = async (scheduleId) => {
try {
await axios.post(`/api/schedules/${scheduleId}/run`);
alert('Tests started successfully!');
} catch (error) {
console.error('Error running tests:', error);
alert('Failed to run tests');
}
};
return (
<div className="scheduler">
<h1>Test Scheduler</h1>
<div className="scheduler-container">
<div className="test-selection">
<h2>Select Test Cases</h2>
<div className="test-list">
{testCases.map(test => (
<div key={test.id} className="test-item">
<input
type="checkbox"
id={`test-${test.id}`}
checked={selectedTests.includes(test.id)}
onChange={() => handleTestSelection(test.id)}
/>
<label htmlFor={`test-${test.id}`}>{test.name}</label>
</div>
))}
</div>
</div>
<div className="schedule-config">
<h2>Configure Schedule</h2>
<div className="form-group">
<label>Frequency:</label>
<select
value={scheduleConfig.frequency}
onChange={(e) => setScheduleConfig({...scheduleConfig, frequency: e.target.value})}
>
<option value="daily">Daily</option>
<option value="weekly">Weekly</option>
<option value="monthly">Monthly</option>
</select>
</div>
<div className="form-group">
<label>Time:</label>
<input
type="time"
value={scheduleConfig.time}
onChange={(e) => setScheduleConfig({...scheduleConfig, time: e.target.value})}
/>
</div>
{scheduleConfig.frequency === 'weekly' && (
<div className="form-group">
<label>Days of Week:</label>
<div className="day-selector">
{['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'].map(day => (
<div key={day} className="day-option">
<input
type="checkbox"
id={`day-${day}`}
checked={scheduleConfig.days.includes(day)}
onChange={() => handleDaySelection(day)}
/>
<label htmlFor={`day-${day}`}>{day.substring(0, 3)}</label>
</div>
))}
</div>
</div>
)}
<button onClick={createSchedule} className="create-btn">Create Schedule</button>
</div>
</div>
<div className="schedules-list">
<h2>Existing Schedules</h2>
<table>
<thead>
<tr>
<th>Name</th>
<th>Frequency</th>
<th>Next Run</th>
<th>Tests</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{schedules.map(schedule => (
<tr key={schedule.id}>
<td>{schedule.name}</td>
<td>
{schedule.config.frequency}
{schedule.config.frequency === 'weekly' &&
` (${schedule.config.days.map(d => d.substring(0, 3)).join(', ')})`}
{` at ${schedule.config.time}`}
</td>
<td>{schedule.nextRun}</td>
<td>{schedule.testIds.length} tests</td>
<td>
<button onClick={() => runNow(schedule.id)}>Run Now</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
export default Scheduler;
// backend/server.js
const express = require('express');
const mongoose = require('mongoose');
const cron = require('node-cron');
const cors = require('cors');
const XPathModel = require('./models/XPath');
const TestCaseModel = require('./models/TestCase');
const ScheduleModel = require('./models/Schedule');
const TestResultModel = require('./models/TestResult');
const { runTests } = require('./services/testRunner');
const app = express();
app.use(cors());
app.use(express.json());
// MongoDB connection
mongoose.connect('mongodb://localhost:27017/qa-platform', {
useNewUrlParser: true,
useUnifiedTopology: true
});
// XPath repository endpoints
app.post('/api/xpaths', async (req, res) => {
try {
const xpath = new XPathModel(req.body);
await xpath.save();
res.status(201).json(xpath);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/xpaths', async (req, res) => {
try {
const xpaths = await XPathModel.find();
res.json(xpaths);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Test case endpoints
app.post('/api/test-cases', async (req, res) => {
try {
const testCase = new TestCaseModel(req.body);
await testCase.save();
res.status(201).json(testCase);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/test-cases', async (req, res) => {
try {
const testCases = await TestCaseModel.find();
res.json(testCases);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Test generation endpoint (simplified - would use an LLM in a real app)
app.post('/api/generate-test', async (req, res) => {
try {
const { prompt } = req.body;
// Simulated test case generation - in a real app this would call an LLM
const testCode = `
describe('${prompt}', () => {
test('should perform expected behavior', async () => {
// Setup
await page.goto('https://example.com');
// Login steps
await page.type('#username', 'testuser');
await page.type('#password', 'password123');
await page.click('#login-button');
// Verification
await page.waitForSelector('#dashboard');
const isOnDashboard = await page.$('#dashboard') !== null;
expect(isOnDashboard).toBe(true);
});
});`;
// Simulate processing delay
setTimeout(() => {
res.json({ testCode });
}, 1500);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Schedule endpoints
app.post('/api/schedules', async (req, res) => {
try {
const schedule = new ScheduleModel(req.body);
await schedule.save();
res.status(201).json(schedule);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/api/schedules', async (req, res) => {
try {
const schedules = await ScheduleModel.find();
res.json(schedules);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.post('/api/schedules/:id/run', async (req, res) => {
try {
const schedule = await ScheduleModel.findById(req.params.id);
if (!schedule) {
return res.status(404).json({ error: 'Schedule not found' });
}
const testCases = await TestCaseModel.find({
_id: { $in: schedule.testIds }
});
// Run tests in background
runTests(testCases)
.then(results => {
// Save results
results.forEach(async result => {
const testResult = new TestResultModel({
testId: result.testId,
scheduleId: schedule._id,
status: result.status,
duration: result.duration,
error: result.error,
timestamp: new Date()
});
await testResult.save();
});
})
.catch(error => console.error('Error running tests:', error));
res.json({ message: 'Tests started successfully' });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Dashboard endpoints
app.get('/api/dashboard/stats', async (req, res) => {
try {
// Get test case count
const testCaseCount = await TestCaseModel.countDocuments();
// Get xpath count
const xpathCount = await XPathModel.countDocuments();
// Get test results summary
const testResults = await TestResultModel.aggregate([
{
$group: {
_id: '$status',
count: { $sum: 1 }
}
}
]);
// Calculate pass rate
const resultStats = {
passed: 0,
failed: 0,
skipped: 0
};
testResults.forEach(result => {
resultStats[result._id] = result.count;
});
const totalTests = resultStats.passed + resultStats.failed + resultStats.skipped;
const passRate = totalTests > 0 ? Math.round((resultStats.passed / totalTests) * 100) : 0;
// Get run history (last 7 days)
const sevenDaysAgo = new Date();
sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
const runHistory = await TestResultModel.aggregate([
{
$match: {
timestamp: { $gte: sevenDaysAgo }
}
},
{
$group: {
_id: {
$dateToString: { format: '%Y-%m-%d', date: '$timestamp' }
},
testCount: { $sum: 1 },
passCount: {
$sum: {
$cond: [{ $eq: ['$status', 'passed'] }, 1, 0]
}
}
}
},
{
$project: {
date: '$_id',
testCount: 1,
passCount: 1,
passRate: {
$multiply: [
{ $divide: ['$passCount', '$testCount'] },
100
]
}
}
},
{ $sort: { date: 1 } }
]);
// Get category breakdown
const categoryBreakdown = await TestCaseModel.aggregate([
{
$group: {
_id: '$category',
count: { $sum: 1 }
}
},
{
$project: {
category: '$_id',
count: 1
}
}
]);
res.json({
testCaseCount,
xpathCount,
passRate,
testResults: resultStats,
runHistory,
categoryBreakdown
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Start the server
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
// Set up scheduled tasks checker
cron.schedule('* * * * *', async () => {
const now = new Date();
const currentHour = now.getHours();
const currentMinute = now.getMinutes();
const currentTime = `${currentHour.toString().padStart(2, '0')}:${currentMinute.toString().padStart(2, '0')}`;
const dayOfWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][now.getDay()];
try {
// Find schedules that should run now
const schedulesToRun = await ScheduleModel.find({
'config.time': currentTime,
$or: [
{ 'config.frequency': 'daily' },
{
'config.frequency': 'weekly',
'config.days': dayOfWeek
}
]
});
// Run each scheduled test suite
for (const schedule of schedulesToRun) {
const testCases = await TestCaseModel.find({
_id: { $in: schedule.testIds }
});
console.log(`Running scheduled tests: ${schedule.name}`);
runTests(testCases)
.then(results => {
// Save results
results.forEach(async result => {
const testResult = new TestResultModel({
testId: result.testId,
scheduleId: schedule._id,
status: result.status,
duration: result.duration,
error: result.error,
timestamp: new Date()
});
await testResult.save();
});
})
.catch(error => console.error('Error running scheduled tests:', error));
}
} catch (error) {
console.error('Error checking schedules:', error);
}
});
});