"""Offline Playwright Chromium lab for Chapter 30: Visual Regression Testing."""
import json
import os
import struct
import zlib
from playwright.sync_api import sync_playwright
def decode_png_pixels(data: bytes):
"""Pure-Python decoder for 8-bit RGB/RGBA PNGs returned by Chromium."""
assert data[:8] == b"\x89PNG\r\n\x1a\n", "Invalid PNG signature"
pos = 8
width = height = bit_depth = color_type = 0
idat_chunks = []
while pos < len(data):
length = struct.unpack(">I", data[pos : pos + 4])[0]
ctype = data[pos + 4 : pos + 8]
chunk = data[pos + 8 : pos + 8 + length]
pos += 12 + length
if ctype == b"IHDR":
width, height, bit_depth, color_type = struct.unpack(">IIBB", chunk[:10])
elif ctype == b"IDAT":
idat_chunks.append(chunk)
elif ctype == b"IEND":
break
assert bit_depth == 8 and color_type in (2, 6), f"Unsupported PNG format depth={bit_depth} type={color_type}"
bpp = 3 if color_type == 2 else 4
stride = width * bpp
raw = zlib.decompress(b"".join(idat_chunks))
out = bytearray(height * stride)
in_pos = 0
for y in range(height):
flt = raw[in_pos]
in_pos += 1
row_start = y * stride
prev_start = (y - 1) * stride
for x in range(stride):
val = raw[in_pos]
in_pos += 1
a = out[row_start + x - bpp] if x >= bpp else 0
b = out[prev_start + x] if y > 0 else 0
c = out[prev_start + x - bpp] if (y > 0 and x >= bpp) else 0
if flt == 0:
recon = val
elif flt == 1:
recon = (val + a) & 0xFF
elif flt == 2:
recon = (val + b) & 0xFF
elif flt == 3:
recon = (val + ((a + b) >> 1)) & 0xFF
elif flt == 4:
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c)
recon = (val + pr) & 0xFF
else:
raise ValueError(f"Unsupported PNG filter {flt}")
out[row_start + x] = recon
return width, height, bpp, bytes(out)
def diff_pngs(png_a: bytes, png_b: bytes):
wa, ha, bpp_a, px_a = decode_png_pixels(png_a)
wb, hb, bpp_b, px_b = decode_png_pixels(png_b)
assert (wa, ha, bpp_a) == (wb, hb, bpp_b), "Dimension/format mismatch"
total = wa * ha
diff = 0
for i in range(0, len(px_a), bpp_a):
if px_a[i : i + bpp_a] != px_b[i : i + bpp_a]:
diff += 1
return {"width": wa, "height": ha, "total_pixels": total, "diff_pixels": diff, "diff_ratio": round(diff / total, 6)}
def launch_chromium(p):
if os.path.exists(p.chromium.executable_path):
return p.chromium.launch(headless=True)
for ch in ("chrome", "msedge"):
try:
return p.chromium.launch(channel=ch, headless=True)
except Exception:
continue
raise RuntimeError("No Chromium/Chrome/Edge browser executable available")
def make_case(name, expected, actual):
return {"name": name, "expected": expected, "actual": actual, "passed": actual == expected}
def render_html(box_color="#1e40af", clock_text="12:00:01"):
return f"""<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
body {{ margin: 0; background: #ffffff; font-family: monospace; }}
nav {{ height: 40px; width: 400px; background: #0f172a; color: #ffffff; display: flex; align-items: center; padding-left: 12px; box-sizing: border-box; }}
#box {{ position: absolute; left: 20px; top: 60px; width: 100px; height: 50px; background: {box_color}; }}
#clock {{ position: absolute; left: 20px; top: 140px; width: 140px; height: 30px; background: #e2e8f0; color: #0f172a; line-height: 30px; padding: 0 8px; }}
@keyframes pulse {{ 0% {{ opacity: 1; }} 50% {{ opacity: 0.2; }} 100% {{ opacity: 1; }} }}
#badge {{ width: 20px; height: 20px; background: #22c55e; margin-left: auto; margin-right: 12px; animation: pulse 0.4s infinite; }}
</style>
</head>
<body>
<nav role="navigation"><span>Navbar</span><div id="badge"></div></nav>
<div id="box"></div>
<div id="clock">{clock_text}</div>
</body>
</html>"""
def main():
cases = []
with sync_playwright() as p:
browser = launch_chromium(p)
try:
ctx = browser.new_context(viewport={"width": 400, "height": 300})
pg = ctx.new_page()
# Case 1: Identical static page produces 0 pixel diff
pg.set_content(render_html("#1e40af", "12:00:01"))
base_png = pg.screenshot(animations="disabled")
same_png = pg.screenshot(animations="disabled")
d_same = diff_pngs(base_png, same_png)
cases.append(make_case(
"identical_page_zero_diff",
{"dims": [400, 300], "diff_pixels": 0, "diff_ratio": 0.0},
{"dims": [d_same["width"], d_same["height"]], "diff_pixels": d_same["diff_pixels"], "diff_ratio": d_same["diff_ratio"]},
))
# Case 2: CSS color change on 100x50 box yields exact 5000 diff pixels (ratio 0.041667)
pg.set_content(render_html("#dc2626", "12:00:01"))
changed_png = pg.screenshot(animations="disabled")
d_chg = diff_pngs(base_png, changed_png)
cases.append(make_case(
"css_change_detected_pixel_diff",
{
"diff_pixels": 5000,
"diff_ratio": 0.041667,
"exceeds_max_diff_pixels_100": True,
"exceeds_max_diff_ratio_0_01": True,
},
{
"diff_pixels": d_chg["diff_pixels"],
"diff_ratio": d_chg["diff_ratio"],
"exceeds_max_diff_pixels_100": d_chg["diff_pixels"] > 100,
"exceeds_max_diff_ratio_0_01": d_chg["diff_ratio"] > 0.01,
},
))
# Case 3: mask eliminates diff from dynamic timestamp text
pg.set_content(render_html("#1e40af", "12:00:01"))
unmasked_1 = pg.screenshot(animations="disabled")
masked_1 = pg.screenshot(animations="disabled", mask=[pg.locator("#clock")])
pg.set_content(render_html("#1e40af", "12:59:59"))
unmasked_2 = pg.screenshot(animations="disabled")
masked_2 = pg.screenshot(animations="disabled", mask=[pg.locator("#clock")])
d_unmasked = diff_pngs(unmasked_1, unmasked_2)
d_masked = diff_pngs(masked_1, masked_2)
cases.append(make_case(
"mask_eliminates_dynamic_region_diff",
{"unmasked_has_diff": True, "masked_diff_pixels": 0},
{"unmasked_has_diff": d_unmasked["diff_pixels"] > 0, "masked_diff_pixels": d_masked["diff_pixels"]},
))
# Case 4: Element locator screenshot (navbar) with animations='disabled' yields 0 diff
nav = pg.get_by_role("navigation")
nav_1 = nav.screenshot(animations="disabled")
pg.wait_for_timeout(120)
nav_2 = nav.screenshot(animations="disabled")
d_nav = diff_pngs(nav_1, nav_2)
cases.append(make_case(
"element_screenshot_and_animations_disabled",
{"nav_dims": [400, 40], "diff_pixels": 0},
{"nav_dims": [d_nav["width"], d_nav["height"]], "diff_pixels": d_nav["diff_pixels"]},
))
ctx.close()
finally:
browser.close()
print(json.dumps({"cases": cases}, ensure_ascii=False))
if __name__ == "__main__":
main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。
入口文件:projects/playwright-visual-lab/explore-visual.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-visual.py,或下载右侧课程工程包。 - 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a636.zip
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a602.zip