contract testing

This commit is contained in:
2025-12-24 00:01:01 +01:00
parent 43a8afe7a9
commit 5e491d9724
52 changed files with 2058 additions and 612 deletions

View File

@@ -0,0 +1,257 @@
/**
* Contract Validation Tests for API
*
* These tests validate that the API DTOs and OpenAPI spec are consistent
* and that the generated types will be compatible with the website.
*/
import { describe, it, expect } from 'vitest';
import * as fs from 'fs/promises';
import * as path from 'path';
import { glob } from 'glob';
interface OpenAPISchema {
type?: string;
format?: string;
$ref?: string;
items?: OpenAPISchema;
properties?: Record<string, OpenAPISchema>;
required?: string[];
enum?: string[];
nullable?: boolean;
description?: string;
}
interface OpenAPISpec {
openapi: string;
info: {
title: string;
description: string;
version: string;
};
paths: Record<string, any>;
components: {
schemas: Record<string, OpenAPISchema>;
};
}
describe('API Contract Validation', () => {
const apiRoot = path.join(__dirname, '../../..');
const openapiPath = path.join(apiRoot, 'openapi.json');
const generatedTypesDir = path.join(apiRoot, '../website/lib/types/generated');
describe('OpenAPI Spec Integrity', () => {
it('should have a valid OpenAPI spec file', async () => {
const specExists = await fs.access(openapiPath).then(() => true).catch(() => false);
expect(specExists).toBe(true);
});
it('should have a valid JSON structure', async () => {
const content = await fs.readFile(openapiPath, 'utf-8');
expect(() => JSON.parse(content)).not.toThrow();
});
it('should have required OpenAPI fields', async () => {
const content = await fs.readFile(openapiPath, 'utf-8');
const spec: OpenAPISpec = JSON.parse(content);
expect(spec.openapi).toMatch(/^3\.\d+\.\d+$/);
expect(spec.info).toBeDefined();
expect(spec.info.title).toBeDefined();
expect(spec.info.version).toBeDefined();
expect(spec.components).toBeDefined();
expect(spec.components.schemas).toBeDefined();
});
it('should have no circular references in schemas', async () => {
const content = await fs.readFile(openapiPath, 'utf-8');
const spec: OpenAPISpec = JSON.parse(content);
const schemas = spec.components.schemas;
const visited = new Set<string>();
const visiting = new Set<string>();
function detectCircular(schemaName: string): boolean {
if (visiting.has(schemaName)) return true;
if (visited.has(schemaName)) return false;
visiting.add(schemaName);
const schema = schemas[schemaName];
if (!schema) {
visiting.delete(schemaName);
visited.add(schemaName);
return false;
}
// Check properties for references
if (schema.properties) {
for (const prop of Object.values(schema.properties)) {
if (prop.$ref) {
const refName = prop.$ref.split('/').pop();
if (refName && detectCircular(refName)) {
return true;
}
}
if (prop.items?.$ref) {
const refName = prop.items.$ref.split('/').pop();
if (refName && detectCircular(refName)) {
return true;
}
}
}
}
visiting.delete(schemaName);
visited.add(schemaName);
return false;
}
for (const schemaName of Object.keys(schemas)) {
expect(detectCircular(schemaName)).toBe(false);
}
});
});
describe('DTO Consistency', () => {
it('should have DTO files for all schemas', async () => {
const content = await fs.readFile(openapiPath, 'utf-8');
const spec: OpenAPISpec = JSON.parse(content);
const schemas = Object.keys(spec.components.schemas);
const generatedFiles = await fs.readdir(generatedTypesDir);
const generatedDTOs = generatedFiles
.filter(f => f.endsWith('.ts'))
.map(f => f.replace('.ts', ''));
// All schemas should have corresponding generated DTOs
for (const schema of schemas) {
expect(generatedDTOs).toContain(schema);
}
});
it('should have consistent property types between DTOs and schemas', async () => {
const content = await fs.readFile(openapiPath, 'utf-8');
const spec: OpenAPISpec = JSON.parse(content);
const schemas = spec.components.schemas;
for (const [schemaName, schema] of Object.entries(schemas)) {
const dtoPath = path.join(generatedTypesDir, `${schemaName}.ts`);
const dtoExists = await fs.access(dtoPath).then(() => true).catch(() => false);
if (!dtoExists) continue;
const dtoContent = await fs.readFile(dtoPath, 'utf-8');
// Check that all required properties are present
if (schema.required) {
for (const requiredProp of schema.required) {
expect(dtoContent).toContain(requiredProp);
}
}
// Check that all properties are present
if (schema.properties) {
for (const propName of Object.keys(schema.properties)) {
expect(dtoContent).toContain(propName);
}
}
}
});
});
describe('Type Generation Integrity', () => {
it('should have valid TypeScript syntax in generated files', async () => {
const files = await fs.readdir(generatedTypesDir);
const dtos = files.filter(f => f.endsWith('.ts'));
for (const file of dtos) {
const content = await fs.readFile(path.join(generatedTypesDir, file), 'utf-8');
// Basic TypeScript syntax checks
expect(content).toContain('export interface');
expect(content).toContain('{');
expect(content).toContain('}');
// Should not have syntax errors (basic check)
expect(content).not.toContain('undefined;');
expect(content).not.toContain('any;');
}
});
it('should have proper imports for dependencies', async () => {
const files = await fs.readdir(generatedTypesDir);
const dtos = files.filter(f => f.endsWith('.ts'));
for (const file of dtos) {
const content = await fs.readFile(path.join(generatedTypesDir, file), 'utf-8');
const importMatches = content.match(/import type \{ (\w+) \} from '\.\/(\w+)';/g) || [];
for (const importLine of importMatches) {
const match = importLine.match(/import type \{ (\w+) \} from '\.\/(\w+)';/);
if (match) {
const [, importedType, fromFile] = match;
expect(importedType).toBe(fromFile);
// Check that the imported file exists
const importedPath = path.join(generatedTypesDir, `${fromFile}.ts`);
const exists = await fs.access(importedPath).then(() => true).catch(() => false);
expect(exists).toBe(true);
}
}
}
});
});
describe('Contract Compatibility', () => {
it('should maintain backward compatibility for existing DTOs', async () => {
// This test ensures that when regenerating types, existing properties aren't removed
// unless explicitly intended
const content = await fs.readFile(openapiPath, 'utf-8');
const spec: OpenAPISpec = JSON.parse(content);
// Check critical DTOs that are likely used in production
const criticalDTOs = [
'RequestAvatarGenerationInputDTO',
'RequestAvatarGenerationOutputDTO',
'UploadMediaInputDTO',
'UploadMediaOutputDTO',
'RaceDTO',
'DriverDTO'
];
for (const dtoName of criticalDTOs) {
if (spec.components.schemas[dtoName]) {
const dtoPath = path.join(generatedTypesDir, `${dtoName}.ts`);
const exists = await fs.access(dtoPath).then(() => true).catch(() => false);
expect(exists).toBe(true);
}
}
});
it('should handle nullable fields correctly', async () => {
const content = await fs.readFile(openapiPath, 'utf-8');
const spec: OpenAPISpec = JSON.parse(content);
const schemas = spec.components.schemas;
for (const [schemaName, schema] of Object.entries(schemas)) {
if (!schema.properties) continue;
for (const [propName, propSchema] of Object.entries(schema.properties)) {
const dtoPath = path.join(generatedTypesDir, `${schemaName}.ts`);
const dtoContent = await fs.readFile(dtoPath, 'utf-8');
if (propSchema.nullable) {
// Nullable properties should be optional in TypeScript
const propRegex = new RegExp(`${propName}\\??:\\s*([\\w\\[\\]<>|]+)\\s*;`);
const match = dtoContent.match(propRegex);
if (match) {
// Should include null in the type or be optional
expect(match[1]).toContain('| null');
}
}
}
}
});
});
});