From cb9d0fc54027d3497806feed4fc5fbae15a6970d Mon Sep 17 00:00:00 2001 From: Daniel McCoy Stephenson Date: Fri, 6 Nov 2026 04:10:10 -0700 Subject: [PATCH] Render an environment as text, with an example console application Patchwork could only show an environment through Pygame. text_renderer turns locations into a grid of text without importing Pygame, and console_view prints an existing environment from its ID, so it needs no display, creates nothing in Viron and writes no file. Closes #11 Co-Authored-By: Claude Opus 5.5 --- README.md | 38 ++++++++++- console_view.py | 73 +++++++++++++++++++++ tests/test_console_view.py | 122 ++++++++++++++++++++++++++++++++++++ tests/test_text_renderer.py | 53 ++++++++++++++++ text_renderer.py | 27 ++++++++ 5 files changed, 310 insertions(+), 3 deletions(-) create mode 100644 console_view.py create mode 100644 tests/test_console_view.py create mode 100644 tests/test_text_renderer.py create mode 100644 text_renderer.py diff --git a/README.md b/README.md index b962c7e..97edceb 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ This project is part of the [Viron](https://github.com/Preponderous-Software/Vir - Modular structure designed for future support of other graphics libraries - Clean interface for testing Viron entity placement and behavior - **RenderWindow** class for simplified Pygame window management +- Text rendering of an environment's locations, with an example console application (see [Text rendering](#text-rendering)) - Anonymous usage reporting (`startup` and `environment-created` events with the program name and version) with an opt-out in `settings.json` or the environment (see [Usage reporting](#usage-reporting)) ## RenderWindow @@ -104,6 +105,37 @@ graphik.drawButton(350, 500, 100, 40, (0, 0, 200), "white", 16, "Click", on_clic Colours may be RGB tuples or any colour name Pygame recognises, such as `"white"` or `"red"`. +## Text rendering + +`renderLocations` (in `text_renderer.py`) turns a list of locations into a string, so an environment can be shown without a window. It does not import Pygame: + +```python +from text_renderer import renderLocations + +print(renderLocations(locations)) +print(renderLocations(locations, filled="X", empty="_")) +``` + +Each location needs only `get_x()` and `get_y()`, as in the locations from Viron's `LocationService`. As in the Pygame window, `x` increases to the right and `y` increases downwards. The grid is sized from the locations themselves, up to the largest `x` and `y`, and a cell with no location shows the `empty` text. Cells are separated by a space, since a terminal character is about twice as tall as it is wide. An empty list renders as an empty string. + +`console_view.py` is an example console application built on it, which prints an environment that already exists in Viron: + +```bash +python console_view.py 7 +``` + +``` +# # # +# # # +# # # +``` + +The environment ID is the required argument; `environments.json` records the ID of each environment created by `main.py`. The Viron server is expected at `http://localhost:9999`, as for `main.py` (see [Starting Viron](#starting-viron)). The application uses Viron's `LocationService`, so it needs the `Viron/` submodule and Requests, but not Pygame. + +The exit status is `0` once the environment is printed. It is `1`, with a message, if the locations cannot be fetched or there are none, which is also how an ID unknown to Viron shows up, and `2`, with a usage line, if the argument is missing or is not an integer. `--help` or `-h` prints the usage line and exits with status `0` without contacting Viron. + +Nothing is created in Viron, no file is written, and no usage is reported. Viron gives every grid the same coordinates, so the grids of an environment with several would be drawn on top of each other; environments created by `main.py` have one. + ## Getting Started ### Prerequisites @@ -205,15 +237,15 @@ create_environments.bat 25 ### Running the tests -Unit tests live in `tests/` and use only the standard library's `unittest`. They stand in for Viron's service modules with stubs registered in `sys.modules`, so no display, no running Viron server, and not even a populated `Viron/` submodule are required. The tests for `main.py`, `render_window.py` and `graphik.py` mock Pygame; `tests/test_headless_run.py` also runs the headless harness described below end to end against the real Pygame using SDL's dummy drivers, and the tests for `usage_reporting.py` and `trace_client.py` do not involve Pygame at all. `tests/test_batch_scripts.py` reads the Windows batch scripts as text, so it needs no Windows either. Because Viron is stubbed rather than imported, the suite also runs on Python versions older than the 3.9 that `main.py` itself needs: +Unit tests live in `tests/` and use only the standard library's `unittest`. They stand in for Viron's service modules with stubs registered in `sys.modules`, so no display, no running Viron server, and not even a populated `Viron/` submodule are required. The tests for `main.py`, `render_window.py` and `graphik.py` mock Pygame; `tests/test_headless_run.py` also runs the headless harness described below end to end against the real Pygame using SDL's dummy drivers, and the tests for `text_renderer.py`, `console_view.py`, `usage_reporting.py` and `trace_client.py` do not involve Pygame at all. `tests/test_batch_scripts.py` reads the Windows batch scripts as text, so it needs no Windows either. Because Viron is stubbed rather than imported, the suite also runs on Python versions older than the 3.9 that `main.py` itself needs: ```bash python -m unittest discover -s tests ``` -Run the command from the repository root, so that the top-level modules the tests import (`main.py`, `render_window.py`, `graphik.py`, `headless_run.py`, `usage_reporting.py` and `trace_client.py`) are importable. +Run the command from the repository root, so that the top-level modules the tests import (`main.py`, `render_window.py`, `graphik.py`, `headless_run.py`, `text_renderer.py`, `console_view.py`, `usage_reporting.py` and `trace_client.py`) are importable. -The same command, preceded by a `py_compile` syntax check of the top-level modules, is run by the `Tests` GitHub Actions workflow (`.github/workflows/tests.yml`) on every pull request targeting `main` and on every push to `main`. The workflow checks the repository out without the `Viron` submodule, since the suite does not need it. +The same command, preceded by a `py_compile` syntax check of the top-level modules other than `text_renderer.py` and `console_view.py`, which the suite imports anyway, is run by the `Tests` GitHub Actions workflow (`.github/workflows/tests.yml`) on every pull request targeting `main` and on every push to `main`. The workflow checks the repository out without the `Viron` submodule, since the suite does not need it. ### Running without Docker or a display diff --git a/console_view.py b/console_view.py new file mode 100644 index 0000000..8006a7c --- /dev/null +++ b/console_view.py @@ -0,0 +1,73 @@ +""" +Print a Viron environment to the console, as an example of using text_renderer. + +The environment must already exist, for example from a run of main.py, whose +environments.json records the ID. Nothing is created in Viron and no file is written. + +Usage: + python console_view.py + +The exit status is 0 if the environment was printed, 1 if it could not be fetched or has +no locations, and 2 if the argument is missing or is not an integer. +""" +import sys + +from Viron.src.main.python.preponderous.viron.services.locationService import LocationService +from text_renderer import renderLocations + +url = "http://localhost" +port = 9999 + +usage = "Usage: python console_view.py " + +def parseEnvironmentId(argv): + """ + Read the environment ID from the command line. + + Args: + argv (list): The argument vector, including the program name at index 0 + + Returns: + int: The environment ID, or None if there is not exactly one integer argument + """ + if len(argv) != 2: + return None + try: + return int(argv[1]) + except ValueError: + return None + +def main(argv, locationService=None): + """ + Print the environment named on the command line. + + Args: + argv (list): The argument vector, including the program name at index 0 + locationService (LocationService): The location service to use, or None to build one + + Returns: + int: The exit status + """ + if "--help" in argv[1:] or "-h" in argv[1:]: + print(usage) + return 0 + environmentId = parseEnvironmentId(argv) + if environmentId is None: + print(usage) + return 2 + if locationService is None: + locationService = LocationService(url, port) + try: + locations = locationService.get_locations_in_environment(environmentId) + except Exception as e: + print(f"Error fetching the locations of environment {environmentId}: {e}") + return 1 + # Viron answers an unknown environment ID with an empty list rather than an error + if not locations: + print(f"Environment {environmentId} has no locations.") + return 1 + print(renderLocations(locations)) + return 0 + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/tests/test_console_view.py b/tests/test_console_view.py new file mode 100644 index 0000000..161e654 --- /dev/null +++ b/tests/test_console_view.py @@ -0,0 +1,122 @@ +import contextlib +import importlib +import io +import os +import runpy +import sys +import unittest +from unittest.mock import MagicMock, patch + +import headless_run + +headless_run.installVironStubs() + +import console_view + + +def fakeLocationService(locations): + locationService = MagicMock() + locationService.get_locations_in_environment.return_value = locations + return locationService + + +def runMain(argv, locationService=None): + """Run console_view.main() and return its exit status along with what it printed.""" + output = io.StringIO() + with contextlib.redirect_stdout(output): + status = console_view.main(argv, locationService=locationService) + return status, output.getvalue() + + +class TestParseEnvironmentId(unittest.TestCase): + def test_reads_the_environment_id_from_the_first_argument(self): + self.assertEqual(console_view.parseEnvironmentId(["console_view.py", "7"]), 7) + + def test_a_missing_argument_gives_none(self): + self.assertIsNone(console_view.parseEnvironmentId(["console_view.py"])) + + def test_a_non_integer_argument_gives_none(self): + self.assertIsNone(console_view.parseEnvironmentId(["console_view.py", "seven"])) + + def test_more_than_one_argument_gives_none(self): + self.assertIsNone(console_view.parseEnvironmentId(["console_view.py", "7", "8"])) + + +class TestMain(unittest.TestCase): + def test_prints_the_environment_and_exits_zero(self): + locations = [headless_run.FakeLocation(x, y) for x in range(2) for y in range(2)] + locationService = fakeLocationService(locations) + + status, output = runMain(["console_view.py", "7"], locationService) + + self.assertEqual(status, 0) + self.assertEqual(output, "# #\n# #\n") + locationService.get_locations_in_environment.assert_called_once_with(7) + + def test_a_missing_argument_prints_the_usage_and_exits_two_without_reaching_viron(self): + locationService = fakeLocationService([]) + + status, output = runMain(["console_view.py"], locationService) + + self.assertEqual(status, 2) + self.assertEqual(output, console_view.usage + "\n") + locationService.get_locations_in_environment.assert_not_called() + + def test_a_non_integer_argument_prints_the_usage_and_exits_two(self): + status, output = runMain(["console_view.py", "seven"], fakeLocationService([])) + + self.assertEqual(status, 2) + self.assertEqual(output, console_view.usage + "\n") + + def test_help_prints_the_usage_and_exits_zero_without_reaching_viron(self): + for flag in ("--help", "-h"): + with self.subTest(flag=flag), patch.object(console_view, "LocationService") as service: + status, output = runMain(["console_view.py", flag]) + + self.assertEqual(status, 0) + self.assertEqual(output, console_view.usage + "\n") + service.assert_not_called() + + def test_a_failed_fetch_prints_the_error_and_exits_one(self): + locationService = MagicMock() + locationService.get_locations_in_environment.side_effect = ConnectionError("refused") + + status, output = runMain(["console_view.py", "7"], locationService) + + self.assertEqual(status, 1) + self.assertEqual(output, "Error fetching the locations of environment 7: refused\n") + + def test_an_environment_with_no_locations_is_reported_and_exits_one(self): + status, output = runMain(["console_view.py", "7"], fakeLocationService([])) + + self.assertEqual(status, 1) + self.assertEqual(output, "Environment 7 has no locations.\n") + + def test_a_service_pointed_at_the_local_viron_is_built_by_default(self): + with patch.object(console_view, "LocationService") as service: + service.return_value = fakeLocationService([headless_run.FakeLocation(0, 0)]) + + status, output = runMain(["console_view.py", "7"]) + + self.assertEqual(status, 0) + self.assertEqual(output, "#\n") + service.assert_called_once_with("http://localhost", 9999) + + +class TestEntryPoint(unittest.TestCase): + def test_the_exit_status_of_main_reaches_the_process(self): + scriptPath = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "console_view.py") + + with patch.object(sys, "argv", ["console_view.py"]), contextlib.redirect_stdout(io.StringIO()): + with self.assertRaises(SystemExit) as caught: + runpy.run_path(scriptPath, run_name="__main__") + + self.assertEqual(caught.exception.code, 2) + + def test_the_module_can_be_imported_without_pygame(self): + with patch.dict(sys.modules, {"pygame": None}): + importlib.reload(console_view) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_text_renderer.py b/tests/test_text_renderer.py new file mode 100644 index 0000000..ad4daf0 --- /dev/null +++ b/tests/test_text_renderer.py @@ -0,0 +1,53 @@ +import importlib +import sys +import unittest +from unittest.mock import patch + +from headless_run import FakeLocation + +import text_renderer +from text_renderer import renderLocations + + +class TestRenderLocations(unittest.TestCase): + def test_a_full_grid_is_rendered_as_filled_cells_separated_by_spaces(self): + locations = [FakeLocation(x, y) for x in range(3) for y in range(2)] + + self.assertEqual(renderLocations(locations), "# # #\n# # #") + + def test_no_locations_render_as_an_empty_string(self): + self.assertEqual(renderLocations([]), "") + + def test_x_runs_along_a_row_and_y_runs_down_the_rows(self): + locations = [FakeLocation(2, 0), FakeLocation(0, 1)] + + self.assertEqual(renderLocations(locations), ". . #\n# . .") + + def test_a_cell_with_no_location_is_shown_as_empty(self): + locations = [FakeLocation(x, y) for x in range(3) for y in range(3) if (x, y) != (1, 1)] + + self.assertEqual(renderLocations(locations), "# # #\n# . #\n# # #") + + def test_the_grid_extends_to_the_furthest_location_from_the_origin(self): + self.assertEqual(renderLocations([FakeLocation(1, 2)]), ". .\n. .\n. #") + + def test_the_order_of_the_locations_does_not_matter(self): + locations = [FakeLocation(0, 0), FakeLocation(1, 1)] + + self.assertEqual(renderLocations(locations), renderLocations(list(reversed(locations)))) + + def test_locations_sharing_a_cell_are_drawn_once(self): + self.assertEqual(renderLocations([FakeLocation(0, 0), FakeLocation(0, 0)]), "#") + + def test_the_cell_text_can_be_chosen(self): + locations = [FakeLocation(1, 0)] + + self.assertEqual(renderLocations(locations, filled="X", empty="_"), "_ X") + + def test_the_module_can_be_imported_without_pygame(self): + with patch.dict(sys.modules, {"pygame": None}): + importlib.reload(text_renderer) + + +if __name__ == "__main__": + unittest.main() diff --git a/text_renderer.py b/text_renderer.py new file mode 100644 index 0000000..9d6f805 --- /dev/null +++ b/text_renderer.py @@ -0,0 +1,27 @@ +defaultFilled = "#" +defaultEmpty = "." + +def renderLocations(locations, filled=defaultFilled, empty=defaultEmpty): + """ + Render locations as a grid of text, with x increasing to the right and y increasing + downwards, as in the Pygame window. The grid is sized from the locations themselves, and + any cell in it that has no location is shown as empty. Cells are separated by a space, + since a character in a terminal is about twice as tall as it is wide. + + Args: + locations (list): The locations to render, each with get_x() and get_y() + filled (str): The text for a cell that has a location + empty (str): The text for a cell that has no location + + Returns: + str: One line per row, without a trailing newline, or "" if there are no locations + """ + occupied = {(location.get_x(), location.get_y()) for location in locations} + if not occupied: + return "" + width = max(x for x, y in occupied) + 1 + height = max(y for x, y in occupied) + 1 + rows = [] + for y in range(height): + rows.append(" ".join(filled if (x, y) in occupied else empty for x in range(width))) + return "\n".join(rows)