Files
mtusi2026lab7/student-unit/test_job_envelope.py
T

120 lines
3.2 KiB
Python

import copy
from datetime import UTC, datetime
from uuid import uuid4
import pytest
from jsonschema import Draft202012Validator, FormatChecker
from src.pipeline import validate_job
def example():
return dict(
schema_version=1,
job_id=str(uuid4()),
type="attachment.process.v1",
attachment_id=str(uuid4()),
pipeline_version=1,
attempt=1,
created_at=datetime.now(UTC).isoformat(),
)
def test_schema_and_runtime_agree_on_valid_job():
import json
from pathlib import Path
schema = json.loads(Path("contracts/jobs.schema.json").read_text())
for version in [1, 2]:
data = example()
data["pipeline_version"] = version
data.update(
traceparent="00-" + "a" * 32 + "-" + "b" * 16 + "-01",
tracestate="vendor=opaque",
)
Draft202012Validator(schema, format_checker=FormatChecker()).validate(
data
)
assert validate_job(data) == data
@pytest.mark.parametrize(
"field,value",
[
("schema_version", True),
("schema_version", 2),
("type", "other"),
("job_id", 123),
("job_id", "broken"),
("attachment_id", None),
("pipeline_version", 0),
("pipeline_version", True),
("attempt", 0),
("attempt", 1.0),
("created_at", "2026-01-01"),
("created_at", "2026-01-01T12:00:00"),
("created_at", None),
("traceparent", "not-w3c"),
("tracestate", "x" * 513),
("url", "http://invalid.example"),
("bytes", "secret-contents"),
("filename", "../../bad"),
],
)
def test_invalid_notification_is_rejected(field, value):
data = copy.deepcopy(example())
data[field] = value
with pytest.raises((ValueError, TypeError)):
validate_job(data)
def test_worker_rejects_oversized_pixels_before_decode():
import hashlib
import io
from PIL import Image
from src.pipeline import PermanentFailure
from src.worker import make_variants
stream = io.BytesIO()
Image.new("1", (8000, 5001)).save(stream, format="PNG")
raw = stream.getvalue()
row = dict(
size_bytes=len(raw),
sha256=hashlib.sha256(raw).hexdigest(),
content_type="image/png",
pipeline_version=1,
)
with (
pytest.warns(Image.DecompressionBombWarning),
pytest.raises(PermanentFailure, match="pixel_limit"),
):
list(make_variants(raw, row))
def test_worker_rejects_changed_source_checksum():
from src.pipeline import PermanentFailure
from src.worker import make_variants
with pytest.raises(PermanentFailure, match="source_checksum_mismatch"):
list(make_variants(b"changed", dict(size_bytes=7, sha256="0" * 64)))
def test_worker_rejects_invalid_image_as_permanent():
import hashlib
from src.pipeline import PermanentFailure
from src.worker import make_variants
raw = b"not an image"
with pytest.raises(PermanentFailure, match="invalid_image"):
list(
make_variants(
raw,
dict(
size_bytes=len(raw), sha256=hashlib.sha256(raw).hexdigest()
),
)
)