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
25 changes: 19 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ 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 environment ID is the required argument; `environments.json` records the ID of each environment created by `main.py`. The Viron server is expected at the same address 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.

Expand Down Expand Up @@ -166,7 +166,7 @@ The submodule is required at runtime: `main.py` imports Viron's `EnvironmentServ

### Starting Viron

Patchwork expects a Viron server to be reachable at `http://localhost:9999`. On Windows, the bundled batch scripts start and stop it:
By default, Patchwork expects a Viron server to be reachable at `http://localhost:9999`. On Windows, the bundled batch scripts start and stop it:

```bat
up.bat
Expand All @@ -182,6 +182,19 @@ docker compose -f Viron/compose.yml down --remove-orphans --volumes

Note that `down.bat` passes `--volumes`, so stopping Viron this way also deletes its database volumes. Any environments recorded in `environments.json` will no longer resolve afterwards (see [Running](#running) for what happens then).

To reach a Viron server elsewhere, set either or both of these environment variables, which `main.py` and `console_view.py` both read:

- `PATCHWORK_VIRON_URL`, the URL including its scheme and without the port, which defaults to `http://localhost`
- `PATCHWORK_VIRON_PORT`, which defaults to `9999`

```bash
PATCHWORK_VIRON_URL=https://viron.example PATCHWORK_VIRON_PORT=8080 python main.py
```

A variable that is unset, empty or only whitespace leaves its default in place, and a trailing slash on the URL is ignored. A port that is not an integer from `1` to `65535` prints a message and falls back to `9999`. `up.bat` and `down.bat` still manage only the local server from the bundled Compose file, whichever address is set.

`environments.json` records each environment by its grid size alone, not by the server it was created on. After pointing Patchwork at a different Viron, the file should be deleted, or Patchwork run from another working directory, since a recorded ID could otherwise fail to load or resolve to an unrelated environment on the new server.

### Running

To launch the Patchwork visualization:
Expand Down Expand Up @@ -225,7 +238,7 @@ The window opens at 800x800 and can be resized. The render loop scales the grid

The render loop is capped at 60 frames per second via `RenderWindow.tick()`. Since each location is re-coloured at random on every frame, that cap is also what sets the rate at which the visualization re-randomizes.

`main.py` guards its entry point with `if __name__ == "__main__":`, so the module can be imported — by the test suite, or by another program wanting to call `main(gridSize, exitAfterCreate)` directly — without launching a window. `main()` also accepts `locationService` and `environmentService` arguments, which default to services pointed at `http://localhost:9999`, and a `reportUsage` argument, which defaults to `False`. The CLI entrypoint passes `reportUsage=True`; a direct `main()` call that leaves it at the default starts no usage reporting and does not create or modify `settings.json`.
`main.py` guards its entry point with `if __name__ == "__main__":`, so the module can be imported — by the test suite, or by another program wanting to call `main(gridSize, exitAfterCreate)` directly — without launching a window. `main()` also accepts `locationService` and `environmentService` arguments, which default to services pointed at the address described in [Starting Viron](#starting-viron), and a `reportUsage` argument, which defaults to `False`. The CLI entrypoint passes `reportUsage=True`; a direct `main()` call that leaves it at the default starts no usage reporting and does not create or modify `settings.json`.

### Batch environment creation

Expand All @@ -237,15 +250,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 `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:
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`, `viron_address.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`, `text_renderer.py`, `console_view.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`, `viron_address.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 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.
The same command, preceded by a `py_compile` syntax check of the top-level modules other than `text_renderer.py`, `console_view.py` and `viron_address.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

Expand Down
5 changes: 2 additions & 3 deletions console_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@

from Viron.src.main.python.preponderous.viron.services.locationService import LocationService
from text_renderer import renderLocations

url = "http://localhost"
port = 9999
from viron_address import getVironAddress

usage = "Usage: python console_view.py <environmentId>"

Expand Down Expand Up @@ -56,6 +54,7 @@ def main(argv, locationService=None):
print(usage)
return 2
if locationService is None:
url, port = getVironAddress()
locationService = LocationService(url, port)
try:
locations = locationService.get_locations_in_environment(environmentId)
Expand Down
2 changes: 1 addition & 1 deletion headless_run.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
Pygame, RenderWindow and Graphik are the real ones, rendering to SDL's dummy video driver.
Only Viron is replaced: its service modules are stubbed in sys.modules so that main.py can
be imported (they need Python 3.9+ and a populated submodule), and main() is handed
in-memory services instead of ones pointed at http://localhost:9999.
in-memory services instead of ones pointed at a Viron server.

Three scenarios are run, each in a fresh temporary working directory so that no
environments.json in the repository is read or written:
Expand Down
5 changes: 2 additions & 3 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from graphik import Graphik
from render_window import RenderWindow
from usage_reporting import startUsageReporting
from viron_address import getVironAddress
import os
import json
import sys
Expand All @@ -22,9 +23,6 @@
numGrids = 1
defaultGridSize = 50

url = "http://localhost"
port = 9999

usage = "Usage: python main.py [gridSize] [--exit-after-create]"

def log(message):
Expand Down Expand Up @@ -101,6 +99,7 @@ def main(gridSize=defaultGridSize, exitAfterCreate=False, locationService=None,
reportUsage (bool): Whether to start usage reporting for this process
"""
usage = startUsageReporting(log=log) if reportUsage else None
url, port = getVironAddress()
if locationService is None:
locationService = LocationService(url, port)
if environmentService is None:
Expand Down
9 changes: 9 additions & 0 deletions tests/test_console_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@ def test_a_service_pointed_at_the_local_viron_is_built_by_default(self):
self.assertEqual(output, "#\n")
service.assert_called_once_with("http://localhost", 9999)

def test_the_service_is_built_for_the_address_in_the_environment(self):
address = {"PATCHWORK_VIRON_URL": "http://viron", "PATCHWORK_VIRON_PORT": "8080"}
with patch.object(console_view, "LocationService") as service, patch.dict(os.environ, address):
service.return_value = fakeLocationService([headless_run.FakeLocation(0, 0)])

runMain(["console_view.py", "7"])

service.assert_called_once_with("http://viron", 8080)


class TestEntryPoint(unittest.TestCase):
def test_the_exit_status_of_main_reaches_the_process(self):
Expand Down
26 changes: 26 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,32 @@ def runMain(self, gridSize=10, exitAfterCreate=False, reportUsage=False):
reportUsage=reportUsage)


class TestVironAddress(MainTestCase):
def runMainBuildingServices(self, environment):
"""Run main() with no services supplied, and return the classes that built them."""
with patch("main.EnvironmentService", return_value=self.environmentService) as environmentService, \
patch("main.LocationService", return_value=self.locationService) as locationService, \
patch.dict(os.environ, environment):
for name in ("PATCHWORK_VIRON_URL", "PATCHWORK_VIRON_PORT"):
if name not in environment:
os.environ.pop(name, None)
main.main(10)
return environmentService, locationService

def test_both_services_are_pointed_at_the_local_viron_by_default(self):
environmentService, locationService = self.runMainBuildingServices({})

environmentService.assert_called_once_with("http://localhost", 9999)
locationService.assert_called_once_with("http://localhost", 9999)

def test_both_services_are_pointed_at_the_address_in_the_environment(self):
environmentService, locationService = self.runMainBuildingServices(
{"PATCHWORK_VIRON_URL": "http://viron", "PATCHWORK_VIRON_PORT": "8080"})

environmentService.assert_called_once_with("http://viron", 8080)
locationService.assert_called_once_with("http://viron", 8080)


class TestEnvironmentCreation(MainTestCase):
def test_creates_an_environment_when_the_cache_file_is_absent(self):
self.runMain(gridSize=10)
Expand Down
88 changes: 88 additions & 0 deletions tests/test_viron_address.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import contextlib
import importlib
import io
import os
import sys
import unittest
from unittest.mock import patch

import viron_address


def readAddress(environment):
"""Return the address read from exactly these variables, along with what was printed."""
output = io.StringIO()
with patch.dict(os.environ, environment), contextlib.redirect_stdout(output):
for name in (viron_address.URL_ENV_VAR, viron_address.PORT_ENV_VAR):
if name not in environment:
os.environ.pop(name, None)
address = viron_address.getVironAddress()
return address, output.getvalue()


class TestGetVironAddress(unittest.TestCase):
def test_defaults_to_the_local_viron(self):
address, output = readAddress({})

self.assertEqual(address, ("http://localhost", 9999))
self.assertEqual(output, "")

def test_reads_the_url_and_the_port_from_the_environment(self):
address, output = readAddress({"PATCHWORK_VIRON_URL": "https://viron.example",
"PATCHWORK_VIRON_PORT": "8080"})

self.assertEqual(address, ("https://viron.example", 8080))
self.assertEqual(output, "")

def test_each_variable_can_be_set_on_its_own(self):
self.assertEqual(readAddress({"PATCHWORK_VIRON_URL": "http://viron"})[0], ("http://viron", 9999))
self.assertEqual(readAddress({"PATCHWORK_VIRON_PORT": "8080"})[0], ("http://localhost", 8080))

def test_an_empty_or_blank_variable_leaves_the_default(self):
for value in ("", " "):
with self.subTest(value=value):
address, output = readAddress({"PATCHWORK_VIRON_URL": value, "PATCHWORK_VIRON_PORT": value})

self.assertEqual(address, ("http://localhost", 9999))
self.assertEqual(output, "")

def test_surrounding_whitespace_is_ignored(self):
address, _ = readAddress({"PATCHWORK_VIRON_URL": " http://viron ", "PATCHWORK_VIRON_PORT": " 8080 "})

self.assertEqual(address, ("http://viron", 8080))

def test_a_trailing_slash_is_removed_from_the_url(self):
address, _ = readAddress({"PATCHWORK_VIRON_URL": "http://viron/"})

self.assertEqual(address, ("http://viron", 9999))

def test_the_lowest_and_highest_ports_are_accepted(self):
for value, port in (("1", 1), ("65535", 65535)):
with self.subTest(value=value):
address, output = readAddress({"PATCHWORK_VIRON_PORT": value})

self.assertEqual(address, ("http://localhost", port))
self.assertEqual(output, "")

def test_an_invalid_port_falls_back_to_the_default_and_says_so(self):
for value in ("http", "0", "-1", "65536", "99.5"):
with self.subTest(value=value):
address, output = readAddress({"PATCHWORK_VIRON_PORT": value})

self.assertEqual(address, ("http://localhost", 9999))
self.assertEqual(output, f"Invalid PATCHWORK_VIRON_PORT value {value!r}, using default of 9999.\n")

def test_an_invalid_port_leaves_the_url_in_force(self):
address, _ = readAddress({"PATCHWORK_VIRON_URL": "http://viron", "PATCHWORK_VIRON_PORT": "http"})

self.assertEqual(address, ("http://viron", 9999))


class TestImport(unittest.TestCase):
def test_the_module_can_be_imported_without_pygame(self):
with patch.dict(sys.modules, {"pygame": None}):
importlib.reload(viron_address)


if __name__ == "__main__":
unittest.main()
47 changes: 47 additions & 0 deletions viron_address.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
Work out where the Viron server is, for main.py and console_view.py alike.

This has its own module because console_view.py cannot import main.py without pulling in
Pygame.
"""
import os

URL_ENV_VAR = "PATCHWORK_VIRON_URL"
PORT_ENV_VAR = "PATCHWORK_VIRON_PORT"

defaultUrl = "http://localhost"
defaultPort = 9999

def parsePort(value):
"""
Read a port number, falling back to the default if the value cannot be one.

Args:
value (str): The text of the port

Returns:
int: The port, or the default port if the value is not an integer from 1 to 65535
"""
try:
port = int(value)
except ValueError:
port = 0
if port < 1 or port > 65535:
print(f"Invalid {PORT_ENV_VAR} value {value!r}, using default of {defaultPort}.")
return defaultPort
return port

def getVironAddress():
"""
Read the address of the Viron server from the environment.

A variable that is unset, empty or only whitespace leaves its default in place.

Returns:
tuple: The URL, without a trailing slash, and the port
"""
# Viron's services append ":<port>/api/v1/..." to the URL, so a trailing slash would put the port in the path
url = os.environ.get(URL_ENV_VAR, "").strip().rstrip("/") or defaultUrl
portValue = os.environ.get(PORT_ENV_VAR, "").strip()
port = parsePort(portValue) if portValue else defaultPort
return url, port
Loading