Перенос решения ЛР 6 без изменений (src, migrations, student-tests, bench, infra, scripts, compose, Dockerfile, docs)

This commit is contained in:
Alexey Bodanyuk
2026-11-27 16:01:21 +03:00
parent 20afc2c790
commit 6435b6a1c5
111 changed files with 19604 additions and 0 deletions
+148
View File
@@ -0,0 +1,148 @@
"""Unit tests of the image checks (src/messenger/images.py) and the filename rules. No services.
The JPEG decoder (djpeg) exists in the API image; locally these tests are skipped without it
(the same cases run against the stand in test_attachments.py)."""
from __future__ import annotations
import asyncio
import shutil
import sys
import time
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "student-tests"))
import imagegen # noqa: E402
from messenger import images, validation # noqa: E402
from messenger.errors import InvalidRequest # noqa: E402
LIMIT = 40_000_000
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
has_djpeg = pytest.mark.skipif(shutil.which("djpeg") is None, reason="djpeg (libjpeg-turbo-progs) not installed")
def status(data: bytes) -> int:
"""201 if accepted, else the HTTP status of the ImageError (413/415)."""
try:
info = images.sniff(data, LIMIT)
if info is None:
return 415 # header never completed
asyncio.run(images.verify(data, info))
return 201
except images.ImageError as exc:
return exc.status
def test_public_fixture_is_accepted():
assert images.sniff(SAMPLE, LIMIT) == images.ImageInfo("image/png", 320, 200)
assert status(SAMPLE) == 201
@pytest.mark.parametrize("data", [
imagegen.png(37, 23, "RGBA"), imagegen.png(33, 17, "P"), imagegen.png(33, 17, "1"),
imagegen.png(33, 17, "L"), imagegen.png(81, 57, "RGB", noise=True), imagegen.png(1, 1),
], ids=["rgba", "palette", "1bit", "gray", "noise", "1x1"])
def test_valid_png_kinds(data):
assert status(data) == 201
def test_interlaced_png_is_accepted():
# Pillow cannot write Adam7; build one by hand: 9 x 9 grey, every pass with filter 0.
from messenger.images import _png_segments
raw = b"".join(b"\x00" + bytes(stride - 1) for size, stride in _png_segments(9, 9, 8, 0, 1)
for _ in range(size // stride))
data = imagegen.PNG_SIGNATURE + imagegen.ihdr(9, 9, 8, 0, 1) + imagegen.chunk(b"IDAT", __import__("zlib").compress(raw)) \
+ imagegen.chunk(b"IEND", b"")
assert status(data) == 201
BROKEN_PNG = {
"first 33 bytes of the fixture": SAMPLE[:33],
"truncated (no IEND)": SAMPLE[:-12],
"truncated in IDAT": SAMPLE[:len(SAMPLE) // 2],
"flipped byte -> CRC error": SAMPLE[:500] + bytes([SAMPLE[500] ^ 0xFF]) + SAMPLE[501:],
"garbage IDAT with valid CRC": imagegen.png_corrupt_idat(),
"fewer rows than IHDR": imagegen.png_short_pixels(),
"bytes after IEND (polyglot)": SAMPLE + b"PK\x03\x04zip",
"text": b"just text, definitely not an image",
"gif": b"GIF89a" + bytes(64),
"two bytes of a signature": b"\x89P",
}
@pytest.mark.parametrize("name", list(BROKEN_PNG))
def test_broken_png_is_415(name):
assert status(BROKEN_PNG[name]) == 415, name
def test_pixel_limit_is_checked_from_the_header():
with pytest.raises(images.ImageError) as exc:
images.sniff(imagegen.png_bomb_header()[:33], LIMIT) # 33 bytes are enough
assert exc.value.status == 413
exact = imagegen.PNG_SIGNATURE + imagegen.ihdr(8000, 5000) # exactly 40 000 000: allowed
assert images.sniff(exact, LIMIT).width == 8000
with pytest.raises(images.ImageError) as exc:
images.sniff(imagegen.PNG_SIGNATURE + imagegen.ihdr(8001, 5000), LIMIT)
assert exc.value.status == 413
with pytest.raises(images.ImageError) as exc:
images.sniff(imagegen.jpeg_bomb_header(), LIMIT)
assert exc.value.status == 413
def test_png_verification_is_streaming_and_fast():
"""40 Mpx RGB = 120 MB of raw pixels: inflated in 1 MiB steps and discarded."""
big = imagegen.png(8000, 5000, compress_level=9)
started = time.perf_counter()
assert status(big) == 201
assert time.perf_counter() - started < 5
def test_jpeg_header_is_parsed_incrementally():
data = imagegen.jpeg(320, 200)
assert images.sniff(data[:4], LIMIT) is None # SOF not arrived yet
assert images.sniff(data, LIMIT) == images.ImageInfo("image/jpeg", 320, 200)
@has_djpeg
@pytest.mark.parametrize("data", [imagegen.jpeg(), imagegen.jpeg(640, 480, progressive=True)], ids=["base", "prog"])
def test_valid_jpeg(data):
assert status(data) == 201
@has_djpeg
@pytest.mark.parametrize("name,data", [
("no scan data after SOS", imagegen.jpeg_without_scan_data()),
("truncated", imagegen.jpeg(320, 240, noise=True)[:3000]),
], ids=lambda v: v if isinstance(v, str) else "")
def test_broken_jpeg_is_415(name, data):
assert status(data) == 415, name
# ------------------------------------------------------------------ filename
@pytest.mark.parametrize("name", ["photo.png", "фото отпуска.jpg", "a" * 255, "emoji 👨‍👩‍👧.png", " x ", "..."[:2] + "x"])
def test_good_filenames(name):
assert validation.filename_param([("filename", name)]) == name
@pytest.mark.parametrize("name", ["", " ", " ", ".", "..", "a/b.png", "a\\b.png", "a\x00b", "c1\x85.png",
"tab\t.png", "del\x7f.png", "x
y", "photo‮gnp.exe", "a" * 256])
def test_bad_filenames(name):
with pytest.raises(InvalidRequest):
validation.filename_param([("filename", name)])
def test_filename_must_be_single_and_present():
with pytest.raises(InvalidRequest):
validation.filename_param([])
with pytest.raises(InvalidRequest):
validation.filename_param([("filename", "a.png"), ("filename", "b.png")])
def test_query_must_be_valid_utf8():
assert validation.query_items(b"filename=%D1%84.png") == [("filename", "ф.png")]
with pytest.raises(InvalidRequest):
validation.query_items(b"filename=%FF%FE.png")
+224
View File
@@ -0,0 +1,224 @@
"""Unit tests of lab 5 without services: variant geometry and encoding (imaging.build, the same
code the worker runs in its child process), the job message schema, backoff with jitter and the
pipeline configuration."""
from __future__ import annotations
import io
import json
import sys
import uuid
from pathlib import Path
import pytest
from jsonschema import Draft202012Validator
from PIL import Image
ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "src"))
sys.path.insert(0, str(ROOT / "student-tests"))
import imagegen # noqa: E402
from messenger import broker, imaging, jobs # noqa: E402
from messenger.config import ConfigError, Settings # noqa: E402
from messenger.pipeline import PIPELINES, center_square, fit # noqa: E402
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
SCHEMA = json.loads((ROOT / "contracts" / "jobs.schema.json").read_text(encoding="utf-8"))
LIMIT = 40_000_000
def variants(data: bytes, content_type: str = "image/png", version: int = 1) -> dict[str, imaging.Rendered]:
return {v.name: v for v in imaging.build(data, content_type, version, LIMIT)}
def decoded(v: imaging.Rendered) -> Image.Image:
img = Image.open(io.BytesIO(v.data))
img.load()
return img
# ------------------------------------------------------------------ geometry (contract rules)
@pytest.mark.parametrize("size, box, expected", [
((320, 200), 256, (256, 160)), # public fixture
((200, 320), 256, (160, 256)),
((100, 50), 256, (100, 50)), # never upscale
((256, 256), 256, (256, 256)),
((1000, 1), 256, (256, 1)), # 0.256 px -> minimum 1 px
((1, 1000), 256, (1, 256)),
((257, 255), 256, (256, 254)), # 255 * 256 / 257 = 254.0 (floor)
((3000, 2000), 1280, (1280, 853)), # 853.33 -> 853
])
def test_fit_rounds_down_without_upscaling(size, box, expected):
assert fit(*size, box) == expected
def test_center_square():
assert center_square(320, 200) == (60, 0, 260, 200)
assert center_square(7, 10) == (0, 1, 7, 8)
def test_public_fixture_variants_match_the_contract():
out = variants(SAMPLE)
assert list(out) == ["thumbnail", "crop", "optimized"]
assert (out["thumbnail"].content_type, decoded(out["thumbnail"]).format, decoded(out["thumbnail"]).size) == \
("image/jpeg", "JPEG", (256, 160))
assert (out["crop"].content_type, decoded(out["crop"]).size) == ("image/jpeg", (128, 128))
assert (out["optimized"].content_type, decoded(out["optimized"]).format, decoded(out["optimized"]).size) == \
("image/webp", "WEBP", (320, 200)) # fits 1280 already: no upscale
for v in out.values():
assert (v.width, v.height) == decoded(v).size
def test_small_image_is_not_upscaled_but_crop_is():
out = variants(imagegen.png(40, 30))
assert decoded(out["thumbnail"]).size == (40, 30)
assert decoded(out["optimized"]).size == (40, 30)
assert decoded(out["crop"]).size == (128, 128)
def test_big_image_is_bounded_by_1280():
out = variants(imagegen.png(3000, 2000))
assert decoded(out["optimized"]).size == (1280, 853)
assert decoded(out["thumbnail"]).size == (256, 170)
def test_exif_orientation_is_applied_and_dropped():
# 60x20 stored landscape with Orientation=6 (rotate 90 CW): displayed portrait 20x60.
img = Image.new("RGB", (60, 20), (200, 30, 30))
exif = Image.Exif()
exif[0x0112] = 6
buf = io.BytesIO()
img.save(buf, "JPEG", exif=exif.tobytes(), quality=95)
out = variants(buf.getvalue(), "image/jpeg")
assert decoded(out["thumbnail"]).size == (20, 60)
assert decoded(out["optimized"]).size == (20, 60)
for v in out.values():
assert not decoded(v).getexif(), v.name
def test_alpha_is_composited_on_white_for_jpeg_and_kept_for_webp():
img = Image.new("RGBA", (64, 64), (255, 0, 0, 0)) # fully transparent red
buf = io.BytesIO()
img.save(buf, "PNG")
out = variants(buf.getvalue())
thumb = decoded(out["thumbnail"]).convert("RGB")
assert min(thumb.getpixel((32, 32))) >= 250, "transparent pixels must become white, not red/black"
webp = decoded(out["optimized"])
assert webp.mode == "RGBA" and webp.getpixel((10, 10))[3] == 0
def test_metadata_is_not_copied():
img = Image.new("RGB", (300, 300), (10, 200, 10))
exif = Image.Exif()
exif[0x010F] = "SecretCamera" # Make
buf = io.BytesIO()
img.save(buf, "JPEG", exif=exif.tobytes(), icc_profile=b"\0" * 128, comment=b"private")
out = variants(buf.getvalue(), "image/jpeg")
for name in ("thumbnail", "crop"):
data = out[name].data
assert b"Exif" not in data and b"ICC_PROFILE" not in data and b"SecretCamera" not in data, name
assert b"EXIF" not in out["optimized"].data and b"ICCP" not in out["optimized"].data
@pytest.mark.parametrize("mode", ["RGBA", "P", "1", "L", "LA", "RGB"])
def test_png_modes_are_processed(mode):
out = variants(imagegen.png(33, 17, mode))
assert decoded(out["thumbnail"]).size == (33, 17)
def test_16_bit_grey_is_scaled_not_clipped():
img = Image.new("I;16", (8, 8), 32768) # 50 % grey in 16 bits
buf = io.BytesIO()
img.save(buf, "PNG")
out = variants(buf.getvalue())
value = decoded(out["thumbnail"]).convert("L").getpixel((4, 4))
assert 120 <= value <= 135
def test_pipeline_versions_differ_in_bytes_not_in_geometry():
v1, v2 = variants(SAMPLE, version=1), variants(SAMPLE, version=2)
for name in v1:
assert (v1[name].width, v1[name].height) == (v2[name].width, v2[name].height)
assert v1[name].sha256 != v2[name].sha256
assert variants(SAMPLE, version=1)["thumbnail"].sha256 == v1["thumbnail"].sha256 # deterministic
def test_pixel_limit_is_checked_before_decoding():
# 8001 x 5000 = 40.005 Mpx with only a few rows of data: refused from the header (TooLarge);
# 20000 x 10000 is refused even earlier by Pillow's own bomb check (> 2 x MAX_IMAGE_PIXELS).
with pytest.raises(imaging.TooLarge):
imaging.build(imagegen.png_bomb_header(8001, 5000), "image/png", 1, LIMIT)
with pytest.raises((imaging.TooLarge, Image.DecompressionBombError)):
imaging.build(imagegen.png_bomb_header(), "image/png", 1, LIMIT)
def test_child_process_protocol_round_trip():
out = list(variants(SAMPLE).values())
raw = json.dumps({"variants": [{"name": v.name, "content_type": v.content_type, "width": v.width,
"height": v.height, "size": len(v.data)} for v in out]}).encode() + b"\n"
raw += b"".join(v.data for v in out)
parsed = imaging.parse_output(raw)
assert [(p.name, p.sha256) for p in parsed] == [(v.name, v.sha256) for v in out]
with pytest.raises(imaging.ProcessingError):
imaging.parse_output(raw[:-1])
# ------------------------------------------------------------------ message format
def test_encoded_message_matches_jobs_schema_and_carries_ids_only():
import datetime as dt
raw = broker.encode(str(uuid.uuid4()), str(uuid.uuid4()), 1, 2, dt.datetime.now(dt.timezone.utc))
body = json.loads(raw)
assert not list(Draft202012Validator(SCHEMA, format_checker=Draft202012Validator.FORMAT_CHECKER).iter_errors(body))
assert set(body) == {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at"}
assert broker.decode(raw) == body
@pytest.mark.parametrize("change", [
{"schema_version": 2}, {"type": "other"}, {"job_id": "not-a-uuid"}, {"attempt": 0}, {"attempt": True},
{"pipeline_version": "1"}, {"created_at": "yesterday"}, {"url": "http://evil"}, {"object_key": "a/b"},
{"traceparent": "bad"},
])
def test_invalid_messages_are_rejected(change):
body = json.loads(broker.encode(str(uuid.uuid4()), str(uuid.uuid4()), 1, 1,
__import__("datetime").datetime(2026, 1, 1, tzinfo=__import__("datetime").timezone.utc)))
body.update(change)
with pytest.raises(broker.BadMessage):
broker.decode(json.dumps(body).encode())
# The contract schema refuses the same messages (date-time needs an optional jsonschema extra).
checker = Draft202012Validator.FORMAT_CHECKER
assert list(Draft202012Validator(SCHEMA, format_checker=checker).iter_errors(body)) or "created_at" in change
def test_garbage_is_rejected():
for raw in (b"", b"[]", b"{", b"\xff", b"x" * 5000):
with pytest.raises(broker.BadMessage):
broker.decode(raw)
# ------------------------------------------------------------------ backoff and configuration
def test_backoff_is_full_jitter_and_capped():
assert jobs.backoff_delay(1, 2, 60, rnd=lambda: 1.0) == 2
assert jobs.backoff_delay(3, 2, 60, rnd=lambda: 1.0) == 8
assert jobs.backoff_delay(10, 2, 60, rnd=lambda: 1.0) == 60
assert jobs.backoff_delay(4, 2, 60, rnd=lambda: 0.0) == 0
samples = [jobs.backoff_delay(3, 2, 60) for _ in range(500)]
assert 0 <= min(samples) < 2 and 6 < max(samples) <= 8 # spread over the whole window
def test_pipeline_settings(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.setenv("S3_ACCESS_KEY_ID", "AKTEST")
monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret-for-unit-tests")
s = Settings.from_env()
assert (s.job_max_attempts, s.job_timeout_seconds, s.worker_concurrency, s.staging_retention_seconds) == (5, 60, 2, 86400)
assert s.s3_staging_bucket == "messenger-staging" and s.pipeline_version == 1
monkeypatch.setenv("FAULT_POINTS", "transient_error=3,slow")
s = Settings.from_env()
assert s.fault_points == {"transient_error", "slow"} and s.fault_value("transient_error") == 3
for name, value in (("PIPELINE_VERSION", "9"), ("JOB_MAX_ATTEMPTS", "0"), ("FAULT_POINTS", "slow=x"),
("S3_STAGING_BUCKET", "messenger-attachments"), ("JOB_RETRY_BASE_SECONDS", "100")):
monkeypatch.setenv(name, value)
with pytest.raises(ConfigError):
Settings.from_env()
monkeypatch.delenv(name)
assert set(PIPELINES) == {1, 2, 3}
+196
View File
@@ -0,0 +1,196 @@
"""Lab 6 unit tests of the instrumentation (no stand): in-memory span/log/metric exporters.
What must hold (README level 3/4, reviewer remarks to other students):
* the HTTP SERVER span CONTINUES an incoming W3C traceparent (same trace id, parent = caller span),
it is SERVER (not INTERNAL), named by the route TEMPLATE; 5xx = error, 4xx = not an error;
* metric attributes are low-cardinality only (no ids, no raw path); buckets fit seconds;
* the job message carries traceparent in the schema field (contracts/jobs.schema.json);
* log records carry trace_id/span_id of the active span; successful probes are not exported.
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
import pytest
from jsonschema import Draft202012Validator
from opentelemetry import metrics, trace
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk._logs.export import InMemoryLogRecordExporter, SimpleLogRecordProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.trace import SpanKind, StatusCode
from starlette.applications import Starlette
from starlette.responses import JSONResponse
from starlette.routing import Route
from starlette.testclient import TestClient
from messenger import broker, telemetry
from messenger.app import RequestContextMiddleware, route_template
ROOT = Path(__file__).resolve().parents[2]
SPANS = InMemorySpanExporter()
LOGS = InMemoryLogRecordExporter()
METRICS = InMemoryMetricReader()
@pytest.fixture(scope="module", autouse=True)
def providers():
provider = TracerProvider()
provider.add_span_processor(SimpleSpanProcessor(SPANS))
trace.set_tracer_provider(provider)
metrics.set_meter_provider(MeterProvider(metric_readers=[METRICS]))
log_provider = LoggerProvider()
log_provider.add_log_record_processor(SimpleLogRecordProcessor(LOGS))
set_logger_provider(log_provider)
handler = telemetry.OtlpLogHandler(log_provider)
logger = logging.getLogger("messenger")
level = logger.level
logger.addHandler(handler)
logger.setLevel(logging.INFO)
yield
logger.removeHandler(handler)
logger.setLevel(level)
async def item(request):
status = int(request.query_params.get("status", "200"))
logging.getLogger("messenger.test").info("item_served", extra={"fields": {"item": "x", "n": 1}})
return JSONResponse({"ok": True}, status_code=status)
async def health(request):
return JSONResponse({"status": "ok"})
def client() -> TestClient:
app = Starlette(routes=[Route("/api/v1/items/{item_id}", item, methods=["GET"]),
Route("/health/live", health, methods=["GET"])])
app.add_middleware(RequestContextMiddleware, instance_id="unit-1")
return TestClient(app)
def server_spans():
return [s for s in SPANS.get_finished_spans() if s.kind == SpanKind.SERVER]
def test_server_span_continues_incoming_traceparent():
SPANS.clear()
trace_id, parent = "4bf92f3577b34da6a3ce929d0e0e4736", "00f067aa0ba902b7"
response = client().get("/api/v1/items/123e4567-e89b-12d3-a456-426614174000",
headers={"traceparent": f"00-{trace_id}-{parent}-01"})
assert response.status_code == 200
assert response.headers["x-trace-id"] == trace_id
(span,) = server_spans()
assert format(span.context.trace_id, "032x") == trace_id
assert format(span.parent.span_id, "016x") == parent and span.parent.is_remote
assert span.name == "GET /api/v1/items/{item_id}" # template, not the UUID
assert span.attributes["http.route"] == "/api/v1/items/{item_id}"
assert span.attributes["http.response.status_code"] == 200
assert span.status.status_code == StatusCode.UNSET
assert "123e4567" not in json.dumps(dict(span.attributes)) # no raw path / ids in attributes
def test_without_traceparent_a_new_root_trace_is_started():
SPANS.clear()
response = client().get("/api/v1/items/1")
(span,) = server_spans()
assert span.parent is None
assert response.headers["x-trace-id"] == format(span.context.trace_id, "032x")
def test_5xx_is_an_error_4xx_is_not():
SPANS.clear()
client().get("/api/v1/items/1?status=503")
client().get("/api/v1/items/1?status=404")
by_code = {s.attributes["http.response.status_code"]: s for s in server_spans()}
assert by_code[503].status.status_code == StatusCode.ERROR
assert by_code[404].status.status_code == StatusCode.UNSET
def test_health_probes_get_no_span_and_unknown_paths_one_label():
SPANS.clear()
c = client()
assert c.get("/health/live").status_code == 200
assert c.get("/scanner/random/path/12345").status_code == 404
assert [s.name for s in server_spans()] == ["GET UNMATCHED"]
assert route_template({}) == "UNMATCHED"
def test_http_metric_attributes_are_low_cardinality_and_buckets_fit_seconds():
client().get("/api/v1/items/42?status=200")
data = METRICS.get_metrics_data()
points = [p for rm in data.resource_metrics for sm in rm.scope_metrics for m in sm.metrics
if m.name == "http.server.request.duration" for p in m.data.data_points]
assert points
for point in points:
assert set(point.attributes) == {"http.request.method", "http.route", "http.response.status_code",
"http.response.status_class"}
assert "42" not in str(point.attributes["http.route"])
assert list(points[0].explicit_bounds) == list(telemetry.HTTP_BUCKETS)
assert points[0].explicit_bounds[0] <= 0.001 # millisecond resolution, not 0/5/10 s
def test_job_message_carries_traceparent_in_the_schema_field():
schema = json.loads((ROOT / "contracts" / "jobs.schema.json").read_text(encoding="utf-8"))
tracer = trace.get_tracer("test")
with tracer.start_as_current_span("producer", kind=SpanKind.PRODUCER) as span:
carrier = telemetry.inject()
import datetime as dt
raw = broker.encode("11111111-1111-4111-8111-111111111111", "22222222-2222-4222-8222-222222222222", 1, 1,
dt.datetime(2026, 11, 16, tzinfo=dt.timezone.utc), carrier)
body = json.loads(raw)
assert list(Draft202012Validator(schema).iter_errors(body)) == []
# flags: 01 = sampled (+ 02 = "random trace id", W3C Trace Context level 2, newer SDKs)
ctx = span.get_span_context()
assert body["traceparent"][:52] == f"00-{format(ctx.trace_id, '032x')}-{format(ctx.span_id, '016x')}"
assert int(body["traceparent"][-2:], 16) & 1 == 1
assert broker.decode(raw)["traceparent"] == body["traceparent"]
# the consumer side: the extracted context makes the CONSUMER span a child of the producer
ctx = telemetry.extract(body["traceparent"], body.get("tracestate"))
with tracer.start_as_current_span("consumer", context=ctx, kind=SpanKind.CONSUMER) as consumer:
assert consumer.parent.span_id == span.get_span_context().span_id
def test_log_records_carry_trace_context_and_fields():
LOGS.clear()
SPANS.clear()
client().get("/api/v1/items/7", headers={"X-Request-Id": "unit-req-1"})
records = [r.log_record for r in LOGS.get_finished_logs()]
served = next(r for r in records if r.body == "item_served")
(span,) = server_spans()
assert served.trace_id == span.context.trace_id and served.span_id == span.context.span_id
assert served.attributes["item"] == "x" and served.attributes["n"] == 1
access = next(r for r in records if r.body == "request")
assert access.attributes["request_id"] == "unit-req-1"
assert access.attributes["route"] == "/api/v1/items/{item_id}"
assert access.trace_id == span.context.trace_id
def test_successful_probe_lines_are_not_exported_failed_ones_are():
LOGS.clear()
log = logging.getLogger("messenger.access")
log.info("request", extra={"fields": {"route": "/health/ready", "status": 200}})
log.info("request", extra={"fields": {"route": "/health/ready", "status": 503}})
log.info("request", extra={"fields": {"route": "/api/v1/chats", "status": 200}})
exported = [(r.log_record.attributes["route"], r.log_record.attributes["status"]) for r in LOGS.get_finished_logs()]
assert exported == [("/health/ready", 503), ("/api/v1/chats", 200)]
def test_child_span_only_inside_a_traced_operation():
SPANS.clear()
with telemetry.child_span("orphan") as span:
assert span is None # no root spans from background loops
tracer = trace.get_tracer("test")
with tracer.start_as_current_span("job"):
with pytest.raises(ValueError):
with telemetry.child_span("step") as span:
assert span is not None
raise ValueError("boom")
step = next(s for s in SPANS.get_finished_spans() if s.name == "step")
assert step.status.status_code == StatusCode.ERROR and step.attributes["error.type"] == "ValueError"
+225
View File
@@ -0,0 +1,225 @@
"""Pure functions, no services: validation, cursor, Authorization parsing, Argon2id, config."""
from __future__ import annotations
import asyncio
import base64
import datetime as dt
import pytest
from messenger import authhdr, cursor, passwords, validation
from messenger.config import ConfigError, Settings
from messenger.errors import InvalidRequest, Unauthorized
from messenger.timefmt import UTC, from_us, rfc3339, to_us
def b64(raw: bytes) -> str:
return base64.b64encode(raw).decode()
# ------------------------------------------------------------------ password rules
@pytest.mark.parametrize("password", ["Twelve-chars", "я" * 128, "пароль:с:двоеточиями", "😀" * 12, "a b c d e f g"])
def test_valid_passwords(password):
assert validation.password_field({"password": password}) == password
@pytest.mark.parametrize("password", ["short-11ch", "я" * 129, " " * 12, "\t\n " * 5, "\ud800" * 12, None, 123456789012])
def test_invalid_passwords(password):
with pytest.raises(InvalidRequest):
validation.password_field({"password": password})
def test_text_may_contain_nul_but_not_lone_surrogates():
assert validation.text_field({"t": "a\u0000b"}, "t", 10) == "a\u0000b"
with pytest.raises(InvalidRequest):
validation.text_field({"t": "a\ud800"}, "t", 10)
# ------------------------------------------------------------------ cursor
CHAT = "3f2c7a5e-0b7d-4a35-9a43-8d1f0f3b2c11"
def test_cursor_roundtrip_and_binding():
key = (to_us(dt.datetime(2026, 10, 12, 12, 0, 0, 123456, tzinfo=UTC)), "11111111-1111-4111-8111-111111111111")
token = cursor.encode(cursor.MESSAGES, CHAT, key)
assert cursor.decode(token, cursor.MESSAGES, CHAT) == key
with pytest.raises(InvalidRequest):
cursor.decode(token, cursor.MESSAGES, "00000000-0000-4000-8000-000000000000") # other chat
with pytest.raises(InvalidRequest):
cursor.decode(token, cursor.CHATS, CHAT) # other resource
@pytest.mark.parametrize("payload", [
b"v1|m|" + CHAT.encode() + b"|253402300800000000|11111111-1111-4111-8111-111111111111", # 1 us after 9999-12-31
b"v1|m|" + CHAT.encode() + b"|9999999999999999999|11111111-1111-4111-8111-111111111111", # int64 edge
b"v1|m|" + CHAT.encode() + b"|-1|11111111-1111-4111-8111-111111111111",
b"v1|m|" + CHAT.encode() + b"|1|not-a-uuid",
b"v1|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-11111111111G",
b"v2|m|" + CHAT.encode() + b"|1|11111111-1111-4111-8111-111111111111",
])
def test_broken_cursors_are_400_not_500(payload):
token = base64.urlsafe_b64encode(payload).rstrip(b"=").decode()
with pytest.raises(InvalidRequest):
cursor.decode(token, cursor.MESSAGES, CHAT)
def test_time_helpers_are_exact():
moment = dt.datetime(2026, 2, 28, 23, 59, 59, 999999, tzinfo=UTC)
assert from_us(to_us(moment)) == moment
assert rfc3339(moment) == "2026-02-28T23:59:59.999999Z"
assert from_us(cursor.MAX_TS_US).year == 9999
# ------------------------------------------------------------------ Authorization header
def test_basic_is_parsed_and_password_may_contain_colons():
assert authhdr.parse_basic("Basic " + b64("alice:pa:ss:wörd".encode())) == ("alice", "pa:ss:wörd")
assert authhdr.parse_basic("basic " + b64(b"bob_1:x" * 1)) == ("bob_1", "x")
@pytest.mark.parametrize("header", [
None, "", "Basic", "Basic é", "Basic !!!!", "Basic " + b64(b"no-colon"), "Basic " + b64(b"\xff\xfe:pw"),
"Basic " + b64(b":password"), "Basic " + b64(b"alice:"), "Basic " + b64("Алиса:pw".encode()),
"Bearer " + "a" * 43, "Basic " + "A" * 2000,
])
def test_bad_basic_is_401_with_basic_challenge(header):
with pytest.raises(Unauthorized) as info:
authhdr.parse_basic(header)
assert info.value.headers["WWW-Authenticate"].startswith("Basic realm=\"messenger\"")
@pytest.mark.parametrize("header", [None, "", "Bearer", "Bearer short", "Bearer " + "a" * 43 + "!",
"Basic " + b64(b"alice:password-123"), "Token " + "a" * 43, "Bearer " + "é" * 43])
def test_bad_bearer_is_401_with_bearer_challenge(header):
with pytest.raises(Unauthorized) as info:
authhdr.parse_bearer(header)
assert info.value.headers["WWW-Authenticate"] == 'Bearer realm="messenger"'
def test_bearer_ok():
token = "A_b-" + "x" * 39
assert authhdr.parse_bearer("Bearer " + token) == token
# ------------------------------------------------------------------ Argon2id
def test_argon2id_hash_and_verify():
async def scenario():
stored = await passwords.hash_password("я" * 128)
assert stored.startswith("$argon2id$v=19$m=19456,t=2,p=1$")
assert await passwords.verify_password(stored, "я" * 128)
assert not await passwords.verify_password(stored, "я" * 127)
assert not await passwords.verify_password(None, "anything") # unknown user, dummy hash
assert not await passwords.verify_password("not-a-hash", "anything")
assert await passwords.hash_password("same password!") != await passwords.hash_password("same password!") # salt
asyncio.run(scenario())
# ------------------------------------------------------------------ config
@pytest.fixture(autouse=True)
def s3_credentials(monkeypatch):
"""Lab 4: Settings require the API's S3 key pair; synthetic values for the unit tests."""
monkeypatch.setenv("S3_ACCESS_KEY_ID", "AKTEST")
monkeypatch.setenv("S3_SECRET_ACCESS_KEY", "secret-for-unit-tests")
def test_s3_settings_are_validated_and_contract_limits_cannot_be_raised(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
settings = Settings.from_env()
assert (settings.max_upload_bytes, settings.max_image_pixels) == (10 * 1024 * 1024, 40_000_000)
assert settings.fault_points == frozenset() and settings.upload_concurrency == 4
for name, value in (("MAX_UPLOAD_BYTES", "10485761"), ("MAX_IMAGE_PIXELS", "40000001"),
("FAULT_POINTS", "drop_database"), ("S3_ENDPOINT", "ftp://s3"), ("S3_BUCKET", "Bad_Bucket")):
monkeypatch.setenv(name, value)
with pytest.raises(ConfigError):
Settings.from_env()
monkeypatch.delenv(name)
monkeypatch.delenv("S3_SECRET_ACCESS_KEY")
with pytest.raises(ConfigError):
Settings.from_env()
def test_settings_read_secret_files_and_contract_names(tmp_path, monkeypatch):
url_file = tmp_path / "database_url"
url_file.write_text("postgresql://u:p@db/x\n", encoding="utf-8")
monkeypatch.setenv("DATABASE_URL_FILE", str(url_file))
monkeypatch.setenv("SESSION_STORE", "redis")
monkeypatch.setenv("CACHE_URL", "redis://:p@valkey:6379/0")
monkeypatch.setenv("SESSION_TTL_SECONDS", "2")
settings = Settings.from_env()
assert settings.database_url == "postgresql://u:p@db/x"
assert settings.session_store == "valkey" and settings.session_ttl_seconds == 2
monkeypatch.setenv("SESSION_TTL_SECONDS", "0")
with pytest.raises(ConfigError):
Settings.from_env()
monkeypatch.setenv("SESSION_TTL_SECONDS", "2")
monkeypatch.setenv("DATABASE_URL_FILE", str(tmp_path / "missing"))
with pytest.raises(ConfigError) as info:
Settings.from_env()
assert "u:p" not in str(info.value)
# ------------------------------------------------------------------ lab 3: idempotency, JSON, instance id
@pytest.mark.parametrize("key", ["a", "k" * 128, "A-Za-z0-9._:-", "2026-10-16T10:00:00.1"])
def test_valid_idempotency_keys(key):
assert validation.idempotency_key(key) == key
@pytest.mark.parametrize("key", [None, "", "k" * 129, "ключ", "a b", "a/b", "a,b", "a\tb", "a\x00b", "*", "é"])
def test_invalid_idempotency_keys(key):
with pytest.raises(InvalidRequest):
validation.idempotency_key(key)
@pytest.mark.parametrize("raw", [b'{"text":"a","text":"b"}', b'{"a":{"x":1,"x":2}}', b'\xff', b'{"text":"x"} {}'])
def test_duplicate_keys_and_garbage_json_are_rejected(raw):
with pytest.raises(InvalidRequest):
validation.parse_json_object(raw)
def test_attachment_ids_absent_equals_empty_and_is_validated():
assert validation.attachment_ids_field({"text": "x"}) == []
assert validation.attachment_ids_field({"attachment_ids": []}) == []
one = "11111111-1111-4111-8111-111111111111"
assert validation.attachment_ids_field({"attachment_ids": [one.upper()]}) == [one]
for bad in (None, "x", [1], ["nope"], [one, one.upper()], [one] * 11):
with pytest.raises(InvalidRequest):
validation.attachment_ids_field({"attachment_ids": bad})
def test_request_fingerprint_ignores_key_order_and_default_attachments():
from messenger.app import request_fingerprint
assert request_fingerprint("привет", []) == request_fingerprint("привет", [])
assert request_fingerprint("привет", []) != request_fingerprint("привет ", [])
assert request_fingerprint("a\u0000b", []) != request_fingerprint("ab", [])
one = "11111111-1111-4111-8111-111111111111"
assert request_fingerprint("x", [one]) != request_fingerprint("x", [])
def test_instance_id_defaults_to_hostname_and_is_validated(monkeypatch):
import socket
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.delenv("INSTANCE_ID", raising=False)
assert Settings.from_env().instance_id == socket.gethostname()
monkeypatch.setenv("INSTANCE_ID", "replica-a")
assert Settings.from_env().instance_id == "replica-a"
for bad in ("with space", "x" * 65, "ip/1"):
monkeypatch.setenv("INSTANCE_ID", bad)
with pytest.raises(ConfigError):
Settings.from_env()
def test_idempotency_ttl_cannot_be_below_24_hours(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.setenv("IDEMPOTENCY_TTL_SECONDS", "3600")
with pytest.raises(ConfigError):
Settings.from_env()
def test_message_write_path_setting(monkeypatch):
monkeypatch.setenv("DATABASE_URL", "postgresql://x@y/z")
monkeypatch.delenv("MESSAGE_WRITE_PATH", raising=False)
assert Settings.from_env().message_write_path == "function"
monkeypatch.setenv("MESSAGE_WRITE_PATH", "multi")
assert Settings.from_env().message_write_path == "multi"
monkeypatch.setenv("MESSAGE_WRITE_PATH", "fast")
with pytest.raises(ConfigError):
Settings.from_env()