AtlatestRepositorysigil-image

sigil-image / tree / testtest-image.sgl

1(import (sigil io)
2 (sigil test)
3 (sigil image))
4
5(define (fixture name)
6 (let* ((port (open-binary-input-file (string-append "test/fixtures/" name)))
7 (bytes (read-bytevector 65536 port)))
8 (close-port port)
9 bytes))
11(define png (fixture "logo.png"))
12(define jpeg (fixture "logo.jpg"))
14(test-group "bounded memory image normalization"
15 (test "PNG decodes and re-encodes to the same dimensions"
16 (let ((image (image-normalize-png png)))
17 (assert-equal (dict-ref image width:) 2)
18 (assert-equal (dict-ref image height:) 3)
19 (assert-equal (bytevector-u8-ref (dict-ref image bytes:) 0) 137)
20 (assert-equal (dict-ref (image-normalize-png (dict-ref image bytes:)) width:) 2)))
22 (test "JPEG is converted to PNG"
23 (let ((image (image-normalize-png jpeg)))
24 (assert-equal (dict-ref image width:) 2)
25 (assert-equal (dict-ref image height:) 3)
26 (assert-equal (bytevector-u8-ref (dict-ref image bytes:) 0) 137)))
28 (test "normalization removes ancillary source metadata"
29 (let* ((bytes (dict-ref (image-normalize-png png) bytes:))
30 (port (open-output-string)))
31 ;; Re-encoded PNG contains only IHDR, IDAT and IEND chunks.
32 (let loop ((at 8))
33 (when (< at (bytevector-length bytes))
34 (let ((length (+ (* 16777216 (bytevector-u8-ref bytes at))
35 (* 65536 (bytevector-u8-ref bytes (+ at 1)))
36 (* 256 (bytevector-u8-ref bytes (+ at 2)))
37 (bytevector-u8-ref bytes (+ at 3))))
38 (kind (utf8->string (bytevector-copy bytes (+ at 4) (+ at 8)))))
39 (assert-true (if (member kind '("IHDR" "IDAT" "IEND")) #t #f))
40 (loop (+ at length 12)))))))
42 (test "invalid, truncated and unsupported bytes are rejected"
43 (assert-false (image-normalize-png (make-bytevector 0)))
44 (assert-false (image-normalize-png (string->utf8 "<svg></svg>")))
45 (assert-false (image-normalize-png (bytevector-copy png 0 30)))))
47(test-group "decode budgets"
48 (test "dimensions, pixels and input bytes are bounded before decoding"
49 (assert-false (image-normalize-png png max-dimension: 2))
50 (assert-false (image-normalize-png png max-pixels: 5))
51 (assert-false (image-normalize-png png max-input-bytes: 8)))
53 (test "invalid limits and non-bytevector input raise errors"
54 (assert-error (image-normalize-png "not bytes"))
55 (assert-error (image-normalize-png png max-dimension: 0))
56 (assert-error (image-normalize-png png max-pixels: 16777217))
57 (assert-error (image-normalize-png png max-input-bytes: 16777217))))