Improve logic and error messages for file reading and writing with Python code (#4567)

* Fix issues with file reading and writing with Python code

* Change error message, use Workspace.get_path

---------

Co-authored-by: Reinier van der Leer <github@pwuts.nl>
This commit is contained in:
Erik Peterson
2023-06-06 17:54:02 -07:00
committed by GitHub
parent 20a4922b40
commit fdc6e12945
4 changed files with 39 additions and 11 deletions

View File

@@ -1,6 +1,7 @@
import random
import string
import tempfile
from typing import Callable
import pytest
from pytest_mock import MockerFixture
@@ -10,12 +11,12 @@ from autogpt.config import Config
@pytest.fixture
def config_allow_execute(config: Config, mocker: MockerFixture):
def config_allow_execute(config: Config, mocker: MockerFixture) -> Callable:
yield mocker.patch.object(config, "execute_local_commands", True)
@pytest.fixture
def python_test_file(config: Config, random_string):
def python_test_file(config: Config, random_string) -> Callable:
temp_file = tempfile.NamedTemporaryFile(dir=config.workspace_path, suffix=".py")
temp_file.write(str.encode(f"print('Hello {random_string}!')"))
temp_file.flush()
@@ -34,18 +35,24 @@ def test_execute_python_file(python_test_file: str, random_string: str, config):
assert result.replace("\r", "") == f"Hello {random_string}!\n"
def test_execute_python_file_invalid(config):
def test_execute_python_file_invalid(config: Config):
assert all(
s in sut.execute_python_file("not_python", config).lower()
for s in ["error:", "invalid", ".py"]
)
def test_execute_python_file_not_found(config: Config):
assert all(
s in sut.execute_python_file("notexist.py", config).lower()
for s in ["error:", "does not exist"]
for s in [
"python: can't open file 'notexist.py'",
"[errno 2] no such file or directory",
]
)
def test_execute_shell(config_allow_execute, random_string, config):
def test_execute_shell(config_allow_execute: bool, random_string: str, config: Config):
result = sut.execute_shell(f"echo 'Hello {random_string}!'", config)
assert f"Hello {random_string}!" in result