import fs from 'fs'; import path from 'path'; import { PythonTypeMapper } from '../src/server-targets/python/python-type-mapper'; // Adjust path as necessary import { OpenRPCSpec } from '../src/types'; // Import necessary OpenRPC types describe('PythonTypeMapper', () => { let typeMapper: PythonTypeMapper; let testSpec: OpenRPCSpec; beforeAll(() => { // Load the test OpenRPC spec that's been generated from IComprehensiveTypes.sol 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')); }); beforeEach(() => { typeMapper = new PythonTypeMapper(); }); describe('mapSolidityType', () => { it('should map basic Solidity types to Python types', () => { expect(typeMapper.mapSolidityType('address')).toBe('str'); expect(typeMapper.mapSolidityType('uint256')).toBe('HexInt'); expect(typeMapper.mapSolidityType('uint8')).toBe('HexInt'); expect(typeMapper.mapSolidityType('int256')).toBe('HexInt'); expect(typeMapper.mapSolidityType('bytes')).toBe('bytes'); expect(typeMapper.mapSolidityType('string')).toBe('str'); expect(typeMapper.mapSolidityType('bool')).toBe('bool'); }); it('should handle dynamic array types', () => { expect(typeMapper.mapSolidityType('uint256[]')).toBe('list[HexInt]'); expect(typeMapper.mapSolidityType('string[]')).toBe('list[str]'); expect(typeMapper.mapSolidityType('address[]')).toBe('list[str]'); }); it('should handle fixed-size array types', () => { // In Python, fixed-size arrays are generally mapped to lists, // as Python's native list is dynamic and commonly used for array-like structures. expect(typeMapper.mapSolidityType('uint256[5]')).toBe('list[HexInt]'); expect(typeMapper.mapSolidityType('string[10]')).toBe('list[str]'); }); it('should handle multi-dimensional array types', () => { expect(typeMapper.mapSolidityType('uint256[][2]')).toBe( 'list[list[HexInt]]' ); expect(typeMapper.mapSolidityType('address[3][]')).toBe( 'list[list[str]]' ); expect(typeMapper.mapSolidityType('bool[1][2][3]')).toBe( 'list[list[list[bool]]]' ); }); it('should handle fixed-size byte arrays', () => { expect(typeMapper.mapSolidityType('bytes1')).toBe('bytes'); expect(typeMapper.mapSolidityType('bytes32')).toBe('bytes'); expect(typeMapper.mapSolidityType('bytes16')).toBe('bytes'); }); it('should return null for unknown types', () => { expect(typeMapper.mapSolidityType('unknownType')).toBe(null); expect(typeMapper.mapSolidityType('int257')).toBe(null); // Beyond int256 logic for Solidity }); }); describe('generateTypes', () => { let generatedTypes: string; beforeAll(() => { generatedTypes = typeMapper.generateTypes(testSpec); }); it('should generate valid Python code structure for Pydantic models', () => { expect(generatedTypes).toMatch(/^from typing import/m); // Check for typing import expect(generatedTypes).toMatch(/^from pydantic import BaseModel, Field/m); // Check for pydantic import expect(generatedTypes).toMatch(/^from collections import OrderedDict/m); // Check for OrderedDict import }); it('should generate proper Pydantic model definitions from OpenRPC components', () => { // BasicStruct checks expect(generatedTypes).toContain('class BasicStruct(BaseModel):'); expect(generatedTypes).toContain(' id: HexInt'); // uint256 maps to HexInt expect(generatedTypes).toContain(' name: str'); expect(generatedTypes).toContain(' active: bool'); // NestedStruct checks expect(generatedTypes).toContain('class NestedStruct(BaseModel):'); expect(generatedTypes).toContain(' numbers: list[HexInt]'); expect(generatedTypes).toContain(' basic: BasicStruct'); // Reference to BasicStruct }); it('should handle field name sanitization (snake_case)', () => { expect(generatedTypes).toContain('active: bool'); }); it('should only import used typing primitives', () => { const typingImportLine = generatedTypes.match( /from typing import ([^\n]+)/ ); expect(typingImportLine).toBeTruthy(); if (typingImportLine) { const imports = typingImportLine[1] .split(',') .map((s) => s.trim()) .sort(); expect(imports).toEqual(['Any']); } }); it('should generate compilable Python code (basic syntax check)', () => { // Check for common syntax errors, this is a very basic check expect(generatedTypes).not.toContain(';;'); // No semicolons expect(generatedTypes).not.toContain('public'); // No Rust-specific keywords expect(generatedTypes).not.toContain('alloy_primitives'); // No Rust-specific library names }); }); describe('getRequiredImports', () => { it('should extract correct imports from OpenRPC spec', () => { const imports = typeMapper.getRequiredImports(testSpec); expect(imports).toEqual([ 'from typing import Any', 'from pydantic import BaseModel, Field', 'from eth_pydantic_types.hex.int import HexInt', 'from collections import OrderedDict', ]); }); it('should extract correct imports for a spec with optional parameters', () => { const optionalParamSpec: OpenRPCSpec = { openrpc: '1.2.6', info: { title: 'Optional', version: '1.0.0' }, methods: [ { name: 'getData', params: [ { name: 'id', schema: { type: 'string' } }, { name: 'optionalId', schema: { type: 'string' }, required: false, }, ], result: { schema: { type: 'boolean' } }, }, ], }; const imports = typeMapper.getRequiredImports(optionalParamSpec); expect(imports).toEqual([ 'from typing import Optional', 'from collections import OrderedDict', ]); }); }); describe('Edge cases and error handling for generateTypes', () => { it('should return empty string when no struct components exist', () => { const minimalSpec: OpenRPCSpec = { openrpc: '1.2.6', info: { title: 'Test', version: '1.0.0' }, methods: [ { name: 'test', params: [ { name: 'param', schema: { type: 'string' }, // Basic type without components }, ], result: { schema: { type: 'boolean' } }, }, ], }; const types = typeMapper.generateTypes(minimalSpec); expect(types).toBe(''); // No types.py needed for primitive-only specs }); it('should handle spec with components but no schemas', () => { const emptyComponentsSpec: OpenRPCSpec = { openrpc: '1.2.6', info: { title: 'Test', version: '1.0.0' }, methods: [], components: {}, // Empty components }; const types = typeMapper.generateTypes(emptyComponentsSpec); expect(types).toBe(''); }); it('should handle malformed struct schemas gracefully (missing properties)', () => { const malformedSpec: OpenRPCSpec = { openrpc: '1.2.6', info: { title: 'Test', version: '1.0.0' }, methods: [], components: { schemas: { BadStruct: { type: 'object', // Missing properties field, which should be handled by `if ('properties' in schema)` }, AnotherStruct: { type: 'object', properties: { name: { type: 'string' }, }, }, }, }, }; const types = typeMapper.generateTypes(malformedSpec); // It should still generate the AnotherStruct, and not crash for BadStruct expect(types).toContain('class AnotherStruct(BaseModel):'); expect(types).not.toContain('class BadStruct(BaseModel):'); // Malformed one should be skipped }); it('should handle malformed struct schemas gracefully (non-object properties)', () => { const malformedSpec: OpenRPCSpec = { openrpc: '1.2.6', info: { title: 'Test', version: '1.0.0' }, methods: [], components: { schemas: { BadStruct: { type: 'object', properties: 'notAnObject', // Malformed properties field } as any, // Cast to any to allow invalid type for testing AnotherStruct: { type: 'object', properties: { name: { type: 'string' }, }, }, }, }, }; const types = typeMapper.generateTypes(malformedSpec); expect(types).toContain('class AnotherStruct(BaseModel):'); expect(types).not.toContain('class BadStruct(BaseModel):'); // Malformed one should be skipped }); }); });