Files
saura_shakti_website/backend/tests/test_watermark_unit.py
T
Shubhankar45 53dbfa976b -
2026-11-13 12:14:55 +00:00

63 lines
2.6 KiB
Python

"""Unit tests for the watermark algorithm itself (no HTTP / DB)."""
from PIL import Image, ImageChops, ImageStat
from app.core.config import settings
from app.services.image_processing import apply_watermark
def _logo(path) -> Image.Image:
return Image.open(path).convert("RGBA")
def _bbox_of_change(a: Image.Image, b: Image.Image):
return ImageChops.difference(a.convert("RGB"), b.convert("RGB")).getbbox()
def test_watermark_bottom_right_and_proportional(logo_path):
logo = _logo(logo_path)
for size in [(4000, 3000), (1200, 800), (800, 1200), (300, 200)]:
img = Image.new("RGB", size, (90, 120, 150))
out = apply_watermark(img, logo)
assert out.size == size
x0, y0, x1, y1 = _bbox_of_change(img, out)
W, H = size
assert x0 > W / 2 and y0 > H / 2, "watermark must sit in the bottom-right quadrant"
margin = max(8, round(min(W, H) * settings.WATERMARK_MARGIN_RATIO))
assert W - x1 <= margin + 2 and H - y1 <= margin + 2 # consistent margins (halo may bleed slightly)
# scales with image size, capped at 50% width for small images
assert (x1 - x0) <= W * 0.5 + 10
def test_logo_aspect_ratio_never_distorted(logo_path):
logo = _logo(logo_path)
img = Image.new("RGB", (2000, 2000), (0, 0, 0))
out = apply_watermark(img, logo)
# Find the solid logo area: pixels clearly brighter than the halo
diff = ImageChops.difference(img, out.convert("RGB")).convert("L").point(lambda v: 255 if v > 100 else 0)
x0, y0, x1, y1 = diff.getbbox()
w, h = x1 - x0, y1 - y0
# fixture content is 400x80 inside a 400x120 canvas -> ratio 5.0
assert abs((w / h) - 5.0) < 0.25
def test_visible_on_bright_and_dark_photos(logo_path):
logo = _logo(logo_path) # white logo -> hardest case is a white photo
for colour in [(255, 255, 255), (0, 0, 0), (128, 128, 128)]:
img = Image.new("RGB", (1600, 1000), colour)
out = apply_watermark(img, logo).convert("RGB")
box = _bbox_of_change(img, out)
region_diff = ImageStat.Stat(ImageChops.difference(img.crop(box), out.crop(box))).mean
assert max(region_diff) > 20, f"watermark not visible on {colour}"
def test_transparency_keeps_photo_visible(logo_path):
logo = _logo(logo_path)
img = Image.new("RGB", (1600, 1000), (20, 140, 60))
out = apply_watermark(img, logo).convert("RGB")
x0, y0, x1, y1 = _bbox_of_change(img, out)
centre = out.getpixel(((x0 + x1) // 2, (y0 + y1) // 2))
# with partial opacity the green photo still shows through the white logo
assert centre != (255, 255, 255)
assert centre[1] > centre[0]