hanabhi/gridworld-env
0
1# Copyright (c) Meta Platforms, Inc. and affiliates.2# All rights reserved.3#4# This source code is licensed under the BSD-style license found in the5# LICENSE file in the root directory of this source tree.6 7#!/usr/bin/env python38"""9Simple test showing how users will use CodingEnv.from_docker_image().10 11This is the simplest possible usage12"""13 14import sys15from pathlib import Path16 17# Add src to path18sys.path.insert(0, str(Path(__file__).parent.parent / "src"))19 20from coding_env import CodeAction, CodingEnv21 22 23def main():24 """Test CodingEnv.from_docker_image()."""25 print("=" * 60)26 print("CodingEnv.from_docker_image() Test")27 print("=" * 60)28 print()29 30 try:31 # This is what users will do - just one line!32 print("Creating client from Docker image...")33 print(" CodingEnv.from_docker_image('coding-env:latest')")34 print()35 36 client = CodingEnv.from_docker_image("coding-env:latest")37 38 print("✓ Client created and container started!\n")39 40 # Now use it like any other client41 print("Testing the environment:")42 print("-" * 60)43 44 # Reset45 print("\n1. Reset:")46 result = client.reset()47 print(f" stdout: {result.observation.stdout}")48 print(f" stderr: {result.observation.stderr}")49 print(f" exit_code: {result.observation.exit_code}")50 51 # Get initial state52 state = client.state()53 print(f" State: episode_id={state.episode_id}, step_count={state.step_count}")54 55 # Execute some Python code56 print("\n2. Execute Python code:")57 58 code_samples = [59 "print('Hello, World!')",60 "x = 5 + 3\nprint(f'Result: {x}')",61 "import math\nprint(f'Pi is approximately {math.pi:.4f}')",62 "# Multi-line calculation\nfor i in range(1, 4):\n print(f'{i} squared is {i**2}')",63 ]64 65 for i, code in enumerate(code_samples, 1):66 result = client.step(CodeAction(code=code))67 print(f" {i}. Code: {code.replace(chr(10), '\\n')[:50]}...")68 print(f" → stdout: {result.observation.stdout.strip()}")69 print(f" → exit_code: {result.observation.exit_code}")70 if result.observation.stderr:71 print(f" → stderr: {result.observation.stderr}")72 73 # Test error scenarios74 print("\n3. Test error scenarios:")75 76 error_samples = [77 ("Division by zero", "x = 1 / 0\nprint('Should not reach here')"),78 ("Undefined variable", "print(undefined_variable)"),79 ("Syntax error", "print('Hello'"),80 ]81 82 for i, (description, code) in enumerate(error_samples, 1):83 result = client.step(CodeAction(code=code))84 print(f" {i}. {description}")85 print(f" Code: {code.replace(chr(10), '\\n')[:40]}...")86 print(f" → exit_code: {result.observation.exit_code}")87 if result.observation.stderr:88 # Truncate long error messages89 error_msg = result.observation.stderr[:100]90 if len(result.observation.stderr) > 100:91 error_msg += "..."92 print(f" → stderr: {error_msg}")93 94 # Check final state95 print("\n4. Check final state:")96 state = client.state()97 print(f" episode_id: {state.episode_id}")98 print(f" step_count: {state.step_count}")99 print(f" last_exit_code: {state.last_exit_code}")100 101 print("\n" + "-" * 60)102 print("\n✓ All operations successful!")103 print()104 105 print("Cleaning up...")106 client.close()107 print("✓ Container stopped and removed")108 print()109 110 print("=" * 60)111 print("Test completed successfully! 🎉")112 print("=" * 60)113 114 return True115 116 except Exception as e:117 print(f"\n❌ Test failed: {e}")118 import traceback119 traceback.print_exc()120 return False121 122 123if __name__ == "__main__":124 success = main()125 exit(0 if success else 1)126 