diff --git a/Taskfile.yaml b/Taskfile.yaml index fa4d31f..39c6afb 100644 --- a/Taskfile.yaml +++ b/Taskfile.yaml @@ -235,6 +235,11 @@ tasks: cmds: - uv lock --upgrade-package $PACKAGE + upgrade:check: + desc: "End-to-end check of a dependency upgrade against a base ref (usage: task upgrade:check BASE=master -- --docker)" + cmds: + - scripts/upgrade-check/run.sh --base {{.BASE | default "master"}} {{.CLI_ARGS}} + tests: desc: Run all tests cmds: diff --git a/scripts/upgrade-check/README.md b/scripts/upgrade-check/README.md new file mode 100644 index 0000000..7616611 --- /dev/null +++ b/scripts/upgrade-check/README.md @@ -0,0 +1,80 @@ +# Upgrade check + +End-to-end check for dependency upgrades (Wagtail, Django, ...). It migrates +data created with the **old** dependencies, then drives the Wagtail admin and +the public site in a headless browser with the **new** ones. + +The project's unit tests do not cover the admin or page rendering, so run this +before merging any Wagtail or Django upgrade. + +## Usage + +From the checkout of the upgrade branch (for example a worktrunk worktree): + +```bash +task upgrade:check # compare against master +task upgrade:check BASE=v2026.10 # compare against another ref +task upgrade:check -- --docker # also build the Docker image + +# or directly +scripts/upgrade-check/run.sh [--base REF] [--docker] [--debug] +``` + +The script exits with status 0 when every step passes, 1 otherwise. + +## What it does + +1. Starts a disposable PostgreSQL 17 container (`127.0.0.1:15432`). +2. Checks out the base ref in a temporary worktree, installs its dependencies, + runs the migrations and seeds representative content (`seed.py`): + - a page tree: home, nested `HomePage`, `SimplePage`s and an unpublished draft + - rich text with bold, italic, external, page and document links, lists and an embedded image + - PNG and WebP images, a document + - a `PageSegment`, a `Meetup`, a sponsor with a sponsorship level, a redirect +3. With the current checkout: installs the new dependencies, lists and applies + the pending migrations, runs `check`, `makemigrations --check` and + `collectstatic --clear`. +4. Renders the public pages before and after the upgrade and diffs the HTML + (`snapshot.py`). A difference is reported as a warning, not a failure. +5. Starts `runserver` with `DEBUG` off (like production) and runs + `browser_check.py` with Playwright: + - admin login and the page explorer in the sidebar + - page listing and search + - editing rich text on an existing page, publishing it and checking the public page + - creating and publishing a new page + - preview, revision history and the unpublished draft + - saving the `PageSegment` and `Meetup` snippets + - images, documents, sites, users and redirects + - the Django admin (sponsors) + - the public pages, the redirect and the 404 page +6. Fails when a step fails, when the application returns a 4xx/5xx response + or when the server log contains a traceback. + +The container, the server and the base worktree are always removed at the end. +Logs, HTML snapshots and screenshots stay in the run directory printed at the +end (`$TMPDIR/upgrade-check.XXXXXX`). + +## Requirements + +- Docker, uv, git, curl. +- Playwright is fetched by `uv` on the fly; its Chromium is installed on the + first run. To use an existing browser instead, set `CHROMIUM_PATH` + (for example `CHROMIUM_PATH=/usr/bin/chromium-browser`). + +## Configuration + +| Variable | Default | Purpose | +|---|---|---| +| `UPGRADE_CHECK_PG_PORT` | `15432` | Host port of the PostgreSQL container | +| `UPGRADE_CHECK_SERVER_PORT` | `18000` | Port of the Django server | +| `UPGRADE_CHECK_ADMIN_PASSWORD` | `upgrade-check` | Password of the seeded `admin` user | +| `PLAYWRIGHT_VERSION` | `1.65.2` | Playwright version used by the browser check | +| `CHROMIUM_PATH` | unset | Chromium binary to use instead of Playwright's | + +## Limits + +- The data is synthetic. Before deploying, also migrate a copy of the + production database (`task database:pull`). +- `seed.py` uses the project models: if a model changes, update the seed. +- Known noise in the browser report: the `axe.run` console messages come from + the Wagtail userbar accessibility checker. diff --git a/scripts/upgrade-check/browser_check.py b/scripts/upgrade-check/browser_check.py new file mode 100644 index 0000000..e0a065e --- /dev/null +++ b/scripts/upgrade-check/browser_check.py @@ -0,0 +1,269 @@ +"""Drive the Wagtail admin and public site in a headless browser. + +Usage: python browser_check.py + +Environment: + UPGRADE_CHECK_SERVER_PORT port of the running server (default 18000) + UPGRADE_CHECK_ADMIN_PASSWORD admin password set by seed.py + CHROMIUM_PATH optional Chromium binary; Playwright's bundled + browser is used when unset + +Exits with status 1 when a step fails. +""" + +import os +import re +import sys +from pathlib import Path + +from playwright.sync_api import expect, sync_playwright + +BASE = f"http://127.0.0.1:{os.environ.get('UPGRADE_CHECK_SERVER_PORT', '18000')}" +PASSWORD = os.environ.get("UPGRADE_CHECK_ADMIN_PASSWORD", "upgrade-check") +OUT = Path(sys.argv[1]) +OUT.mkdir(parents=True, exist_ok=True) + +# Draftail syncs its hidden form input asynchronously: wait before saving, +# like a human would, or the typed text is not submitted. +DRAFTAIL_SYNC_MS = 800 + +results = [] +console_errors = [] +bad_responses = [] +steps = [] + + +def step(name): + def decorator(fn): + def run(page): + try: + fn(page) + results.append(("PASS", name, "")) + except Exception as exc: # noqa: BLE001 - report every failure + results.append(("FAIL", name, str(exc).splitlines()[0][:300])) + finally: + slug = re.sub(r"\W+", "-", name.lower()).strip("-") + page.screenshot( + path=OUT / f"{len(results):02d}-{slug}.png", full_page=True + ) + + steps.append(run) + return run + + return decorator + + +def page_id(page, title): + """Return the id of the page with this title, using the admin search.""" + page.goto(f"{BASE}/admin/pages/search/?q={title}") + link = page.locator("main").get_by_role("link", name=title, exact=True).first + return re.search(r"/pages/(\d+)/", link.get_attribute("href")).group(1) + + +def open_editor(page, title): + page.goto(f"{BASE}/admin/pages/{page_id(page, title)}/edit/") + page.wait_for_load_state("networkidle") + + +def publish(page): + page.wait_for_timeout(DRAFTAIL_SYNC_MS) + page.locator("[data-w-dropdown-target='toggle']").last.click() + page.get_by_role("button", name="Publish").click() + expect(page.locator(".messages")).to_contain_text("published", timeout=15000) + + +@step("Admin login") +def login(page): + page.goto(f"{BASE}/admin/login/") + page.fill("#id_username", "admin") + page.fill("#id_password", PASSWORD) + page.click("button[type=submit]") + page.wait_for_url(f"{BASE}/admin/") + expect(page.locator("main")).to_contain_text("Pages") + + +@step("Page explorer (sidebar)") +def explorer(page): + page.goto(f"{BASE}/admin/") + page.wait_for_load_state("networkidle") + panel = page.locator("#wagtail-sidebar") + panel.get_by_text("Pages", exact=True).click() + expect(panel).to_contain_text("Python Ireland", timeout=10000) + panel.locator("a, button").filter( + has_text=re.compile("Python Ireland") + ).last.click() + expect(panel).to_contain_text("About", timeout=10000) + expect(panel).to_contain_text("Meetups") + + +@step("Page listing and search") +def listing(page): + page.goto(f"{BASE}/admin/pages/{page_id(page, 'Python Ireland')}/") + expect(page.locator("main")).to_contain_text("About") + expect(page.locator("main")).to_contain_text("Draft page") + page.goto(f"{BASE}/admin/pages/search/?q=Conduct") + expect(page.locator("main")).to_contain_text("Code of Conduct") + + +@step("Edit rich text and publish an existing page") +def edit_publish(page): + open_editor(page, "About") + editor = page.locator(".Draftail-Editor .public-DraftEditor-content").first + editor.click() + page.keyboard.press("Control+End") + page.keyboard.type(" Edited by the upgrade check.", delay=30) + page.keyboard.press("Enter") + page.keyboard.press("Control+b") + page.keyboard.type("Bold line", delay=30) + expect(editor).to_contain_text("Edited by the upgrade check.") + publish(page) + page.goto(f"{BASE}/about/") + expect(page.locator("body")).to_contain_text("Edited by the upgrade check.") + bold = page.locator("b, strong").filter(has_text="Bold line") + assert bold.count() == 1, "bold text missing on the public page" + + +@step("Create a new page with rich text and publish") +def create_page(page): + home_id = page_id(page, "Python Ireland") + page.goto(f"{BASE}/admin/pages/add/core/simplepage/{home_id}/") + page.wait_for_load_state("networkidle") + page.fill("#id_title", "Upgrade check page") + page.get_by_role("button", name=re.compile("Insert a block")).first.click() + page.get_by_role("option", name=re.compile("Paragraph")).click() + editor = page.locator(".Draftail-Editor .public-DraftEditor-content").first + editor.click() + page.keyboard.type("Created by the upgrade check", delay=30) + expect(editor).to_contain_text("Created by the upgrade check") + publish(page) + page.goto(f"{BASE}/upgrade-check-page/") + expect(page.locator("body")).to_contain_text("Created by the upgrade check") + + +@step("Preview and revision history") +def preview_history(page): + about_id = page_id(page, "About") + response = page.request.get(f"{BASE}/admin/pages/{about_id}/edit/preview/?mode=") + assert response.status in (200, 400), f"preview status {response.status}" + page.goto(f"{BASE}/admin/pages/{about_id}/history/") + expect(page.locator("main")).to_contain_text("Published") + + +@step("Draft page (unpublished) opens in editor") +def draft_page(page): + open_editor(page, "Draft page") + expect(page.locator("#id_title")).to_have_value("Draft page") + + +@step("Snippets: PageSegment and Meetup") +def snippets(page): + page.goto(f"{BASE}/admin/snippets/") + expect(page.locator("main")).to_contain_text("Page segments") + expect(page.locator("main")).to_contain_text("Meetups") + page.goto(f"{BASE}/admin/snippets/core/pagesegment/") + page.locator("main").get_by_role("link", name=re.compile("Sidebar")).first.click() + expect(page.locator("#id_title")).to_have_value("Sidebar") + page.get_by_role("button", name="Save").click() + expect(page.locator(".messages")).to_contain_text("updated", timeout=15000) + page.goto(f"{BASE}/admin/snippets/meetups/meetup/") + page.locator("main").get_by_role("link", name="November Meetup").first.click() + expect(page.locator("#id_name")).to_have_value("November Meetup") + page.get_by_role("button", name="Save").click() + expect(page.locator(".messages")).to_contain_text("updated", timeout=15000) + + +@step("Images and documents") +def images_documents(page): + page.goto(f"{BASE}/admin/images/") + expect(page.locator("main")).to_contain_text("banner-webp") + page.locator("main").get_by_role( + "link", name=re.compile("banner-webp") + ).first.click() + expect(page.locator("#id_title")).to_have_value("banner-webp") + page.goto(f"{BASE}/admin/documents/") + expect(page.locator("main")).to_contain_text("CoC") + + +@step("Settings: sites, users, redirects") +def settings_pages(page): + for path, text in [ + ("/admin/sites/", "127.0.0.1"), + ("/admin/users/", "admin"), + ("/admin/redirects/", "/old-about"), + ]: + page.goto(BASE + path) + expect(page.locator("main")).to_contain_text(text) + + +@step("Django admin: sponsors") +def django_admin(page): + page.goto(f"{BASE}/django-admin/") + expect(page.locator("body")).to_contain_text("Sponsors") + page.goto(f"{BASE}/django-admin/sponsors/sponsor/") + expect(page.locator("body")).to_contain_text("Acme") + + +@step("Public pages render (home, nested, redirect, 404)") +def public_pages(page): + for path, text in [ + ("/", "Python Ireland"), + ("/meetups/", "Meetups"), + ("/meetups/coc/", "Code of Conduct"), + ]: + response = page.goto(BASE + path) + assert response.status == 200, f"{path} -> {response.status}" + expect(page.locator("body")).to_contain_text(text) + assert page.locator("img").count() >= 2, f"{path}: images missing" + page.goto(f"{BASE}/old-about") + assert page.url.endswith("/about/"), f"redirect landed on {page.url}" + response = page.goto(f"{BASE}/nope/") + assert response.status == 404 + + +def main(): + with sync_playwright() as playwright: + launch_options = {} + if os.environ.get("CHROMIUM_PATH"): + launch_options["executable_path"] = os.environ["CHROMIUM_PATH"] + browser = playwright.chromium.launch(**launch_options) + page = browser.new_page(viewport={"width": 1400, "height": 900}) + page.on( + "console", + lambda m: ( + m.type == "error" and console_errors.append(f"{page.url} :: {m.text}") + ), + ) + page.on( + "pageerror", + lambda e: console_errors.append(f"{page.url} :: PAGEERROR {e}"), + ) + page.on( + "response", + lambda r: ( + r.status >= 400 + and not r.url.endswith(("/nope/", "/favicon.ico")) + and bad_responses.append(f"{r.status} {r.request.method} {r.url}") + ), + ) + for run in steps: + run(page) + browser.close() + + for status, name, error in results: + print(f" {status} {name}") + if error: + print(f" -> {error}") + print(f"\n JS console errors: {len(console_errors)}") + for error in dict.fromkeys(console_errors): + print(f" {error[:300]}") + print(f" HTTP >= 400 responses: {len(bad_responses)}") + for response in dict.fromkeys(bad_responses): + print(f" {response[:300]}") + print(f"\n Screenshots: {OUT}") + + failed = [r for r in results if r[0] == "FAIL"] + return 1 if failed or bad_responses else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/upgrade-check/run.sh b/scripts/upgrade-check/run.sh new file mode 100755 index 0000000..0cac0d1 --- /dev/null +++ b/scripts/upgrade-check/run.sh @@ -0,0 +1,170 @@ +#!/usr/bin/env bash +# Upgrade check: verify that a dependency upgrade (Wagtail, Django, ...) does +# not break the site, by migrating real pre-existing data and driving the +# admin in a headless browser. +# +# 1. Start a disposable PostgreSQL 17 container. +# 2. Check out the base ref (default: master) in a temporary worktree, +# migrate and seed representative content with the *old* dependencies. +# 3. With the current checkout (the upgrade branch): migrate, run checks, +# collectstatic --clear. +# 4. Render the public pages before and after, and diff the HTML. +# 5. Run the server (DEBUG off) and drive the admin with Playwright. +# +# Usage: scripts/upgrade-check/run.sh [--base REF] [--docker] [--debug] +# See scripts/upgrade-check/README.md for details. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +TARGET_DIR="$(git -C "$SCRIPT_DIR" rev-parse --show-toplevel)" + +BASE_REF="master" +BUILD_DOCKER=0 +export UPGRADE_CHECK_DEBUG=0 +export UPGRADE_CHECK_PG_PORT="${UPGRADE_CHECK_PG_PORT:-15432}" +export UPGRADE_CHECK_SERVER_PORT="${UPGRADE_CHECK_SERVER_PORT:-18000}" +export UPGRADE_CHECK_ADMIN_PASSWORD="${UPGRADE_CHECK_ADMIN_PASSWORD:-upgrade-check}" +PLAYWRIGHT_VERSION="${PLAYWRIGHT_VERSION:-1.65.2}" + +usage() { + sed -n '2,15p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//' + exit "${1:-0}" +} + +while [[ $# -gt 0 ]]; do + case "$1" in + --base) BASE_REF="$2"; shift 2 ;; + --docker) BUILD_DOCKER=1; shift ;; + --debug) UPGRADE_CHECK_DEBUG=1; shift ;; + -h|--help) usage 0 ;; + *) echo "Unknown option: $1" >&2; usage 1 ;; + esac +done + +for tool in docker git uv curl; do + command -v "$tool" >/dev/null || { echo "Missing required tool: $tool" >&2; exit 1; } +done + +RUN_DIR="$(mktemp -d "${TMPDIR:-/tmp}/upgrade-check.XXXXXX")" +export UPGRADE_CHECK_DIR="$RUN_DIR" +BASE_DIR="$RUN_DIR/base" +PG_CONTAINER="upgrade-check-pg-$$" +SERVER_PID="" + +section() { printf '\n\033[1m== %s\033[0m\n' "$*"; } + +# Drop the noise printed by the project settings on every command. +quiet() { grep -vE "PROJECT_ROOT=|No DATABASE_URL environment variable|objects imported automatically|^$" || true; } + +# Kill a process and all its descendants (the server runs as subshell -> uv -> python). +kill_tree() { + local child + for child in $(pgrep -P "$1" 2>/dev/null); do + kill_tree "$child" + done + kill "$1" 2>/dev/null || true +} + +cleanup() { + [[ -n "$SERVER_PID" ]] && kill_tree "$SERVER_PID" + docker rm -f "$PG_CONTAINER" >/dev/null 2>&1 || true + git -C "$TARGET_DIR" worktree remove --force "$BASE_DIR" >/dev/null 2>&1 || true +} +trap cleanup EXIT + +# manage : run manage.py with the upgrade check settings. +manage() { + local checkout="$1"; shift + ( + cd "$checkout" + env -u DATABASE_URL -u VIRTUAL_ENV PYTHONPATH="$SCRIPT_DIR" \ + uv run --frozen python pythonie/manage.py "$@" --settings=upgrade_check_settings + ) +} + +wagtail_version() { + (cd "$1" && env -u VIRTUAL_ENV uv run --frozen python -c "import wagtail, django; print(f'Wagtail {wagtail.__version__}, Django {django.__version__}')") +} + +section "Run directory: $RUN_DIR" +echo "Base ref: $BASE_REF | Target: $TARGET_DIR ($(git -C "$TARGET_DIR" rev-parse --abbrev-ref HEAD))" + +if [[ "$BUILD_DOCKER" == 1 ]]; then + section "Docker build" + docker build -t python.ie/website-dev:upgrade-check "$TARGET_DIR" > "$RUN_DIR/docker-build.log" 2>&1 \ + || { echo "Docker build failed, see $RUN_DIR/docker-build.log"; exit 1; } + docker run --rm python.ie/website-dev:upgrade-check python -c \ + "import wagtail, django; print(f'Image OK: Wagtail {wagtail.__version__}, Django {django.__version__}')" +fi + +section "PostgreSQL 17 (port $UPGRADE_CHECK_PG_PORT)" +docker run -d --name "$PG_CONTAINER" -e POSTGRES_PASSWORD=pythonie -e POSTGRES_DB=pythonie \ + -p "127.0.0.1:$UPGRADE_CHECK_PG_PORT:5432" postgres:17 >/dev/null +for _ in $(seq 60); do + docker exec "$PG_CONTAINER" pg_isready -U postgres -q 2>/dev/null && break + sleep 1 +done +docker exec "$PG_CONTAINER" pg_isready -U postgres + +section "Base ($BASE_REF): install, migrate, seed" +git -C "$TARGET_DIR" worktree add --detach --quiet "$BASE_DIR" "$BASE_REF" +(cd "$BASE_DIR" && env -u VIRTUAL_ENV uv sync --frozen --all-groups --quiet) +wagtail_version "$BASE_DIR" +manage "$BASE_DIR" migrate --verbosity 0 2>&1 | quiet +manage "$BASE_DIR" shell --verbosity 0 -c "exec(open('$SCRIPT_DIR/seed.py').read())" 2>&1 | quiet +# Snapshots render with DEBUG on: static files are only collected later, and +# both sides must render with the same settings to be comparable. +UPGRADE_CHECK_DEBUG=1 UPGRADE_CHECK_SNAPSHOT="$RUN_DIR/snapshot-base" \ + manage "$BASE_DIR" shell --verbosity 0 -c "exec(open('$SCRIPT_DIR/snapshot.py').read())" 2>&1 | quiet | grep -v "Not Found" + +section "Target: install, migrate, checks, collectstatic" +(cd "$TARGET_DIR" && env -u VIRTUAL_ENV uv sync --frozen --all-groups --quiet) +wagtail_version "$TARGET_DIR" +echo "Pending migrations:" +manage "$TARGET_DIR" showmigrations --plan 2>&1 | quiet | grep '\[ \]' || echo " (none)" +manage "$TARGET_DIR" migrate 2>&1 | quiet | grep -E "Applying|No migrations" || true +manage "$TARGET_DIR" check 2>&1 | quiet +manage "$TARGET_DIR" makemigrations --check --dry-run 2>&1 | quiet +manage "$TARGET_DIR" collectstatic --clear --noinput 2>&1 | quiet | tail -1 + +section "Public pages: before/after HTML diff" +UPGRADE_CHECK_DEBUG=1 UPGRADE_CHECK_SNAPSHOT="$RUN_DIR/snapshot-target" \ + manage "$TARGET_DIR" shell --verbosity 0 -c "exec(open('$SCRIPT_DIR/snapshot.py').read())" 2>&1 | quiet | grep -v "Not Found" +if diff -r "$RUN_DIR/snapshot-base" "$RUN_DIR/snapshot-target" > "$RUN_DIR/snapshot.diff"; then + echo "HTML identical before and after the upgrade." +else + echo "WARNING: rendered HTML changed, review $RUN_DIR/snapshot.diff:" + head -40 "$RUN_DIR/snapshot.diff" +fi + +section "Browser check (server on port $UPGRADE_CHECK_SERVER_PORT, DEBUG=$UPGRADE_CHECK_DEBUG)" +manage "$TARGET_DIR" runserver "127.0.0.1:$UPGRADE_CHECK_SERVER_PORT" --noreload > "$RUN_DIR/server.log" 2>&1 & +SERVER_PID=$! +for _ in $(seq 60); do + curl -fs -o /dev/null "http://127.0.0.1:$UPGRADE_CHECK_SERVER_PORT/" && break + sleep 1 +done +curl -fs -o /dev/null "http://127.0.0.1:$UPGRADE_CHECK_SERVER_PORT/" \ + || { echo "Server did not start, see $RUN_DIR/server.log"; exit 1; } + +if [[ -z "${CHROMIUM_PATH:-}" ]]; then + uv run --quiet --no-project --with "playwright==$PLAYWRIGHT_VERSION" playwright install chromium >/dev/null +fi +status=0 +(cd "$RUN_DIR" && uv run --quiet --no-project --with "playwright==$PLAYWRIGHT_VERSION" \ + python -I "$SCRIPT_DIR/browser_check.py" "$RUN_DIR/screenshots") || status=$? + +if grep -qE "Traceback|\" 5[0-9]{2} " "$RUN_DIR/server.log"; then + echo "WARNING: server errors found in $RUN_DIR/server.log" + status=1 +fi + +section "Result" +if [[ "$status" == 0 ]]; then + echo "Upgrade check PASSED." +else + echo "Upgrade check FAILED." +fi +echo "Artifacts (logs, HTML snapshots, screenshots): $RUN_DIR" +exit "$status" diff --git a/scripts/upgrade-check/seed.py b/scripts/upgrade-check/seed.py new file mode 100644 index 0000000..c21ce59 --- /dev/null +++ b/scripts/upgrade-check/seed.py @@ -0,0 +1,149 @@ +"""Populate the database with representative content. + +Run with the *base* version of the code (before the upgrade) through +`manage.py shell`, so that the upgrade check migrates real, pre-existing data. +""" + +import io +import json +import os +import uuid +from datetime import timedelta + +from core.models import ( + HomePage, + HomePageSegment, + HomePageSponsorRelationship, + PageSegment, + SimplePage, +) +from django.contrib.auth import get_user_model +from django.core.files.base import ContentFile +from django.core.files.images import ImageFile +from django.utils import timezone +from meetups.models import Meetup, MeetupSponsorRelationship +from PIL import Image as PILImage +from sponsors.models import Sponsor, SponsorshipLevel +from wagtail.contrib.redirects.models import Redirect +from wagtail.documents.models import Document +from wagtail.images.models import Image +from wagtail.models import Page, Site + +ADMIN_PASSWORD = os.environ.get("UPGRADE_CHECK_ADMIN_PASSWORD", "upgrade-check") +SERVER_PORT = int(os.environ.get("UPGRADE_CHECK_SERVER_PORT", "18000")) + +User = get_user_model() +if not User.objects.filter(username="admin").exists(): + User.objects.create_superuser("admin", "admin@example.com", ADMIN_PASSWORD) + + +def make_image(title, fmt, color): + buffer = io.BytesIO() + PILImage.new("RGB", (320, 200), color).save(buffer, fmt) + buffer.seek(0) + return Image.objects.create( + title=title, file=ImageFile(buffer, name=f"{title}.{fmt.lower()}") + ) + + +png = make_image("logo-png", "PNG", "navy") +webp = make_image("banner-webp", "WEBP", "darkgreen") +document = Document.objects.create( + title="CoC", file=ContentFile(b"%PDF-1.4 upgrade check", name="coc.pdf") +) + +gold = SponsorshipLevel.objects.create(level=1000, name="Gold") +acme = Sponsor.objects.create( + name="Acme", description="Acme Corp", logo=png, url="https://example.com" +) + +# Replace the default Wagtail welcome page with our own tree. +root = Page.objects.get(depth=1) +for page in Page.objects.filter(depth=2): + page.delete() +root.refresh_from_db() + +RICH_TEXT = ( + "

Welcome

" + "

Hello bold, italic, " + 'ext link, ' + 'internal, ' + f'doc

' + "
  • one
  • two
  1. first
" + f'' +) + + +def stream_body(linked_page_id): + return json.dumps( + [ + {"type": "heading", "value": "Python Ireland", "id": str(uuid.uuid4())}, + { + "type": "paragraph", + "value": RICH_TEXT.format(page_id=linked_page_id), + "id": str(uuid.uuid4()), + }, + {"type": "image", "value": webp.id, "id": str(uuid.uuid4())}, + {"type": "image", "value": png.id, "id": str(uuid.uuid4())}, + { + "type": "html", + "value": "
raw
", + "id": str(uuid.uuid4()), + }, + ] + ) + + +home = HomePage( + title="Python Ireland", + slug="home", + body="[]", + show_meetups=True, + show_sponsors=True, +) +root.add_child(instance=home) +Site.objects.all().delete() +Site.objects.create( + hostname="127.0.0.1", + port=SERVER_PORT, + root_page=home, + is_default_site=True, + site_name="pythonie", +) + +about = SimplePage(title="About", slug="about", body="[]") +home.add_child(instance=about) +meetups = HomePage(title="Meetups", slug="meetups", body="[]", show_meetups=True) +home.add_child(instance=meetups) +coc = SimplePage(title="Code of Conduct", slug="coc", body="[]") +meetups.add_child(instance=coc) +draft = SimplePage(title="Draft page", slug="draft", body="[]", live=False) +home.add_child(instance=draft) + +for page in (home, about, meetups, coc): + page.body = stream_body(about.id) + page.save_revision().publish() +draft.body = stream_body(home.id) +draft.save_revision() + +segment = PageSegment.objects.create( + title="Sidebar", body="

Segment text

", location="right" +) +HomePageSegment.objects.create(homepage=home, segment=segment, sort_order=0) +HomePageSponsorRelationship.objects.create(sponsor=acme, homepage=home, level=gold) + +now = timezone.now() +meetup = Meetup.objects.create( + id="m1", + name="November Meetup", + description="

Talks

", + event_url="https://example.com/m1", + time=now + timedelta(days=7), + created=now, + status="upcoming", + visibility="public", +) +MeetupSponsorRelationship.objects.create(sponsor=acme, meetup=meetup, note="pizza") +Redirect.objects.create(old_path="/old-about", redirect_page=about) + +print(f"Seeded {Page.objects.count()} pages and {Image.objects.count()} images") diff --git a/scripts/upgrade-check/snapshot.py b/scripts/upgrade-check/snapshot.py new file mode 100644 index 0000000..b52332d --- /dev/null +++ b/scripts/upgrade-check/snapshot.py @@ -0,0 +1,33 @@ +"""Render the public pages and save their HTML, to diff before/after upgrade. + +Run through `manage.py shell`. The output directory is given by the +UPGRADE_CHECK_SNAPSHOT environment variable. +""" + +import os +import re +from pathlib import Path + +from django.test import Client + +output = Path(os.environ["UPGRADE_CHECK_SNAPSHOT"]) +output.mkdir(parents=True, exist_ok=True) +port = os.environ.get("UPGRADE_CHECK_SERVER_PORT", "18000") +client = Client(HTTP_HOST=f"127.0.0.1:{port}") + +PAGES = [ + ("home", "/"), + ("about", "/about/"), + ("meetups", "/meetups/"), + ("coc", "/meetups/coc/"), + ("redirect", "/old-about"), + ("missing", "/nope/"), +] + +for name, url in PAGES: + response = client.get(url) + html = response.content.decode() + html = re.sub(r'csrfmiddlewaretoken" value="[^"]+"', "csrf", html) + (output / f"{name}.html").write_text(html) + location = response.get("Location", "") + print(f" {name:<9} {response.status_code} {location}") diff --git a/scripts/upgrade-check/upgrade_check_settings.py b/scripts/upgrade-check/upgrade_check_settings.py new file mode 100644 index 0000000..6fe86d4 --- /dev/null +++ b/scripts/upgrade-check/upgrade_check_settings.py @@ -0,0 +1,30 @@ +"""Django settings for the upgrade check. + +Extends the dev settings, but points to the disposable PostgreSQL container +started by run.sh and keeps media/static files inside the run directory. +""" + +import os + +from pythonie.settings.dev import * + +RUN_DIR = os.environ["UPGRADE_CHECK_DIR"] +SERVER_PORT = os.environ.get("UPGRADE_CHECK_SERVER_PORT", "18000") + +# DEBUG off by default to mimic production (WhiteNoise, compressor, manifest). +DEBUG = os.environ.get("UPGRADE_CHECK_DEBUG", "0") == "1" + +DATABASES = { + "default": { + "ENGINE": "django.db.backends.postgresql", + "NAME": "pythonie", + "USER": "postgres", + "PASSWORD": "pythonie", + "HOST": "127.0.0.1", + "PORT": os.environ.get("UPGRADE_CHECK_PG_PORT", "15432"), + } +} +MEDIA_ROOT = os.path.join(RUN_DIR, "media") +STATIC_ROOT = os.path.join(RUN_DIR, "static") +ROOT_URLCONF = "upgrade_check_urls" +WAGTAILADMIN_BASE_URL = f"http://127.0.0.1:{SERVER_PORT}" diff --git a/scripts/upgrade-check/upgrade_check_urls.py b/scripts/upgrade-check/upgrade_check_urls.py new file mode 100644 index 0000000..c638d45 --- /dev/null +++ b/scripts/upgrade-check/upgrade_check_urls.py @@ -0,0 +1,11 @@ +"""Project URLs plus media serving, which runserver skips when DEBUG is off.""" + +from django.conf import settings +from django.urls import re_path +from django.views.static import serve +from pythonie.urls import urlpatterns as project_urlpatterns + +urlpatterns = [ + re_path(r"^media/(?P.*)$", serve, {"document_root": settings.MEDIA_ROOT}), + *project_urlpatterns, +]