@simonecoelhosfo/optimizely-mcp-server
Version:
Optimizely MCP Server for AI assistants with integrated CLI tools
286 lines • 11.2 kB
JavaScript
/**
* Phase 4D Test - Advanced JSON Transformations
*
* Tests complex JSON path queries and nested object manipulation
*/
import { IntelligentQueryEngine } from './IntelligentQueryEngine.js';
import { OptimizelyAdapter } from './adapters/OptimizelyAdapter.js';
import { JSONPathHandler } from './JSONPathHandler.js';
import Database from 'better-sqlite3';
async function runTest(engine, test) {
const startTime = Date.now();
try {
const result = await engine.query(test.query);
const isValid = test.validate ? test.validate(result) : true;
if (!isValid) {
throw new Error('Validation failed');
}
return {
name: test.name,
success: true,
rowCount: result.data?.length || 0,
executionTime: Date.now() - startTime,
data: result.data
};
}
catch (error) {
return {
name: test.name,
success: false,
error: error instanceof Error ? error.message : String(error),
executionTime: Date.now() - startTime
};
}
}
async function testJSONPathHandler() {
console.log('## JSON Path Handler Unit Tests\\n');
const handler = new JSONPathHandler();
const testPaths = [
{
path: '$.environments.production.rules[0]',
expected: { segments: 4, isValid: true }
},
{
path: '$.variations[*].key',
expected: { segments: 3, isValid: true, hasWildcard: true }
},
{
path: '$.rules[?(@.percentage > 50)]',
expected: { segments: 2, isValid: true, hasFilter: true }
},
{
path: '$.metrics..goal',
expected: { segments: 3, isValid: true, hasRecursive: true }
},
{
path: 'environments.staging.enabled',
expected: { segments: 3, isValid: true }
}
];
for (const test of testPaths) {
const result = handler.parseJSONPath(test.path);
console.log(`Path: ${test.path}`);
console.log(`Valid: ${result.isValid} | Segments: ${result.segments.length}`);
console.log(`SQLite: ${result.sqliteExpression}\\n`);
}
}
async function testPhase4DJSONTransformations() {
console.log('# Phase 4D JSON Transformations Test Suite\\n');
// First run unit tests
await testJSONPathHandler();
// Initialize
const db = new Database('./data/optimizely-cache.db', { readonly: true });
const engine = new IntelligentQueryEngine({
discovery: {
autoDiscover: true,
discoveryInterval: 60000,
cacheTTL: 3600000
}
});
const adapter = new OptimizelyAdapter({ database: db });
engine.registerAdapter(adapter);
// Wait for discovery
await new Promise(resolve => setTimeout(resolve, 500));
const testGroups = [
{
name: 'Simple JSON Path Queries',
tests: [
{
name: 'Extract environment data',
query: {
find: 'flag',
select: ['name', '$.environments.production as prod_env'],
limit: 3
},
expectedBehavior: 'Extract production environment JSON'
},
{
name: 'Query specific rule percentage',
query: {
find: 'flag',
select: ['name', '$.rules[0].percentage as first_rule_pct'],
where: [{ field: '$.rules[0].percentage', operator: '>', value: 0 }],
limit: 3
},
expectedBehavior: 'Extract first rule percentage'
},
{
name: 'Extract nested variation keys',
query: {
find: 'flag',
select: ['name', '$.variations[0].key as first_var_key'],
limit: 3
},
expectedBehavior: 'Extract first variation key'
}
]
},
{
name: 'Complex JSON Navigation',
tests: [
{
name: 'Multi-level path extraction',
query: {
find: 'flag',
select: ['name', '$.environments.production.rules[0].variations as prod_rule_vars'],
limit: 3
},
expectedBehavior: 'Deep nested path extraction'
},
{
name: 'JSON path in WHERE clause',
query: {
find: 'flag',
select: ['name', '$.environments.production.enabled as is_prod_enabled'],
where: [{ field: '$.environments.production.enabled', operator: '=', value: true }],
limit: 3
},
expectedBehavior: 'Filter by JSON boolean value'
},
{
name: 'Multiple JSON extractions',
query: {
find: 'experiment',
select: [
'name',
'$.metrics[0].event_id as primary_metric',
'$.variations[0].name as control_name',
'$.variations[1].name as treatment_name'
],
limit: 3
},
expectedBehavior: 'Multiple JSON field extractions'
}
]
},
{
name: 'JSON Array Operations',
tests: [
{
name: 'Array length queries',
query: {
find: 'flag',
select: ['name', 'JSON_ARRAY_LENGTH($.variations) as var_count'],
where: [{ field: 'JSON_ARRAY_LENGTH($.variations)', operator: '>', value: 2 }],
limit: 3
},
expectedBehavior: 'Count array elements'
},
{
name: 'Array contains check',
query: {
find: 'experiment',
select: ['name'],
where: [{
field: 'JSON_EXTRACT(data_json, "$.audience_conditions[0].audience_id")',
operator: 'IS NOT',
value: null
}],
limit: 3
},
expectedBehavior: 'Check if array contains elements'
}
]
},
{
name: 'Entity Prefix JSON Paths',
tests: [
{
name: 'Entity-prefixed JSON path',
query: {
find: 'flag',
select: ['flag.name', 'flag.environments.production.enabled as prod_enabled'],
limit: 3
},
expectedBehavior: 'Handle entity.json.path syntax'
},
{
name: 'Mixed regular and JSON fields',
query: {
find: 'flag',
select: [
'key',
'archived',
'flag.environments.production.rules[0].percentage as prod_traffic'
],
where: [
{ field: 'archived', operator: '=', value: false },
{ field: 'flag.environments.production.enabled', operator: '=', value: true }
],
limit: 3
},
expectedBehavior: 'Mix of regular columns and JSON paths'
}
]
},
{
name: 'Advanced JSON Filtering',
tests: [
{
name: 'Complex JSON condition',
query: {
find: 'flag',
select: ['name', '$.environments as all_envs'],
where: [
{ field: '$.environments.production.enabled', operator: '=', value: true },
{ field: '$.environments.staging.enabled', operator: '=', value: false }
],
limit: 3
},
expectedBehavior: 'Multiple JSON path conditions'
},
{
name: 'JSON null handling',
query: {
find: 'experiment',
select: ['name', '$.holdback as holdback_pct'],
where: [{ field: '$.holdback', operator: 'IS NOT', value: null }],
limit: 3
},
expectedBehavior: 'Handle JSON nulls correctly'
}
]
}
];
const allResults = [];
// Run tests
for (const group of testGroups) {
console.log(`\\n## ${group.name}\\n`);
for (const test of group.tests) {
const result = await runTest(engine, test);
allResults.push(result);
const status = result.success ? '✅' : '❌';
console.log(`${status} ${test.name}`);
if (result.success) {
console.log(` Rows: ${result.rowCount} | Time: ${result.executionTime}ms`);
}
else {
console.log(` Error: ${result.error}`);
console.log(` Time: ${result.executionTime}ms`);
}
console.log(` Expected: ${test.expectedBehavior}\\n`);
}
}
// Summary
const passed = allResults.filter(r => r.success).length;
const total = allResults.length;
const successRate = ((passed / total) * 100).toFixed(1);
const avgTime = (allResults.reduce((sum, r) => sum + r.executionTime, 0) / total).toFixed(1);
console.log('## Summary');
console.log(`- Total Tests: ${total}`);
console.log(`- Passed: ${passed}`);
console.log(`- Failed: ${total - passed}`);
console.log(`- Success Rate: ${successRate}%`);
console.log(`- Average Time: ${avgTime}ms\\n`);
console.log('## Phase 4D Features Tested');
console.log('JSON path parsing and validation');
console.log('Simple JSON field extraction');
console.log('Nested JSON path navigation');
console.log('JSON array operations');
console.log('Entity-prefixed JSON paths');
console.log('JSON filtering in WHERE clauses');
console.log('JSON null handling');
db.close();
}
testPhase4DJSONTransformations().catch(console.error);
//# sourceMappingURL=test-phase4d-json-transformations.js.map