diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml new file mode 100644 index 0000000..9ef5f66 --- /dev/null +++ b/.gitea/workflows/ci.yml @@ -0,0 +1,272 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + - cron: "0 6 * * 1" + +jobs: + build-and-scan: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v7 + with: + fetch-depth: 0 + persist-credentials: false + + - name: Scan for secrets + run: | + # docker cp, not a build COPY: a repo's own .dockerignore would otherwise + # silently give an empty, falsely-clean scan. + CID=$(docker create zricethezav/gitleaks:v8.30.1 detect --source=/repo --no-banner -v) + docker cp . "$CID:/repo" + docker start -a "$CID" + STATUS=$? + docker rm "$CID" > /dev/null + exit $STATUS + + - name: Lint Dockerfile with hadolint + run: docker run --rm -i hadolint/hadolint:v2.15.1-alpine hadolint --failure-threshold error - < docker/Dockerfile + + - name: Build Docker image + run: | + docker build -f docker/Dockerfile -t instameex:ci . 2>&1 | tee build.log + if grep -q "Building wheel for" build.log; then + echo "::warning::A dependency was built from source โ€” check Python/Alpine compatibility" + fi + + - name: Smoke test (syntax + binaries) + run: | + docker run --rm --entrypoint python instameex:ci -m compileall -q /app/main.py /app/src + docker run --rm --entrypoint sh instameex:ci -c "test -x /usr/local/bin/ultrahdr_app && exiftool -ver" + + - name: Run unit tests + run: | + docker build -f docker/Dockerfile --target test -t instameex:test . + docker run --rm instameex:test pytest -v --cov=src --cov-report=term-missing --cov-fail-under=75 + + - name: Lint with ruff + run: docker build -f docker/Dockerfile --target lint -t instameex:lint . + + - name: Check deprecation warnings + run: | + docker run --rm --entrypoint python instameex:ci -W error::DeprecationWarning -c "import main" 2>&1 | tee deprecation.log || true + if grep -qi "deprecat" deprecation.log; then + echo "::warning::Deprecation warning detected, check logs" + fi + + - name: Scan with Trivy (critical - blocking) + id: trivy_critical + continue-on-error: true + run: | + docker run --rm \ + -e DOCKER_HOST=tcp://dockerhost:2375 \ + --add-host=dockerhost:host-gateway \ + aquasec/trivy:0.74.0 image --exit-code 1 --severity CRITICAL instameex:ci + + - name: Handle CRITICAL findings + if: steps.trivy_critical.outcome == 'failure' + run: | + if [ "${{ github.event_name }}" != "schedule" ]; then + echo "::error::CRITICAL vulnerabilities found, failing the build." + exit 1 + fi + + echo "Scheduled scan found CRITICAL vulnerabilities โ€” attempting an automatic apk upgrade + rescan." + + # Add an apk upgrade right after the base stage's FROM + sed -i '/^FROM python:.* AS base$/a RUN apk upgrade --no-cache' docker/Dockerfile + docker build -f docker/Dockerfile -t instameex:remediated . + + if docker run --rm \ + -e DOCKER_HOST=tcp://dockerhost:2375 \ + --add-host=dockerhost:host-gateway \ + aquasec/trivy:0.74.0 image --exit-code 1 --severity CRITICAL instameex:remediated; then + echo "apk upgrade clears the CRITICAL finding(s) โ€” opening a PR for review." + + BRANCH="auto/cve-fix-$(date +%Y%m%d)-$(echo "${{ github.sha }}" | cut -c1-7)" + git config user.name "instameex-ci" + git config user.email "ci@git.djeex.fr" + git checkout -b "$BRANCH" + git add docker/Dockerfile + git commit -m "Auto-remediate CRITICAL CVE via apk upgrade" + git config --unset-all http.https://git.djeex.fr/.extraheader || true + git push "https://Djeex:${{ secrets.CI_PUSH_TOKEN }}@git.djeex.fr/Djeex/instameex.git" "HEAD:$BRANCH" + + PR_JSON=$(curl -s -X POST \ + -H "Authorization: token ${{ secrets.CI_PUSH_TOKEN }}" \ + -H "Content-Type: application/json" \ + -d "$(jq -n --arg head "$BRANCH" '{title: "๐Ÿ”’ Auto: remediate CRITICAL CVE via apk upgrade", head: $head, base: "main", body: "Opened automatically by the scheduled CVE scan. An `apk upgrade --no-cache` cleared the CRITICAL Trivy finding(s) in a rebuild โ€” review the diff and merge to publish the fix."}')" \ + "https://git.djeex.fr/api/v1/repos/Djeex/instameex/pulls") + echo "PR API response: $(echo "$PR_JSON" | jq -r '.html_url // .message // "unknown"')" + else + echo "::error::apk upgrade does not clear the CRITICAL finding(s) โ€” no automatic fix available, needs manual review." + exit 1 + fi + + - name: Scan with Trivy (high - informative) + run: | + docker run --rm \ + -e DOCKER_HOST=tcp://dockerhost:2375 \ + --add-host=dockerhost:host-gateway \ + aquasec/trivy:0.74.0 image --exit-code 0 --severity HIGH instameex:ci + + - name: Publish tagged image + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + run: | + BEFORE="${{ github.event.before }}" + if [ -n "$BEFORE" ] && [ "$BEFORE" != "0000000000000000000000000000000000000000" ] && git cat-file -e "$BEFORE" 2>/dev/null; then + BASE_REF="$BEFORE" + else + BASE_REF="HEAD~1" + fi + CHANGED=$(git diff --name-only "$BASE_REF" "${{ github.sha }}") + echo "Changed files:" + echo "$CHANGED" + + if ! echo "$CHANGED" | grep -qE '^(VERSION|main\.py|requirements\.txt)$|^(docker|src)/'; then + echo "No container-relevant file changed, skipping publish." + exit 0 + fi + + if echo "$CHANGED" | grep -qE '^VERSION$'; then + echo "VERSION was manually edited in this push, using it as-is." + else + echo "VERSION untouched but container files changed, auto-bumping the build number (Z)." + OLD_VERSION=$(tr -d '[:space:]' < VERSION) + IFS='.' read -r MAJOR MINOR PATCH <<< "$OLD_VERSION" + NEW_VERSION="${MAJOR}.${MINOR}.$((PATCH + 1))" + echo "$NEW_VERSION" > VERSION + + git config user.name "instameex-ci" + git config user.email "ci@git.djeex.fr" + git add VERSION + git commit -m "Bump build version to $NEW_VERSION [skip ci]" + + git config --unset-all http.https://git.djeex.fr/.extraheader || true + + git push "https://Djeex:${{ secrets.CI_PUSH_TOKEN }}@git.djeex.fr/Djeex/instameex.git" HEAD:main + fi + + VERSION=$(tr -d '[:space:]' < VERSION) + IFS='.' read -r MAJOR MINOR PATCH <<< "$VERSION" + MINOR_TAG="${MAJOR}.${MINOR}" + + IMAGE=git.djeex.fr/djeex/instameex + echo "${{ secrets.REGISTRY_TOKEN }}" | docker login git.djeex.fr -u Djeex --password-stdin + + # Retag the already-built, already-scanned image โ€” never rebuild for publish, + # so what ships is byte-for-byte what Trivy just scanned. + docker tag instameex:ci "$IMAGE:latest" + docker tag instameex:ci "$IMAGE:$MINOR_TAG" + docker tag instameex:ci "$IMAGE:$VERSION" + docker push "$IMAGE:latest" + docker push "$IMAGE:$MINOR_TAG" + docker push "$IMAGE:$VERSION" + + GHCR_IMAGE=ghcr.io/djeex/instameex + echo "${{ secrets.GH_TOKEN }}" | docker login ghcr.io -u Djeex --password-stdin + + docker tag instameex:ci "$GHCR_IMAGE:latest" + docker tag instameex:ci "$GHCR_IMAGE:$MINOR_TAG" + docker tag instameex:ci "$GHCR_IMAGE:$VERSION" + docker push "$GHCR_IMAGE:latest" + docker push "$GHCR_IMAGE:$MINOR_TAG" + docker push "$GHCR_IMAGE:$VERSION" + + TRIGGER_MSG=$(git log -1 --format=%s "${{ github.sha }}") + PR_NUM=$(echo "$TRIGGER_MSG" | grep -oE '#[0-9]+' | head -1 | tr -d '#' || true) + + CATEGORY="๐Ÿ”ง Maintenance" + CHANGE_TITLE="$TRIGGER_MSG" + + if [ -n "$PR_NUM" ]; then + PR_JSON=$(curl -s -H "Authorization: token ${{ secrets.CI_PUSH_TOKEN }}" \ + "https://git.djeex.fr/api/v1/repos/Djeex/instameex/pulls/$PR_NUM") + PR_TITLE=$(echo "$PR_JSON" | jq -r '.title // empty' 2>/dev/null || true) + LABELS=$(echo "$PR_JSON" | jq -r '.labels[]?.name' 2>/dev/null || true) + + if [ -n "$PR_TITLE" ]; then + CHANGE_TITLE="$PR_TITLE" + fi + + if echo "$LABELS" | grep -qx 'bug'; then + CATEGORY="โš ๏ธ Hotfix" + elif echo "$LABELS" | grep -qx 'major'; then + CATEGORY="๐Ÿ’ฅ Breaking change" + elif echo "$LABELS" | grep -qx 'minor'; then + CATEGORY="โœจ Update" + fi + fi + + REPO_URL="https://git.djeex.fr/Djeex/instameex" + COMMIT_LIST=$(git log --no-merges --format="- %s ([%h](${REPO_URL}/commit/%H))" "$BASE_REF".."${{ github.sha }}") + + SHORT_SHA=$(echo "${{ github.sha }}" | cut -c1-7) + SOURCE_LINE="[${SHORT_SHA}](${REPO_URL}/commit/${{ github.sha }})" + if [ -n "$PR_NUM" ]; then + SOURCE_LINE="[#${PR_NUM}](${REPO_URL}/pulls/${PR_NUM}) ยท ${SOURCE_LINE}" + fi + + NOTE_BANNER=$(printf '> [!NOTE]\n>โš ๏ธ _This is an heavily vibe-coded proof of concept โ€” do not expose it to the internet โ€” use it at your own risk._') + + BODY=$(cat </dev/null || true + fi diff --git a/docker/Dockerfile b/docker/Dockerfile index d325917..f634a6e 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -15,7 +15,7 @@ RUN cmake -G "Unix Makefiles" -DUHDR_WRITE_XMP=ON \ && cmake --build libultrahdr/build -j"$(nproc)" # ---- Stage 2: runtime ------------------------------------------------------- -FROM python:3.11-alpine +FROM python:3.11-alpine AS base RUN apk add --no-cache exiftool libjpeg-turbo libstdc++ @@ -32,6 +32,22 @@ COPY LICENSE VERSION ./ COPY docker/entrypoint.sh /app/entrypoint.sh RUN chmod +x /app/entrypoint.sh +FROM base AS test + +RUN pip install --no-cache-dir pytest==9.1.1 pytest-cov==7.1.0 +COPY pytest.ini ./ +COPY tests/ tests/ +CMD ["pytest", "-v"] + +FROM base AS lint + +RUN pip install --no-cache-dir ruff==0.16.4 +COPY ruff.toml ./ +COPY tests/ tests/ +RUN ruff check . + +FROM base + RUN adduser -D runner && mkdir -p /app/jobs && chown -R runner:runner /app USER runner diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..5ee6477 --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +testpaths = tests diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..bde126f --- /dev/null +++ b/renovate.json @@ -0,0 +1,40 @@ +{ + "$schema": "https://docs.renovatebot.com/renovate-schema.json", + "extends": ["config:recommended"], + "timezone": "Europe/Paris", + "labels": ["bot"], + "vulnerabilityAlerts": { + "addLabels": ["bug"] + }, + "customManagers": [ + { + "customType": "regex", + "description": "Docker images pinned in CI 'docker run' / 'docker create' commands", + "managerFilePatterns": ["/^\\.gitea/workflows/.+\\.ya?ml$/"], + "matchStrings": [ + "(?(?:zricethezav/gitleaks|hadolint/hadolint|aquasec/trivy)):(?v?\\d+\\.\\d+\\.\\d+(?:-[a-z]+)?)" + ], + "datasourceTemplate": "docker" + } + ], + "packageRules": [ + { + "matchManagers": ["pip_requirements"], + "matchUpdateTypes": ["patch", "minor"], + "automerge": true + }, + { + "matchManagers": ["dockerfile"], + "matchUpdateTypes": ["patch"], + "automerge": true + }, + { + "matchUpdateTypes": ["major"], + "addLabels": ["major"] + }, + { + "matchUpdateTypes": ["minor"], + "addLabels": ["minor"] + } + ] +} diff --git a/requirements.txt b/requirements.txt index 5052222..2fc0060 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,5 @@ Flask==3.1.3 gunicorn==23.0.0 -Pillow==11.1.0 +Pillow==13.0.0 numpy==2.4.6 tifffile==2026.3.3 diff --git a/ruff.toml b/ruff.toml new file mode 100644 index 0000000..2a6635e --- /dev/null +++ b/ruff.toml @@ -0,0 +1,12 @@ +line-length = 100 + +[lint] +select = ["E", "F", "I", "UP", "B"] +# E501: long lines are left alone. B905: zip() in routes.py is already +# length-checked just before; not touching app logic here. +ignore = ["E501", "B905"] + +[lint.isort] +# Pinned explicitly: auto-detection of first-party modules differs between the +# host and the Docker lint stage, which would silently diverge import sorting. +known-first-party = ["app", "main"] diff --git a/src/script/app/assembler.py b/src/script/app/assembler.py index d316cd1..2b58c1f 100644 --- a/src/script/app/assembler.py +++ b/src/script/app/assembler.py @@ -226,6 +226,8 @@ def _tiff_max_boost(hdr_linear: np.ndarray, sdr_420: Path) -> float: sdr_linear = _jpeg_to_linear(sdr_420) real_signal = sdr_linear > 0.005 ratio = hdr_linear[real_signal] / sdr_linear[real_signal] + if ratio.size == 0: + return 1.0 # all-black SDR: nothing to boost n = min(32, ratio.size) return float(np.partition(ratio, -n)[-n]) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..3db600d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,28 @@ +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(ROOT / "src" / "script")) +sys.path.insert(0, str(ROOT)) + + +@pytest.fixture +def jobs_dir(tmp_path, monkeypatch): + from app import jobs + + monkeypatch.setattr(jobs, "JOBS_DIR", tmp_path / "jobs") + jobs.JOBS.clear() + yield tmp_path / "jobs" + jobs.JOBS.clear() + + +@pytest.fixture +def client(jobs_dir, monkeypatch): + from app import create_app, jobs + + monkeypatch.setattr(jobs, "start_reaper", lambda: None) + app = create_app() + app.config["TESTING"] = True + return app.test_client() diff --git a/tests/test_assembler.py b/tests/test_assembler.py new file mode 100644 index 0000000..825baac --- /dev/null +++ b/tests/test_assembler.py @@ -0,0 +1,207 @@ +import subprocess +from types import SimpleNamespace + +import numpy as np +import pytest +import tifffile +from PIL import Image + +from app import assembler + + +def cp(returncode=0, stdout="", stderr=""): + return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr) + + +@pytest.fixture +def tools(monkeypatch): + monkeypatch.setattr(assembler.shutil, "which", lambda t: f"/usr/bin/{t}") + + +def test_check_dependencies(monkeypatch): + monkeypatch.setattr(assembler.shutil, "which", lambda t: None) + assert assembler.check_dependencies() == ["ultrahdr_app", "exiftool"] + monkeypatch.setattr(assembler.shutil, "which", lambda t: "/x" if t == "exiftool" else None) + assert assembler.check_dependencies() == ["ultrahdr_app"] + monkeypatch.setattr(assembler.shutil, "which", lambda t: "/x") + assert assembler.check_dependencies() == [] + + +@pytest.mark.parametrize("desc,code", [ + ("Display P3", "1"), ("Rec2020 PQ", "2"), ("ITU-R BT.2100", "2"), + ("sRGB IEC61966-2.1", "0"), ("", "0"), +]) +def test_detect_gamut(monkeypatch, tmp_path, desc, code): + monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(stdout=desc + "\n")) + assert assembler._detect_gamut(tmp_path / "x.jpg") == code + + +def test_decode_hdr_intent_error(monkeypatch, tools, tmp_path): + monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(1, stderr="bad file")) + with pytest.raises(assembler.AssemblyError, match="bad file"): + assembler._decode_hdr_intent(tmp_path / "h.jpg", tmp_path / "o.raw") + + +def test_encode_without_and_with_max_boost(monkeypatch, tools, tmp_path): + calls = [] + monkeypatch.setattr(assembler.subprocess, "run", lambda args, **k: calls.append(args) or cp()) + assembler._encode(tmp_path / "r", "0", tmp_path / "s", "0", 10, 20, tmp_path / "o") + assert "-K" not in calls[0] and calls[0][calls[0].index("-t") + 1] == "1" + + assembler._encode(tmp_path / "r", "1", tmp_path / "s", "0", 10, 20, tmp_path / "o", max_boost=4.0) + args = calls[1] + assert args[args.index("-K") + 1] == "4.0" + assert args[args.index("-k") + 1] == "1" # floor never below 1 + assert args[args.index("-L") + 1] == str(4.0 * 203) + + +@pytest.mark.parametrize("boost,nits", [(0.1, 203), (100.0, 10000)]) +def test_encode_target_nits_clamped(monkeypatch, tools, tmp_path, boost, nits): + calls = [] + monkeypatch.setattr(assembler.subprocess, "run", lambda args, **k: calls.append(args) or cp()) + assembler._encode(tmp_path / "r", "0", tmp_path / "s", "0", 1, 1, tmp_path / "o", max_boost=boost) + assert calls[0][calls[0].index("-L") + 1] == str(nits) + + +def test_encode_failure(monkeypatch, tools, tmp_path): + monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(1, stderr="nope")) + with pytest.raises(assembler.AssemblyError, match="nope"): + assembler._encode(tmp_path / "r", "0", tmp_path / "s", "0", 1, 1, tmp_path / "o") + + +def test_to_4_2_0_keeps_icc_profile(tmp_path): + src, dest = tmp_path / "s.jpg", tmp_path / "d.jpg" + Image.new("RGB", (16, 16), "red").save(src, "JPEG", icc_profile=b"ICCDATA") + assembler._to_4_2_0(src, dest) + with Image.open(dest) as img: + assert img.info.get("icc_profile") == b"ICCDATA" + assert img.size == (16, 16) + + +def test_to_4_2_0_without_icc(tmp_path): + src, dest = tmp_path / "s.jpg", tmp_path / "d.jpg" + Image.new("RGB", (8, 8)).save(src, "JPEG") + assembler._to_4_2_0(src, dest) + assert dest.exists() + + +def test_tiff_to_hdr_raw(tmp_path): + tiff = tmp_path / "h.tif" + data = np.full((2, 3, 3), 2.0, dtype=np.float32) + data[0, 0] = -1.0 # negative values must be clipped + tifffile.imwrite(tiff, data) + dest = tmp_path / "out.raw" + w, h, linear = assembler._tiff_to_hdr_raw(tiff, dest) + assert (w, h) == (3, 2) + assert linear[0, 0, 0] == 0.0 + assert linear[1, 1, 0] == pytest.approx(2.0 ** assembler._HLG_SYSTEM_GAMMA) + assert dest.stat().st_size == 2 * 3 * 4 * 2 # RGBA half floats + + +def test_jpeg_to_linear_range(tmp_path): + p = tmp_path / "w.jpg" + Image.new("RGB", (4, 4), "white").save(p, "JPEG") + lin = assembler._jpeg_to_linear(p) + assert lin.shape == (4, 4, 3) and lin.max() == pytest.approx(1.0, abs=0.02) + + +def test_tiff_max_boost_ignores_near_black_and_picks_32nd(tmp_path): + sdr = tmp_path / "s.jpg" + Image.new("RGB", (16, 16), (128, 128, 128)).save(sdr, "JPEG", quality=100) + sdr_lin = assembler._jpeg_to_linear(sdr) + hdr = sdr_lin * 3.0 + assert assembler._tiff_max_boost(hdr, sdr) == pytest.approx(3.0, rel=0.01) + hdr[0, 0] = 1000.0 # a lone spike must not set the boost + assert assembler._tiff_max_boost(hdr, sdr) == pytest.approx(3.0, rel=0.01) + + +def test_tiff_max_boost_all_black_image_has_no_signal(tmp_path): + sdr = tmp_path / "s.jpg" + Image.new("RGB", (8, 8), "black").save(sdr, "JPEG") + assert assembler._tiff_max_boost(np.ones((8, 8, 3), dtype=np.float32), sdr) == 1.0 + + +def test_tiff_max_boost_fewer_than_32_pixels(tmp_path): + sdr = tmp_path / "s.jpg" + Image.new("RGB", (2, 2), (128, 128, 128)).save(sdr, "JPEG", quality=100) + hdr = assembler._jpeg_to_linear(sdr) * 2.0 + assert assembler._tiff_max_boost(hdr, sdr) == pytest.approx(2.0, rel=0.01) + + +def test_probe_hdr_capacity(monkeypatch, tools, tmp_path): + out = "foo\n --hdrCapacityMax 3.5\n" + monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(stdout=out)) + assert assembler._probe_hdr_capacity(tmp_path / "x") == 3.5 + monkeypatch.setattr(assembler.subprocess, "run", lambda *a, **k: cp(stdout="nothing")) + with pytest.raises(assembler.AssemblyError): + assembler._probe_hdr_capacity(tmp_path / "x") + + +def fake_exiftool(min_value=None, extract_ok=True, report_stdout=None): + import json + + def run(args, **k): + if "-MPImage2" in args: + return cp(0 if extract_ok else 1, stdout=b"data" if extract_ok else b"") + stdout = report_stdout + if stdout is None: + meta = {"XMP-hdrgm:Version": "1.0", "Other:Tag": "x"} + if min_value is not None: + meta["XMP-hdrgm:GainMapMin"] = min_value + stdout = json.dumps([meta]) + return cp(stdout=stdout) + + return run + + +@pytest.mark.parametrize("value,negative", [(-0.5, True), (0, False), (1, False), (None, False)]) +def test_validate_output_gain_map_min(monkeypatch, tmp_path, value, negative): + monkeypatch.setattr(assembler.subprocess, "run", fake_exiftool(min_value=value)) + log = [] + assert assembler._validate_output(tmp_path / "o.jpg", log) is negative + assert any("Validation report" in line for line in log) + assert any("WARNING" in line for line in log) is negative + assert not any("Other:Tag" in line for line in log) # non-hdrgm tags filtered + + +@pytest.mark.parametrize("kwargs", [ + {"extract_ok": False}, {"report_stdout": "not json"}, {"report_stdout": "[]"}, +]) +def test_validate_output_unreadable_metadata(monkeypatch, tmp_path, kwargs): + monkeypatch.setattr(assembler.subprocess, "run", fake_exiftool(**kwargs)) + log = [] + assert assembler._validate_output(tmp_path / "o.jpg", log) is False + assert log == [] + + +def test_run_missing_tools(monkeypatch, tmp_path): + monkeypatch.setattr(assembler.shutil, "which", lambda t: None) + ok, log, warn = assembler.run(tmp_path / "s.jpg", tmp_path / "h.jpg", tmp_path / "o.jpg") + assert (ok, warn) == (False, False) and "ultrahdr_app" in log + + +@pytest.mark.parametrize("suffix,target", [ + (".jpg", "_assemble_from_jpeg"), (".JPEG", "_assemble_from_jpeg"), + (".tif", "_assemble_from_tiff_hdr"), (".TIFF", "_assemble_from_tiff_hdr"), +]) +def test_run_dispatch_by_hdr_extension(monkeypatch, tools, tmp_path, suffix, target): + called = [] + for name in ("_assemble_from_jpeg", "_assemble_from_tiff_hdr"): + monkeypatch.setattr(assembler, name, lambda *a, n=name: called.append(n)) + monkeypatch.setattr(assembler, "_validate_output", lambda *a: True) + ok, log, warn = assembler.run(tmp_path / "s.jpg", tmp_path / f"h{suffix}", tmp_path / "o.jpg") + assert called == [target] and ok is True and warn is True and "Done!" in log + + +@pytest.mark.parametrize("exc", [ + assembler.AssemblyError("boom"), + subprocess.CalledProcessError(1, "x"), + subprocess.TimeoutExpired("x", 1), +]) +def test_run_pipeline_errors_are_reported(monkeypatch, tools, tmp_path, exc): + def fail(*a): + raise exc + + monkeypatch.setattr(assembler, "_assemble_from_jpeg", fail) + ok, log, warn = assembler.run(tmp_path / "s.jpg", tmp_path / "h.jpg", tmp_path / "o.jpg") + assert (ok, warn) == (False, False) and log.startswith("Error:") diff --git a/tests/test_jobs.py b/tests/test_jobs.py new file mode 100644 index 0000000..c879101 --- /dev/null +++ b/tests/test_jobs.py @@ -0,0 +1,79 @@ +import time + +import pytest + +from app import jobs + + +def test_new_job_dir_creates_directory(jobs_dir): + d = jobs.new_job_dir("abc") + assert d == jobs_dir / "abc" and d.is_dir() + assert jobs.new_job_dir("abc") == d # idempotent + + +def test_register_get_unknown(jobs_dir): + assert jobs.get("nope") is None + jobs.register("j1", items=[1]) + job = jobs.get("j1") + assert job["items"] == [1] and "last_seen" in job + + +def test_touch_updates_and_ignores_unknown(jobs_dir): + jobs.register("j1") + jobs.JOBS["j1"]["last_seen"] = 0 + jobs.touch("j1") + assert jobs.JOBS["j1"]["last_seen"] > 0 + jobs.touch("unknown") # must not raise + assert "unknown" not in jobs.JOBS + + +def test_cleanup_removes_registry_and_dir(jobs_dir): + d = jobs.new_job_dir("j1") + (d / "f.txt").write_text("x") + jobs.register("j1") + jobs.cleanup("j1") + assert jobs.get("j1") is None and not d.exists() + + +def test_cleanup_unknown_job_is_noop(jobs_dir): + jobs.reset_jobs_dir() + jobs.cleanup("ghost") + + +def test_reset_jobs_dir_wipes_leftovers(jobs_dir): + jobs.new_job_dir("old") + jobs.reset_jobs_dir() + assert jobs_dir.is_dir() and list(jobs_dir.iterdir()) == [] + + +def test_reap_removes_only_stale_jobs(jobs_dir, monkeypatch): + jobs.new_job_dir("stale") + jobs.new_job_dir("fresh") + jobs.register("stale") + jobs.register("fresh") + jobs.JOBS["stale"]["last_seen"] = time.time() - 1000 + + def stop(_): + if stop.called: + raise StopIteration + stop.called = True + + stop.called = False + monkeypatch.setattr(jobs.time, "sleep", stop) + with pytest.raises(StopIteration): + jobs._reap_stale_jobs() + assert "stale" not in jobs.JOBS and not (jobs_dir / "stale").exists() + assert "fresh" in jobs.JOBS and (jobs_dir / "fresh").exists() + + +def test_reap_with_no_jobs(jobs_dir, monkeypatch): + calls = [] + + def stop(_): + if calls: + raise StopIteration + calls.append(1) + + monkeypatch.setattr(jobs.time, "sleep", stop) + with pytest.raises(StopIteration): + jobs._reap_stale_jobs() diff --git a/tests/test_routes.py b/tests/test_routes.py new file mode 100644 index 0000000..1ca956c --- /dev/null +++ b/tests/test_routes.py @@ -0,0 +1,147 @@ +import io +import zipfile + +import pytest +from PIL import Image + +from app import assembler, jobs + + +def jpeg_bytes(size=(1080, 1080)): + buf = io.BytesIO() + Image.new("RGB", size, "gray").save(buf, "JPEG") + return buf.getvalue() + + +def pair(name="a", sdr_name=None, hdr_name=None, size=(1080, 1080)): + return ( + (io.BytesIO(jpeg_bytes(size)), sdr_name or f"{name}_sdr.jpg"), + (io.BytesIO(jpeg_bytes(size)), hdr_name or f"{name}_hdr.jpg"), + ) + + +def post(client, pairs): + data = {"sdr[]": [p[0] for p in pairs], "hdr[]": [p[1] for p in pairs]} + return client.post("/convert", data=data, content_type="multipart/form-data") + + +@pytest.fixture +def fake_run(monkeypatch): + def run(sdr_path, hdr_path, out_path): + out_path.write_bytes(b"OUT:" + out_path.name.encode()) + return True, "ok", False + + monkeypatch.setattr(assembler, "run", run) + + +def job_id_from(resp): + return resp.headers["Location"].rstrip("/").split("/")[-1] + + +def test_index(client): + assert client.get("/").status_code == 200 + + +def test_convert_without_files(client): + resp = client.post("/convert", data={}, content_type="multipart/form-data") + assert resp.status_code == 400 and b"at least one" in resp.data + + +def test_convert_unbalanced_pairs(client): + data = {"sdr[]": [(io.BytesIO(jpeg_bytes()), "a.jpg")], "hdr[]": []} + resp = client.post("/convert", data=data, content_type="multipart/form-data") + assert resp.status_code == 400 + + +def test_convert_success_single(client, fake_run): + resp = post(client, [pair()]) + assert resp.status_code == 302 + jid = job_id_from(resp) + page = client.get(f"/result/{jid}") + assert page.status_code == 200 and b"JPEG assembled" in page.data + dl = client.get(f"/download/{jid}") + assert dl.status_code == 200 + assert dl.headers["Content-Disposition"].endswith("instagram_hdr_output.jpg") + assert dl.data.startswith(b"OUT:") + + +def test_convert_multiple_downloads_zip(client, fake_run): + jid = job_id_from(post(client, [pair("a"), pair("b"), pair("c")])) + assert b"All 3 assembled" in client.get(f"/result/{jid}").data + dl = client.get(f"/download/{jid}") + assert dl.mimetype == "application/zip" + with zipfile.ZipFile(io.BytesIO(dl.data)) as zf: + assert zf.namelist() == [f"instagram_hdr_output_{i}.jpg" for i in (1, 2, 3)] + + +def test_partial_failure_download_only_successes(client, fake_run): + bad = pair("b", sdr_name="b.png") + jid = job_id_from(post(client, [pair("a"), bad])) + assert b"1/2 assembled" in client.get(f"/result/{jid}").data + dl = client.get(f"/download/{jid}") + assert dl.mimetype != "application/zip" # a single success is sent as a plain JPEG + + +def test_all_failed(client, fake_run): + jid = job_id_from(post(client, [pair(sdr_name="x.png")])) + assert b"Conversion failed" in client.get(f"/result/{jid}").data + assert client.get(f"/download/{jid}").status_code == 404 + + +def test_bad_hdr_extension_reported(client, fake_run): + jid = job_id_from(post(client, [pair(hdr_name="h.png")])) + assert jobs.get(jid)["items"][0]["success"] is False + assert "HDR file" in jobs.get(jid)["items"][0]["log"] + + +@pytest.mark.parametrize("sdr_name,hdr_name", [("", "h.jpg"), ("s.jpg", ""), ("", "")]) +def test_empty_filename_reported(tmp_path, sdr_name, hdr_name): + from types import SimpleNamespace + + from app.routes import _process_pair + + item = _process_pair(tmp_path, 1, SimpleNamespace(filename=sdr_name), + SimpleNamespace(filename=hdr_name)) + assert item["success"] is False and "Missing" in item["log"] + + +def test_resolution_rejected_and_inputs_removed(client, fake_run, jobs_dir): + jid = job_id_from(post(client, [pair(size=(100, 100))])) + item = jobs.get(jid)["items"][0] + assert not item["success"] and "Instagram requires" in item["log"] + assert list((jobs_dir / jid).iterdir()) == [] + + +def test_ignore_ig_resolution_flag(client, fake_run): + pairs = [pair(size=(100, 100))] + data = {"sdr[]": [pairs[0][0]], "hdr[]": [pairs[0][1]], "ignore_ig_resolution": "on"} + resp = client.post("/convert", data=data, content_type="multipart/form-data") + assert jobs.get(job_id_from(resp))["items"][0]["success"] is True + + +def test_assembler_failure_has_no_output(client, monkeypatch): + monkeypatch.setattr(assembler, "run", lambda *a: (False, "boom", False)) + jid = job_id_from(post(client, [pair()])) + item = jobs.get(jid)["items"][0] + assert item["success"] is False and item["output"] is None + assert client.get(f"/download/{jid}").status_code == 404 + + +def test_unknown_job_404(client): + assert client.get("/result/nope").status_code == 404 + assert client.get("/download/nope").status_code == 404 + + +def test_heartbeat(client): + assert client.post("/heartbeat/unknown").status_code == 204 + jobs.register("j1") + jobs.JOBS["j1"]["last_seen"] = 0 + assert client.post("/heartbeat/j1").status_code == 204 + assert jobs.JOBS["j1"]["last_seen"] > 0 + + +def test_too_large(client, monkeypatch): + client.application.config["MAX_CONTENT_LENGTH"] = 10 + resp = client.post("/convert", data={"sdr[]": (io.BytesIO(b"x" * 100), "a.jpg")}, + content_type="multipart/form-data") + assert resp.status_code == 413 and b"too large" in resp.data diff --git a/tests/test_validation.py b/tests/test_validation.py new file mode 100644 index 0000000..30eb027 --- /dev/null +++ b/tests/test_validation.py @@ -0,0 +1,106 @@ +import numpy as np +import pytest +import tifffile +from PIL import Image + +from app import validation + + +def make_jpeg(path, size): + Image.new("RGB", size, "gray").save(path, "JPEG") + return path + + +def make_tiff(path, size): + tifffile.imwrite(path, np.zeros((size[1], size[0], 3), dtype=np.float32)) + return path + + +@pytest.mark.parametrize("name,expected", [ + ("a.JPG", ".jpg"), ("a.b.tiff", ".tiff"), ("noext", ""), ("", ""), +]) +def test_ext(name, expected): + assert validation.ext(name) == expected + + +@pytest.mark.parametrize("name,expected", [ + ("x.tif", True), ("x.TIFF", True), ("x.jpg", False), ("tif", False), +]) +def test_is_tiff(name, expected): + assert validation.is_tiff(name) is expected + + +@pytest.mark.parametrize("name,ok", [ + ("a.jpg", True), ("a.JPEG", True), ("a.tif", False), ("a.png", False), ("", False), +]) +def test_sdr_ext_error(name, ok): + assert (validation.sdr_ext_error(name) is None) is ok + + +@pytest.mark.parametrize("name,ok", [ + ("a.jpg", True), ("a.jpeg", True), ("a.tif", True), ("a.TIFF", True), + ("a.png", False), ("a.avif", False), ("", False), +]) +def test_hdr_ext_error(name, ok): + assert (validation.hdr_ext_error(name) is None) is ok + + +def test_probe_dimensions_jpeg_and_tiff(tmp_path): + assert validation.probe_dimensions(make_jpeg(tmp_path / "a.jpg", (30, 20))) == (30, 20) + assert validation.probe_dimensions(make_tiff(tmp_path / "a.tif", (30, 20))) == (30, 20) + + +def test_probe_dimensions_corrupt(tmp_path): + bad_jpg = tmp_path / "bad.jpg" + bad_jpg.write_bytes(b"not an image") + bad_tif = tmp_path / "bad.tif" + bad_tif.write_bytes(b"not a tiff") + with pytest.raises(ValueError, match="image dimensions"): + validation.probe_dimensions(bad_jpg) + with pytest.raises(ValueError, match="TIFF dimensions"): + validation.probe_dimensions(bad_tif) + + +def test_probe_dimensions_missing_file(tmp_path): + with pytest.raises(ValueError): + validation.probe_dimensions(tmp_path / "missing.jpg") + + +@pytest.mark.parametrize("size", [(1080, 1080), (1080, 1350), (1080, 566)]) +def test_resolution_ok_for_each_instagram_format(tmp_path, size): + sdr = make_jpeg(tmp_path / "s.jpg", size) + hdr = make_jpeg(tmp_path / "h.jpg", size) + assert validation.instagram_resolution_error(sdr, hdr) is None + + +def test_resolution_ok_with_tiff_hdr(tmp_path): + sdr = make_jpeg(tmp_path / "s.jpg", (1080, 1080)) + hdr = make_tiff(tmp_path / "h.tif", (1080, 1080)) + assert validation.instagram_resolution_error(sdr, hdr) is None + + +def test_resolution_mismatch_always_rejected(tmp_path): + sdr = make_jpeg(tmp_path / "s.jpg", (1080, 1080)) + hdr = make_jpeg(tmp_path / "h.jpg", (1080, 1350)) + for ignore in (False, True): + assert "identical" in validation.instagram_resolution_error(sdr, hdr, ignore) + + +def test_resolution_not_instagram(tmp_path): + sdr = make_jpeg(tmp_path / "s.jpg", (100, 100)) + hdr = make_jpeg(tmp_path / "h.jpg", (100, 100)) + assert "Instagram requires" in validation.instagram_resolution_error(sdr, hdr) + assert validation.instagram_resolution_error(sdr, hdr, ignore_ig_resolution=True) is None + + +def test_resolution_swapped_dimensions_rejected(tmp_path): + sdr = make_jpeg(tmp_path / "s.jpg", (1350, 1080)) + hdr = make_jpeg(tmp_path / "h.jpg", (1350, 1080)) + assert validation.instagram_resolution_error(sdr, hdr) is not None + + +def test_resolution_unreadable_file(tmp_path): + sdr = make_jpeg(tmp_path / "s.jpg", (1080, 1080)) + bad = tmp_path / "h.jpg" + bad.write_bytes(b"") + assert "Could not validate" in validation.instagram_resolution_error(sdr, bad)