test-base-adapter.js•12.8 kB
/**
* BaseAdapter Test Suite
* @description Comprehensive testing for Universal Content Generation
* @version 5.0.0-alpha
*/
import { BaseAdapter, generateEducationalContent, ContentGenerationUtils } from '../../src/content-generation/index.js';
// Test configuration
const TEST_CASES = [
{
name: 'Physics - Ballistics',
description: 'Movimento de projéteis e balística para alunos do ensino médio',
expectedSubject: 'física',
expectedGrade: 'medio'
},
{
name: 'Chemistry - Photosynthesis',
description: 'Fotossíntese e respiração celular para 7º ano do ensino fundamental',
expectedSubject: 'biologia',
expectedGrade: 'fundamental-2'
},
{
name: 'History - Brazilian Independence',
description: 'Independência do Brasil e suas causas políticas e sociais',
expectedSubject: 'história',
expectedGrade: 'fundamental-2'
},
{
name: 'Mathematics - Basic Algebra',
description: 'Álgebra básica e equações de primeiro grau',
expectedSubject: 'matemática',
expectedGrade: 'fundamental-2'
},
{
name: 'Technology - Programming',
description: 'Introdução à programação e algoritmos básicos',
expectedSubject: 'tecnologia',
expectedGrade: 'medio'
},
{
name: 'Universal Topic - Cooking',
description: 'Técnicas básicas de culinária e segurança alimentar',
expectedSubject: 'geral',
expectedGrade: 'medio'
}
];
class BaseAdapterTestSuite {
constructor() {
this.results = {
total: 0,
passed: 0,
failed: 0,
errors: []
};
}
/**
* Run all tests
*/
async runAllTests() {
console.log('🧪 Starting BaseAdapter Test Suite');
console.log('=====================================\n');
// Test 1: Basic instantiation
await this.testInstantiation();
// Test 2: Topic analysis
await this.testTopicAnalysis();
// Test 3: Content generation
await this.testContentGeneration();
// Test 4: Grade level adaptation
await this.testGradeLevelAdaptation();
// Test 5: Universal topic handling
await this.testUniversalTopicHandling();
// Test 6: Content validation
await this.testContentValidation();
// Test 7: Performance testing
await this.testPerformance();
// Print results
this.printResults();
}
/**
* Test basic instantiation and configuration
*/
async testInstantiation() {
console.log('📋 Test 1: BaseAdapter Instantiation');
try {
// Test default configuration
const adapter1 = new BaseAdapter();
this.assert(adapter1 instanceof BaseAdapter, 'Should create BaseAdapter with default config');
this.assert(adapter1.config.language === 'pt-BR', 'Should have Portuguese as default language');
// Test custom configuration
const customConfig = {
language: 'en-US',
gradeLevel: 'medio',
maxLength: 3000
};
const adapter2 = new BaseAdapter(customConfig);
this.assert(adapter2.config.language === 'en-US', 'Should accept custom language');
this.assert(adapter2.config.maxLength === 3000, 'Should accept custom max length');
console.log('✅ Instantiation tests passed\n');
} catch (error) {
console.log('❌ Instantiation tests failed:', error.message);
this.results.errors.push(`Instantiation: ${error.message}`);
}
}
/**
* Test topic analysis functionality
*/
async testTopicAnalysis() {
console.log('📋 Test 2: Topic Analysis');
const adapter = new BaseAdapter();
for (const testCase of TEST_CASES) {
try {
console.log(` Testing: ${testCase.name}`);
const analysis = await adapter.analyzeTopic(testCase.description);
// Validate analysis structure
this.assert(analysis.subject, 'Should extract subject');
this.assert(analysis.domain, 'Should extract domain');
this.assert(analysis.concepts, 'Should extract concepts');
this.assert(analysis.keywords, 'Should extract keywords');
this.assert(analysis.gradeLevel, 'Should determine grade level');
this.assert(analysis.learningObjectives, 'Should generate learning objectives');
// Validate specific expectations
if (testCase.expectedSubject !== 'geral') {
this.assert(
analysis.subject === testCase.expectedSubject,
`Should identify subject as ${testCase.expectedSubject}, got ${analysis.subject}`
);
}
console.log(` ✅ ${testCase.name} analysis complete`);
} catch (error) {
console.log(` ❌ ${testCase.name} analysis failed:`, error.message);
this.results.errors.push(`Topic Analysis ${testCase.name}: ${error.message}`);
}
}
console.log('✅ Topic analysis tests completed\n');
}
/**
* Test content generation functionality
*/
async testContentGeneration() {
console.log('📋 Test 3: Content Generation');
const adapter = new BaseAdapter();
try {
// Test with a sample topic
const testTopic = 'Fotossíntese e sua importância para a vida na Terra';
console.log(` Generating content for: ${testTopic}`);
const analysis = await adapter.analyzeTopic(testTopic);
const content = await adapter.generateContent(analysis);
// Validate content structure
this.assert(content.metadata, 'Should have metadata');
this.assert(content.components, 'Should have components');
this.assert(content.components.introduction, 'Should have introduction');
this.assert(content.components.explanation, 'Should have explanation');
this.assert(content.components.summary, 'Should have summary');
// Validate content quality
this.assert(content.components.introduction.content.length > 50, 'Introduction should have substantial content');
this.assert(content.components.explanation.content.length > 100, 'Explanation should have substantial content');
console.log(' ✅ Content structure validation passed');
console.log(' ✅ Content quality validation passed');
console.log('✅ Content generation tests completed\n');
} catch (error) {
console.log('❌ Content generation tests failed:', error.message);
this.results.errors.push(`Content Generation: ${error.message}`);
}
}
/**
* Test grade level adaptation
*/
async testGradeLevelAdaptation() {
console.log('📋 Test 4: Grade Level Adaptation');
const adapter = new BaseAdapter();
try {
const testTopic = 'Energia cinética e potencial';
const analysis = await adapter.analyzeTopic(testTopic);
// Test different grade levels
const gradeLevels = ['fundamental-1', 'fundamental-2', 'medio'];
for (const grade of gradeLevels) {
console.log(` Testing adaptation for: ${grade}`);
analysis.gradeLevel = grade;
const content = await adapter.generateContent(analysis);
const adaptedContent = await adapter.adaptComplexity(content, grade);
this.assert(adaptedContent.metadata.adaptedFor === grade, `Should be adapted for ${grade}`);
this.assert(adaptedContent.metadata.complexity, 'Should have complexity metadata');
console.log(` ✅ ${grade} adaptation successful`);
}
console.log('✅ Grade level adaptation tests completed\n');
} catch (error) {
console.log('❌ Grade level adaptation tests failed:', error.message);
this.results.errors.push(`Grade Level Adaptation: ${error.message}`);
}
}
/**
* Test universal topic handling
*/
async testUniversalTopicHandling() {
console.log('📋 Test 5: Universal Topic Handling');
const universalTopics = [
'Como fazer pão caseiro',
'Técnicas de jardinagem urbana',
'Primeiros socorros básicos',
'Astronomia para iniciantes',
'Sustentabilidade no dia a dia'
];
const adapter = new BaseAdapter();
for (const topic of universalTopics) {
try {
console.log(` Testing universal topic: ${topic}`);
const analysis = await adapter.analyzeTopic(topic);
const content = await adapter.generateContent(analysis);
// Should be able to generate content for any topic
this.assert(content.components.introduction, 'Should generate introduction for any topic');
this.assert(content.components.explanation, 'Should generate explanation for any topic');
this.assert(content.metadata.topic, 'Should have topic metadata');
console.log(` ✅ ${topic} handled successfully`);
} catch (error) {
console.log(` ❌ ${topic} handling failed:`, error.message);
this.results.errors.push(`Universal Topic ${topic}: ${error.message}`);
}
}
console.log('✅ Universal topic handling tests completed\n');
}
/**
* Test content validation
*/
async testContentValidation() {
console.log('📋 Test 6: Content Validation');
try {
// Test with valid content
const validResult = await generateEducationalContent('Ciclo da água na natureza');
this.assert(validResult.success, 'Should successfully generate content');
this.assert(validResult.validation.isValid, 'Generated content should be valid');
this.assert(validResult.validation.score > 70, 'Content quality score should be good');
// Test validation utility
const validation = ContentGenerationUtils.validateContent(validResult.content);
this.assert(validation.score >= 0 && validation.score <= 100, 'Score should be in valid range');
console.log(` ✅ Content validation score: ${validation.score}`);
console.log('✅ Content validation tests completed\n');
} catch (error) {
console.log('❌ Content validation tests failed:', error.message);
this.results.errors.push(`Content Validation: ${error.message}`);
}
}
/**
* Test performance requirements
*/
async testPerformance() {
console.log('📋 Test 7: Performance Testing');
const adapter = new BaseAdapter();
const testTopic = 'Revolução Francesa e suas consequências';
try {
// Test generation speed
const startTime = Date.now();
const analysis = await adapter.analyzeTopic(testTopic);
const content = await adapter.generateContent(analysis);
const endTime = Date.now();
const duration = endTime - startTime;
console.log(` Generation time: ${duration}ms`);
// Performance target: < 3000ms (3 seconds)
this.assert(duration < 3000, `Generation should be under 3 seconds, took ${duration}ms`);
// Test memory usage (basic check)
const contentSize = JSON.stringify(content).length;
console.log(` Content size: ${contentSize} bytes`);
this.assert(contentSize > 1000, 'Generated content should be substantial');
console.log('✅ Performance tests completed\n');
} catch (error) {
console.log('❌ Performance tests failed:', error.message);
this.results.errors.push(`Performance: ${error.message}`);
}
}
/**
* Assert helper function
*/
assert(condition, message) {
this.results.total++;
if (condition) {
this.results.passed++;
} else {
this.results.failed++;
throw new Error(message);
}
}
/**
* Print test results
*/
printResults() {
console.log('📊 TEST RESULTS');
console.log('=====================================');
console.log(`Total Tests: ${this.results.total}`);
console.log(`✅ Passed: ${this.results.passed}`);
console.log(`❌ Failed: ${this.results.failed}`);
if (this.results.errors.length > 0) {
console.log('\n🚨 ERRORS:');
this.results.errors.forEach((error, index) => {
console.log(`${index + 1}. ${error}`);
});
}
const successRate = (this.results.passed / this.results.total * 100).toFixed(1);
console.log(`\n📈 Success Rate: ${successRate}%`);
if (this.results.failed === 0) {
console.log('🎉 All tests passed! BaseAdapter is ready for production.');
} else {
console.log('⚠️ Some tests failed. Review errors before deployment.');
}
}
}
// Export test suite for use in other files
export { BaseAdapterTestSuite };
// Run tests if called directly
if (import.meta.url === `file://${process.argv[1]}`) {
const testSuite = new BaseAdapterTestSuite();
testSuite.runAllTests().catch(console.error);
}