codepractice-ai / lib /codeRunner.ts
Mahdi Naser Moghadasi
Add CodePractice AI application with Docker support
4623c17
Raw History Blame Contribute Delete
5.55 kB
// Simulated Python code execution
// In production, this would connect to a secure code execution service
export interface ExecutionResult {
success: boolean
output?: any
error?: string
executionTime?: number
}
export interface TestResult {
passed: boolean
input: any
expectedOutput: any
actualOutput?: any
error?: string
}
export function executePythonCode(code: string, testCases: { input: any; expectedOutput: any }[]): {
results: TestResult[]
allPassed: boolean
} {
// This is a simulated execution
// In production, you would send this to a secure code execution API
const results: TestResult[] = []
// Simulate code execution with a timeout
try {
// Parse the function name from code (simplified)
const functionMatch = code.match(/def\s+(\w+)/)
if (!functionMatch) {
return {
results: [{
passed: false,
input: testCases[0].input,
expectedOutput: testCases[0].expectedOutput,
error: 'No function definition found',
}],
allPassed: false,
}
}
// For demo purposes, we'll simulate different outcomes
// In production, this would actually execute the code securely
for (const testCase of testCases) {
// Simulate execution
const simulatedResult = simulateExecution(code, testCase)
results.push({
passed: simulatedResult.passed,
input: testCase.input,
expectedOutput: testCase.expectedOutput,
actualOutput: simulatedResult.output,
error: simulatedResult.error,
})
}
} catch (error: any) {
return {
results: [{
passed: false,
input: testCases[0].input,
expectedOutput: testCases[0].expectedOutput,
error: error.message || 'Execution error',
}],
allPassed: false,
}
}
return {
results,
allPassed: results.every(r => r.passed),
}
}
function isCodeIncomplete(code: string): boolean {
// Remove comments and whitespace
const lines = code
.split('\n')
.map(line => line.trim())
.filter(line => line.length > 0)
const codeLines = lines.filter(line => !line.startsWith('#'))
if (codeLines.length === 0) return true
// Join non-comment lines
const cleanCode = codeLines.join('\n')
// Check if code only contains function definition with pass
// Pattern: def function(...): followed by only pass
const passOnlyPattern = /^def\s+\w+\([^)]*\):\s*(pass\s*)?$/
if (passOnlyPattern.test(cleanCode)) {
return true
}
// Check if code is just function definition ending with colon (no body)
if (cleanCode.trim().endsWith(':') && codeLines.length <= 1) {
return true
}
// Check if the only non-comment content is "pass"
const nonEmptyLines = codeLines.filter(line => line !== 'pass' && !line.match(/^\s*pass\s*$/))
if (nonEmptyLines.length === 0 && codeLines.some(line => line.includes('pass'))) {
return true
}
return false
}
function simulateExecution(code: string, testCase: { input: any; expectedOutput: any }): {
passed: boolean
output?: any
error?: string
} {
// Check if code is incomplete using the same logic
if (isCodeIncomplete(code)) {
return {
passed: false,
error: 'Code is incomplete. Please implement the solution.',
}
}
// Simulate syntax errors
if (code.includes('SyntaxError') || code.includes('undefined')) {
return {
passed: false,
error: 'Syntax error in your code',
}
}
// For demo, we'll check some common patterns
// In production, this would be actual execution
// Check if there's actual implementation (more than just function definition)
const cleanCode = code
.split('\n')
.map(line => line.trim())
.filter(line => !line.startsWith('#') && line.length > 0)
.join('\n')
const hasImplementation = cleanCode.length > 50 &&
!cleanCode.match(/^def\s+\w+\([^)]*\):\s*pass\s*$/)
if (hasImplementation) {
// Very basic simulation - in production, use actual code execution
// For demo, we'll simulate different outcomes based on code patterns
const looksCorrect = code.includes('return') ||
code.includes('print') ||
code.match(/=\s*\w+/) // Has assignments
if (looksCorrect) {
// Simulate passing test case
return {
passed: true,
output: testCase.expectedOutput,
}
} else {
// Simulate failing test case
return {
passed: false,
output: undefined,
error: 'Incorrect output',
}
}
}
return {
passed: false,
error: 'Please implement your solution',
}
}
export function runCode(code: string): ExecutionResult {
// Simulate running code without test cases (for "Run" button)
try {
if (isCodeIncomplete(code)) {
return {
success: false,
error: 'Code is incomplete. Please implement your solution.',
}
}
// Simulate execution with better output
// In production, this would capture actual stdout/stderr
const output = `Code executed successfully!
Function defined: ${code.match(/def\s+(\w+)/)?.[1] || 'unknown'}
Ready to test with sample inputs.`
return {
success: true,
output: output,
executionTime: Math.random() * 100 + 50, // Simulated execution time
}
} catch (error: any) {
return {
success: false,
error: error.message || 'Execution error',
}
}
}