import fs from 'fs'; import path from 'path'; import { PythonGenerator } from '../src/server-targets/python/python-generator'; import { OpenRPCSpec } from '../src/types'; describe('Integration Tests for IComprehensiveTypes (Python)', () => { const tempOutputDir = path.join(__dirname, 'temp-output-python'); let testSpec: OpenRPCSpec; beforeAll(() => { // Clean up any previous test output if (fs.existsSync(tempOutputDir)) { fs.rmSync(tempOutputDir, { recursive: true, force: true }); } // Load OpenRPC spec for testing const specPath = path.join( __dirname, 'fixtures/IComprehensiveTypes.openrpc.json' ); if (!fs.existsSync(specPath)) { throw new Error('Test spec not found.'); } testSpec = JSON.parse(fs.readFileSync(specPath, 'utf8')); }); afterAll(() => { // Clean up test output if (fs.existsSync(tempOutputDir)) { fs.rmSync(tempOutputDir, { recursive: true, force: true }); } }); describe('Full Python code generation pipeline', () => { it('should generate complete Python project from OpenRPC spec', async () => { const specFileName = 'IComprehensiveTypes.openrpc.json'; const pythonGenerator = new PythonGenerator(); await pythonGenerator.generateServer( testSpec, specFileName, tempOutputDir ); // Check that all expected files were generated expect(fs.existsSync(path.join(tempOutputDir, 'pyproject.toml'))).toBe( true ); expect(fs.existsSync(path.join(tempOutputDir, 'src', 'main.py'))).toBe( true ); expect( fs.existsSync(path.join(tempOutputDir, 'src', 'gen', 'types.py')) ).toBe(true); expect( fs.existsSync(path.join(tempOutputDir, 'src', 'gen', 'server.py')) ).toBe(true); expect( fs.existsSync(path.join(tempOutputDir, 'src', 'gen', '__init__.py')) ).toBe(true); expect(fs.existsSync(path.join(tempOutputDir, 'Dockerfile'))).toBe(true); expect(fs.existsSync(path.join(tempOutputDir, 'README.md'))).toBe(true); expect(fs.existsSync(path.join(tempOutputDir, 'package.json'))).toBe( true ); }); it('should generate main.py with proper content', async () => { const mainPyPath = path.join(tempOutputDir, 'src', 'main.py'); expect(fs.existsSync(mainPyPath)).toBe(true); const mainPyContent = fs.readFileSync(mainPyPath, 'utf8'); // Check imports - updated to match actual structure expect(mainPyContent).toMatch(/from \.gen import \*/); expect(mainPyContent).toMatch( /from eth_pydantic_types\.hex\.int import HexInt/ ); expect(mainPyContent).toMatch(/import asyncio/); expect(mainPyContent).toMatch(/import os/); // Check for class implementation expect(mainPyContent).toMatch( /class ServerImpl\(ComprehensiveTypesServer\):/ ); // Check for uvicorn compatibility expect(mainPyContent).toMatch(/app = create_fastapi_app\(server_impl\)/); }); it('should generate types.py with Pydantic models', async () => { const typesPath = path.join(tempOutputDir, 'src', 'gen', 'types.py'); expect(fs.existsSync(typesPath)).toBe(true); const typesContent = fs.readFileSync(typesPath, 'utf8'); expect(typesContent).toMatch(/from pydantic import BaseModel/); expect(typesContent).toMatch(/class BasicStruct\(BaseModel\):/); expect(typesContent).toMatch(/class NestedStruct\(BaseModel\):/); expect(typesContent).toMatch(/class ComplexStruct\(BaseModel\):/); }); it('should generate pyproject.toml with correct dependencies', async () => { const pyprojectPath = path.join(tempOutputDir, 'pyproject.toml'); expect(fs.existsSync(pyprojectPath)).toBe(true); const pyprojectContent = fs.readFileSync(pyprojectPath, 'utf8'); // Check for required dependencies in modern Python packaging expect(pyprojectContent).toMatch(/fastapi\[standard\]/); expect(pyprojectContent).toMatch(/uvicorn\[standard\]/); expect(pyprojectContent).toMatch(/pydantic/); expect(pyprojectContent).toMatch(/openrpc/); expect(pyprojectContent).toMatch(/eth-pydantic-types/); }); it('should generate main.py with proper class and method structure', async () => { const mainPath = path.join(tempOutputDir, 'src', 'main.py'); expect(fs.existsSync(mainPath)).toBe(true); const mainContent = fs.readFileSync(mainPath, 'utf8'); // Check for server implementation class expect(mainContent).toMatch( /class ServerImpl\(ComprehensiveTypesServer\):/ ); // Check for async method definitions expect(mainContent).toMatch(/async def \w+_function\(/); // Check for main execution block expect(mainContent).toMatch(/if __name__ == "__main__":/); expect(mainContent).toMatch(/asyncio\.run\(main\(\)\)/); // Check for app creation expect(mainContent).toMatch(/app = create_fastapi_app\(server_impl\)/); }); it('should handle all method types from comprehensive interface', async () => { const mainPath = path.join(tempOutputDir, 'src', 'main.py'); const mainContent = fs.readFileSync(mainPath, 'utf8'); // Check for some expected method signatures from IComprehensiveTypes (updated to match HexInt usage) const EXPECTED_METHODS = [ { name: 'boolean_function', args: ['flag: bool'] }, { name: 'unsigned_integer_function', args: [ 'u8: HexInt', 'u16: HexInt', 'u32: HexInt', 'u64: HexInt', 'u128: HexInt', 'u256: HexInt', 'defaultUint: HexInt', ], }, { name: 'signed_integer_function', args: [ 'i8: HexInt', 'i16: HexInt', 'i32: HexInt', 'i64: HexInt', 'i128: HexInt', 'i256: HexInt', 'defaultInt: HexInt', ], }, { name: 'address_function', args: ['addr: str', 'payableAddr: str'] }, { name: 'bytes_function', args: ['data: bytes'] }, { name: 'string_function', args: ['text: str'] }, { name: 'dynamic_array_function', args: [ 'uintArray: list[HexInt]', 'stringArray: list[str]', 'bytesArray: list[bytes]', ], }, { name: 'fixed_array_function', args: [ 'fixedUintArray: list[HexInt]', 'fixedBytesArray: list[bytes]', ], }, { name: 'struct_function', args: [ 'basic: BasicStruct', 'nested: NestedStruct', 'complex: ComplexStruct', ], }, { name: 'kitchen_sink_function', args: [ 'flag: bool', 'number: HexInt', 'addr: str', 'hash: bytes', 'status: HexInt', 'text: str', 'array: list[HexInt]', 'struct_: BasicStruct', ], }, ]; for (const method of EXPECTED_METHODS) { const args = method.args.join(',\\s*'); const regex = new RegExp( `async def ${method.name}\\s*\\(\\s*self,\\s*${args.replace(/\[/g, '\\[').replace(/\]/g, '\\]')}` ); expect(mainContent).toMatch(regex); } }); }); describe('Generated code quality checks', () => { it('should generate properly formatted Python code', async () => { const mainPath = path.join(tempOutputDir, 'src', 'main.py'); const mainContent = fs.readFileSync(mainPath, 'utf8'); // Should not have obvious syntax errors // A simple check for indentation. Python uses 4 spaces. const lines = mainContent.split('\n'); const indentedLines = lines.filter( (line) => line.startsWith(' ') && !line.startsWith(' ') && line.trim().length > 0 ); // allow for docstrings which might not be 4-space indented const nonDocstringIndentedLines = indentedLines.filter( (line) => !line.trim().startsWith('"""') && !line.trim().startsWith('#') ); expect(nonDocstringIndentedLines.length).toBe(0); }); it('should not have duplicate type definitions', async () => { const typesPath = path.join(tempOutputDir, 'src', 'gen', 'types.py'); const typesContent = fs.readFileSync(typesPath, 'utf8'); const lines = typesContent.split('\n'); const typeDeclarations = lines.filter( (line) => line.startsWith('class ') && line.endsWith('(BaseModel):') ); const typeNames = typeDeclarations .map((line) => { const match = line.match(/class (\w+)\(BaseModel\):/); return match ? match[1] : null; }) .filter(Boolean); // Should not have duplicate type names expect(new Set(typeNames).size).toBe(typeNames.length); }); it('should import only necessary types', async () => { const mainPath = path.join(tempOutputDir, 'src', 'main.py'); const mainContent = fs.readFileSync(mainPath, 'utf8'); const importMatch = mainContent.match(/from typing import \([^)]+\)/); if (importMatch) { const imports = importMatch[1].split(',').map((s) => s.trim()); // Should not contain duplicates expect(new Set(imports).size).toBe(imports.length); const usedImports = imports.filter( (imp) => mainContent.includes(`: ${imp}`) || mainContent.includes(`[${imp}]`) ); expect(usedImports.length).toBeGreaterThan(0); } }); }); });