Commit 1744c28d authored by Mickaël Desfrênes's avatar Mickaël Desfrênes
Browse files

Add documented Makefile and isolated integration test runner

parent 6790ab23
Loading
Loading
Loading
Loading
+54
Changes for Makefile: 54 added lines, 0 removed lines.
Original line number Diff line number Diff line
.DEFAULT_GOAL := help

UV ?= uv
TEST_ARGS ?= -q
CIRCE_ARGS ?=

.PHONY: help setup setup-prod lock lock-check build test test-live format format-check check serve workers run clean

help: ## Show available tasks and configuration
	@printf 'Usage: make <target>\n\n'
	@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / {printf "  %-16s %s\n", $$1, $$2}' $(MAKEFILE_LIST)
	@printf '\nVariables: UV=uv, TEST_ARGS="-q", CIRCE_ARGS=""\n'
	@printf 'Example: make test TEST_ARGS="-v -k polling"\n'

setup: ## Create .venv and install locked runtime and development dependencies
	$(UV) sync --locked

setup-prod: ## Install only locked runtime dependencies in .venv
	$(UV) sync --locked --no-dev

lock: ## Update uv.lock after editing dependencies in pyproject.toml
	$(UV) lock

lock-check: ## Check that uv.lock matches pyproject.toml
	$(UV) lock --check

build: ## Build the source archive and wheel in dist/
	$(UV) build

test: ## Run integration tests against an automatically managed temporary server
	$(UV) run --locked python scripts/run_tests.py $(TEST_ARGS)

test-live: ## Run tests against an existing server configured with CIRCE_* variables
	$(UV) run --locked pytest test.py $(TEST_ARGS)

format: ## Format Python sources, tests and scripts with Black
	$(UV) run --locked black circe test.py scripts

format-check: ## Check Python formatting without changing files
	$(UV) run --locked black --check circe test.py scripts

check: lock-check test ## Check the lockfile and run integration tests

serve: ## Start the HTTP server (accepts CIRCE_ARGS and CIRCE_* variables)
	$(UV) run --locked --no-dev circe serve $(CIRCE_ARGS)

workers: ## Start transformation workers (accepts CIRCE_ARGS and CIRCE_* variables)
	$(UV) run --locked --no-dev circe start-workers $(CIRCE_ARGS)

run: ## Start the HTTP server and workers (accepts CIRCE_ARGS and CIRCE_* variables)
	$(UV) run --locked --no-dev circe run $(CIRCE_ARGS)

clean: ## Remove distribution artifacts and the local pytest cache
	rm -rf dist .pytest_cache
+30 −1
Changes for README.md: 30 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -133,6 +133,25 @@ Un serveur de référence est implémenté en Python. Deux composants sont fourn

### Installation et démarrage du service

Un Makefile documente les tâches disponibles avec `make` ou `make help`.
uv doit être installé au préalable. Les principales commandes sont:

    make setup         # environnement de développement
    make setup-prod    # dépendances du service uniquement
    make build         # distributions source et wheel dans dist/
    make test          # tests avec un serveur temporaire isolé
    make check         # vérification du verrou et tests
    make run           # service HTTP et workers

`make format` applique Black et `make format-check` vérifie le formatage.
`make lock` actualise `uv.lock` après modification des dépendances.
Les variables `UV`, `TEST_ARGS` et `CIRCE_ARGS` sont configurables, par exemple:

    make test TEST_ARGS="-v -k polling"
    make serve CIRCE_ARGS="--port 8080 --workers 1"

Les commandes uv équivalentes sont détaillées ci-dessous.

Depuis la racine du dépôt, installation de Circe et de ses dépendances de développement:

    uv sync --locked
@@ -352,7 +371,17 @@ et un [outil en ligne de commande implémenté en Go](https://git.unicaen.fr/mic

Un ensemble de tests exécutables par Pytest sont disponibles dans le fichier ```test.py```.

Ces tests nécessitent un service Circe démarré avec la transformation `sleep_well` disponible,
Pour les lancer sans configuration supplémentaire:

    make test

Cette commande démarre un serveur local sur un port libre avec la transformation `sleep_well`,
exécute les tests dans un dossier temporaire avec une configuration et une base d'authentification
isolées, puis arrête le serveur et supprime le dossier. Les transformations sont exécutées en mode
immédiat, sans workers séparés.

Pour tester un serveur déjà démarré, utiliser `make test-live`. Ces tests nécessitent
un service proposant la transformation `sleep_well`,
ainsi que la même configuration (`CIRCE_WORKING_DIR`, hôte et port) que le processus de test.
Après `uv sync --locked`, les lancer explicitement avec:

+1 −1
Changes for pyproject.toml: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -35,4 +35,4 @@ build-backend = "uv_build"
[tool.uv.build-backend]
module-name = "circe"
module-root = ""
source-include = ["test.py", "test_assets/**"]
source-include = ["Makefile", "scripts/**", "test.py", "test_assets/**"]
+110
Changes for scripts/run_tests.py: 110 added lines, 0 removed lines.
Original line number Diff line number Diff line
"""Run the existing integration suite with an isolated, temporary Circe server."""

import os
from pathlib import Path
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
from urllib.error import URLError
from urllib.request import urlopen


def stop_server(process):
    """Stop the server and the Sanic worker processes it started."""

    def send_signal(sig):
        try:
            if os.name == "posix":
                os.killpg(process.pid, sig)
            else:
                process.send_signal(sig)
        except ProcessLookupError:
            pass

    send_signal(signal.SIGTERM)
    try:
        process.wait(timeout=10)
    except subprocess.TimeoutExpired:
        if os.name == "posix":
            send_signal(signal.SIGKILL)
        else:
            process.kill()
        process.wait(timeout=10)


def main():
    repo = Path(__file__).resolve().parent.parent
    with tempfile.TemporaryDirectory(prefix="circe-test-") as directory:
        root = Path(directory)
        shutil.copy2(repo / "test.py", root / "test.py")
        shutil.copytree(repo / "test_assets", root / "test_assets")
        (root / "test_transformations.py").write_text(
            "from time import sleep\n\n"
            "def sleep_well(working_dir, logger, options):\n"
            '    sleep(options.get("time", 0))\n',
            encoding="utf-8",
        )

        # Avoid inheriting service settings or loading the repository's .env.
        env = {
            key: value
            for key, value in os.environ.items()
            if not key.startswith("CIRCE_")
        }
        with socket.socket() as sock:
            sock.bind(("127.0.0.1", 0))
            port = sock.getsockname()[1]
        env.update(
            CIRCE_HOST="127.0.0.1",
            CIRCE_PORT=str(port),
            CIRCE_WORKING_DIR=str(root / "state") + os.sep,
            CIRCE_TRANSFORMATIONS_MODULE="test_transformations",
            CIRCE_IMMEDIATE_MODE="1",
            CIRCE_USE_AUTH="1",
            CIRCE_ENABLE_WEB_UI="0",
            PYTHONPATH=str(root),
        )

        exit_code = 1
        with (root / "server.log").open("w+", encoding="utf-8") as log:
            server = subprocess.Popen(
                [sys.executable, "-m", "circe", "serve"],
                cwd=root,
                env=env,
                stdout=log,
                stderr=log,
                start_new_session=os.name == "posix",
            )
            try:
                deadline = time.monotonic() + 20
                while time.monotonic() < deadline:
                    if server.poll() is not None:
                        raise RuntimeError("Circe exited before becoming ready")
                    try:
                        with urlopen(f"http://127.0.0.1:{port}/version/", timeout=1):
                            break
                    except (URLError, TimeoutError):
                        time.sleep(0.1)
                else:
                    raise RuntimeError("Circe did not become ready within 20 seconds")

                exit_code = subprocess.run(
                    [sys.executable, "-m", "pytest", "test.py", *sys.argv[1:]],
                    cwd=root,
                    env=env,
                    timeout=120,
                ).returncode
            finally:
                stop_server(server)
                if exit_code:
                    log.seek(0)
                    print("\nCirce server log:\n" + log.read(), file=sys.stderr)
        return exit_code


if __name__ == "__main__":
    sys.exit(main())