import { describe, expect, test } from 'bun:test'
import { compare, diffImage, inkBox, parseHex, sideBySide, TOLERANCE, verdict } from '../tools/bench/diff'
import type { Image } from '../tools/bench/png'
function solid(width: number, height: number, hex: string): Image {
const [r, g, b] = parseHex(hex)
const data = new Uint8Array(width * height * 4)
for (let i = 0; i < width * height; i++) data.set([r, g, b, 255], i * 4)
return { width, height, data }
}
function put(img: Image, x: number, y: number, hex: string) {
const [r, g, b] = parseHex(hex)
img.data.set([r, g, b, 255], (y * img.width + x) * 4)
}
describe('bench diff', () => {
test('identical images pass with zero delta', () => {
const m = compare(solid(4, 3, '#313031'), solid(4, 3, '#313031'))
expect(m.maxDelta).toBe(0)
expect(m.pixels).toBe(12)
expect(m.verdict).toBe('PASS')
})
test('tiers: Δ2 pass, small Δ8 near, big share or Δ9 fail', () => {
expect(verdict(2, 0, 1000, true)).toBe('PASS')
expect(verdict(8, 20, 1000, true)).toBe('NEAR')
expect(verdict(8, 21, 1000, true)).toBe('FAIL')
expect(verdict(9, 1, 1000, true)).toBe('FAIL')
expect(verdict(0, 0, 1000, false)).toBe('FAIL')
expect(TOLERANCE.nearShareOver).toBe(0.02)
})
test('counts pixels over 2 and over 8, per channel max', () => {
const a = solid(3, 1, '#000000')
const b = solid(3, 1, '#000000')
put(b, 0, 0, '#000300')
put(b, 1, 0, '#090000')
const m = compare(a, b)
expect(m.maxDelta).toBe(9)
expect(m.over2).toBe(2)
expect(m.over8).toBe(1)
})
test('masked pixels are not scored but their ink box is', () => {
const a = solid(10, 10, '#242324')
const b = solid(10, 10, '#242324')
put(a, 3, 3, '#ffffff')
put(b, 4, 3, '#ffffff')
const m = compare(a, b, [[2, 2, 5, 5]], '#242324')
expect(m.maxDelta).toBe(0)
expect(m.pixels).toBe(75)
expect(m.text[0]!.edges).toEqual([1, 0, 1, 0])
expect(m.verdict).toBe('PASS')
put(b, 6, 3, '#ffffff')
expect(compare(a, b, [[2, 2, 5, 5]], '#242324').verdict).toBe('FAIL')
})
test('ink box ignores near-background pixels', () => {
const img = solid(5, 5, '#313031')
put(img, 1, 1, '#404040') // Δ 15, below threshold
put(img, 2, 3, '#ffffff')
expect(inkBox(img, [0, 0, 5, 5], '#313031')).toEqual([2, 3, 3, 4])
expect(inkBox(solid(2, 2, '#313031'), [0, 0, 2, 2], '#313031')).toBeNull()
})
test('size mismatch throws', () => {
expect(() => compare(solid(2, 2, '#000'), solid(3, 2, '#000'))).toThrow('size mismatch')
})
test('diff image amplifies and side by side lays out with a gap', () => {
const a = solid(2, 1, '#000000')
const b = solid(2, 1, '#000000')
put(b, 1, 0, '#010203')
const d = diffImage(a, b)
expect([...d.data.subarray(4, 8)]).toEqual([8, 16, 24, 255])
const s = sideBySide([a, b, d], 2)
expect(s.width).toBe(10)
expect([...s.data.subarray(8, 12)]).toEqual([255, 0, 255, 255])
})
})