Add CI/CD pipeline, Renovate config and unit tests
CI / build-and-scan (pull_request) Failing after 2m9s

This commit is contained in:
Djeex committed 2026-11-21 16:15:14 +00:00
1 parent 03d6870c64
commit 4e7b51c334
11 files changed
+912 -1

No files matched your search

+28
View File
@@ -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()
+207
View File
@@ -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:")
+79
View File
@@ -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()
+147
View File
@@ -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
+106
View File
@@ -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)