safeer-pdf-generator
Version:
Framework-agnostic PDF generation library with chunking, merging, S3 upload, and email delivery
256 lines (226 loc) • 6.97 kB
JavaScript
/**
* Simple test script to verify the Express API is working
* Run this after starting the server with: node test.js
*/
const http = require('http');
const BASE_URL = 'http://localhost:3000';
// Helper function to make HTTP requests
function makeRequest(path, method = 'GET', data = null) {
return new Promise((resolve, reject) => {
const url = new URL(path, BASE_URL);
const options = {
hostname: url.hostname,
port: url.port,
path: url.pathname + url.search,
method,
headers: {
'Content-Type': 'application/json',
},
};
const req = http.request(options, res => {
let body = '';
res.on('data', chunk => {
body += chunk;
});
res.on('end', () => {
try {
const parsed = JSON.parse(body);
resolve({ status: res.statusCode, data: parsed, headers: res.headers });
} catch (e) {
resolve({ status: res.statusCode, data: body, headers: res.headers });
}
});
});
req.on('error', reject);
if (data) {
req.write(JSON.stringify(data));
}
req.end();
});
}
// Test functions
async function testHealthCheck() {
console.log('🏥 Testing health check...');
try {
const response = await makeRequest('/api/health');
if (response.status === 200) {
console.log('✅ Health check passed');
console.log(` Status: ${response.data.status}`);
console.log(` Uptime: ${Math.round(response.data.uptime)}s`);
return true;
} else {
console.log('❌ Health check failed');
return false;
}
} catch (error) {
console.log('❌ Health check error:', error.message);
return false;
}
}
async function testSampleData() {
console.log('📊 Testing sample data...');
try {
const response = await makeRequest('/api/samples/customers?count=10');
if (response.status === 200 && response.data.data) {
console.log('✅ Sample data retrieved');
console.log(` Records: ${response.data.data.length}`);
console.log(` Columns: ${response.data.columns.length}`);
return response.data;
} else {
console.log('❌ Sample data failed');
return null;
}
} catch (error) {
console.log('❌ Sample data error:', error.message);
return null;
}
}
async function testEstimation(sampleData) {
console.log('⏱️ Testing performance estimation...');
try {
const response = await makeRequest('/api/estimate', 'POST', {
data: sampleData.data.slice(0, 5), // Use small sample
columns: sampleData.columns,
});
if (response.status === 200) {
console.log('✅ Estimation completed');
console.log(` Estimated time: ${response.data.estimatedTime}ms`);
console.log(` Recommendation: ${response.data.recommendation}`);
return true;
} else {
console.log('❌ Estimation failed');
return false;
}
} catch (error) {
console.log('❌ Estimation error:', error.message);
return false;
}
}
async function testMetrics() {
console.log('📈 Testing metrics...');
try {
const response = await makeRequest('/api/metrics');
if (response.status === 200) {
console.log('✅ Metrics retrieved');
console.log(` Total requests: ${response.data.requests}`);
console.log(` Success rate: ${response.data.successRate}`);
return true;
} else {
console.log('❌ Metrics failed');
return false;
}
} catch (error) {
console.log('❌ Metrics error:', error.message);
return false;
}
}
async function testAsyncGeneration(sampleData) {
console.log('🔄 Testing async PDF generation...');
try {
const response = await makeRequest('/api/generate/async', 'POST', {
title: 'Test Report',
data: sampleData.data.slice(0, 3),
columns: sampleData.columns,
options: {
template: 'modern-business',
format: 'A4',
},
});
if (response.status === 200 && response.data.jobId) {
console.log('✅ Async job started');
console.log(` Job ID: ${response.data.jobId}`);
// Check job status
let attempts = 0;
const maxAttempts = 10;
while (attempts < maxAttempts) {
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait 1 second
const statusResponse = await makeRequest(`/api/job/${response.data.jobId}`);
if (statusResponse.status === 200) {
console.log(
` Job status: ${statusResponse.data.status} (${statusResponse.data.progress}%)`
);
if (statusResponse.data.status === 'completed') {
console.log('✅ Async PDF generation completed');
return true;
} else if (statusResponse.data.status === 'failed') {
console.log('❌ Async PDF generation failed');
return false;
}
}
attempts++;
}
console.log('⏰ Async job timeout (still processing)');
return true; // Not necessarily a failure
} else {
console.log('❌ Async job creation failed');
return false;
}
} catch (error) {
console.log('❌ Async generation error:', error.message);
return false;
}
}
// Main test runner
async function runTests() {
console.log('🚀 Starting API tests...');
console.log('');
let passed = 0;
let total = 0;
// Test health check
total++;
if (await testHealthCheck()) passed++;
console.log('');
// Test sample data
total++;
const sampleData = await testSampleData();
if (sampleData) passed++;
console.log('');
if (sampleData) {
// Test estimation
total++;
if (await testEstimation(sampleData)) passed++;
console.log('');
// Test async generation
total++;
if (await testAsyncGeneration(sampleData)) passed++;
console.log('');
}
// Test metrics
total++;
if (await testMetrics()) passed++;
console.log('');
// Summary
console.log('📋 Test Summary:');
console.log(` Passed: ${passed}/${total}`);
console.log(` Success Rate: ${Math.round((passed / total) * 100)}%`);
if (passed === total) {
console.log('🎉 All tests passed! The API is working correctly.');
} else {
console.log('⚠️ Some tests failed. Check the server logs for details.');
}
process.exit(passed === total ? 0 : 1);
}
// Check if server is running before starting tests
async function checkServer() {
try {
const response = await makeRequest('/');
if (response.status === 200) {
console.log(`✅ Server is running on ${BASE_URL}`);
console.log('');
return true;
}
} catch (error) {
console.log(`❌ Server is not running on ${BASE_URL}`);
console.log(' Please start the server with: npm start');
console.log('');
return false;
}
}
// Run the tests
(async () => {
if (await checkServer()) {
await runTests();
} else {
process.exit(1);
}
})();