Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 3 additions & 4 deletions openevolve/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import asyncio
import pickle
import tempfile
import textwrap
import os
import uuid
import inspect
Expand Down Expand Up @@ -406,7 +407,7 @@ def initial_sort(arr):
"""

# Get function source code
func_source = inspect.getsource(func)
func_source = textwrap.dedent(inspect.getsource(func))
func_name = func.__name__

# Ensure the function source has evolution markers
Expand Down Expand Up @@ -534,7 +535,7 @@ def benchmark_sort(instance):
"""

# Get class source code
class_source = inspect.getsource(algorithm_class)
class_source = textwrap.dedent(inspect.getsource(algorithm_class))

# Ensure the class has evolution markers
if "EVOLVE-BLOCK-START" not in class_source:
Expand All @@ -551,8 +552,6 @@ def benchmark_sort(instance):
class_source = "\n".join(lines)

# Create a self-contained evaluator as a code string so it works in subprocesses.
import textwrap

class_name = algorithm_class.__name__
benchmark_source = textwrap.dedent(inspect.getsource(benchmark))

Expand Down
126 changes: 126 additions & 0 deletions tests/test_api_source_indentation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
"""Convenience APIs must emit importable standalone candidate definitions."""

import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

from openevolve.api import (
EvolutionResult,
_prepare_evaluator,
_prepare_program,
evolve_algorithm,
evolve_function,
)


def top_level_double(value):
if value < 0:
return -(abs(value) * 2)
return value * 2


class TopLevelSum:
def process(self, values):
total = 0
for value in values:
total += value
return total


def benchmark_sum(instance):
return {"score": 1.0 if instance.process([1, 2, 3]) == 6 else 0.0}


class TestGeneratedCandidateSource(unittest.TestCase):
def assert_generated_candidate_scores(self, subject, *, algorithm=False):
# Capture only orchestration, as in test_api.py. Candidate generation,
# file preparation, subprocess import and generated scoring stay real.
with patch("openevolve.api.run_evolution") as run:
run.return_value = EvolutionResult(None, 0.0, "", {}, None)
if algorithm:
evolve_algorithm(subject, benchmark_sum, iterations=1)
else:
evolve_function(subject, [(3, 6), (-2, -4)], iterations=1)
arguments = run.call_args.kwargs
source = arguments["initial_program"]
self.assertEqual(source.count("# EVOLVE-BLOCK-START"), 1)
self.assertEqual(source.count("# EVOLVE-BLOCK-END"), 1)

with tempfile.TemporaryDirectory() as directory:
files = []
program = _prepare_program(source, directory, files)
evaluator = _prepare_evaluator(arguments["evaluator"], directory, files)
self.assertEqual(Path(program).read_text(), source)
process = subprocess.run(
[
sys.executable,
"-c",
"import importlib.util, json, sys; "
"spec = importlib.util.spec_from_file_location('evaluator', sys.argv[1]); "
"module = importlib.util.module_from_spec(spec); "
"spec.loader.exec_module(module); "
"print(json.dumps(module.evaluate(sys.argv[2])))",
evaluator,
program,
],
capture_output=True,
text=True,
timeout=10,
)
self.assertEqual(process.returncode, 0, process.stderr)
metrics = json.loads(process.stdout)
self.assertEqual(metrics["combined_score"], 1.0, metrics)
self.assertNotIn("error", metrics)
if not algorithm:
self.assertEqual(metrics["tests_passed"], 2)

def test_nested_function(self):
def double(value):
if value < 0:
return -(abs(value) * 2)
return value * 2

self.assert_generated_candidate_scores(double)

def test_nested_function_with_markers(self):
def double(value):
# EVOLVE-BLOCK-START
if value < 0:
return -(abs(value) * 2)
return value * 2
# EVOLVE-BLOCK-END

self.assert_generated_candidate_scores(double)

def test_top_level_function(self):
self.assert_generated_candidate_scores(top_level_double)

def test_nested_class(self):
class Sum:
def process(self, values):
total = 0
for value in values:
total += value
return total

self.assert_generated_candidate_scores(Sum, algorithm=True)

def test_nested_class_with_markers(self):
class Sum:
# EVOLVE-BLOCK-START
def process(self, values):
total = 0
for value in values:
total += value
return total

# EVOLVE-BLOCK-END

self.assert_generated_candidate_scores(Sum, algorithm=True)

def test_top_level_class(self):
self.assert_generated_candidate_scores(TopLevelSum, algorithm=True)
Loading