[qr] QR: payloads, PNG and SVG, centre logo at level H, round-trip tests

This commit is contained in:
2026-11-16 13:15:30 +01:00
parent aec0a77786
commit eae7ef5578
14 changed files with 1335 additions and 0 deletions
+58
View File
@@ -0,0 +1,58 @@
//! Helpers shared by the integration tests: decoding a rendered code back with rqrr.
#![allow(dead_code)]
use image::{DynamicImage, GrayImage, Rgba, RgbaImage};
/// Decodes the single QR code in `img` and returns its text and the ECC level rqrr read (0 = M, 1 = L, 2 = H, 3 = Q).
pub fn decode_gray(gray: GrayImage) -> (String, u16) {
let mut prepared = rqrr::PreparedImage::prepare(gray);
let grids = prepared.detect_grids();
assert_eq!(grids.len(), 1, "expected exactly one QR code in the image, found {}", grids.len());
let (meta, content) = grids[0].decode().expect("the QR code should decode");
(content, meta.ecc_level)
}
pub fn decode(img: &RgbaImage) -> String {
decode_with_level(img).0
}
pub fn decode_with_level(img: &RgbaImage) -> (String, u16) {
decode_gray(DynamicImage::ImageRgba8(img.clone()).to_luma8())
}
/// rqrr's `ecc_level` numbering is the format-information encoding: M = 0, L = 1, H = 2, Q = 3.
pub fn rqrr_level(level: pictor_qr::Level) -> u16 {
match level {
pictor_qr::Level::M => 0,
pictor_qr::Level::L => 1,
pictor_qr::Level::H => 2,
pictor_qr::Level::Q => 3,
}
}
/// A logo: a filled red circle on a yellow square, with a transparent border.
pub fn logo(w: u32, h: u32) -> RgbaImage {
let mut img = RgbaImage::from_pixel(w, h, Rgba([0, 0, 0, 0]));
let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0);
let r = (w.min(h) as f64) * 0.35;
for y in 0..h {
for x in 0..w {
let border = x < w / 10 || y < h / 10 || x >= w - w / 10 || y >= h - h / 10;
let (dx, dy) = (x as f64 + 0.5 - cx, y as f64 + 0.5 - cy);
let px = if dx * dx + dy * dy <= r * r {
Rgba([200, 20, 40, 255])
} else if border {
Rgba([0, 0, 0, 0])
} else {
Rgba([240, 200, 30, 255])
};
img.put_pixel(x, y, px);
}
}
img
}
pub fn logo_png(w: u32, h: u32) -> Vec<u8> {
pictor_qr::encode_png(&logo(w, h)).expect("logo PNG")
}
+84
View File
@@ -0,0 +1,84 @@
//! Colour checks and input errors: typed, with a plain message.
mod common;
use common::logo;
use pictor_qr::{Level, QrError, Style, contrast_ok, contrast_ratio, render_png, render_rgba, render_svg};
#[test]
fn contrast_ratio_matches_wcag() {
assert!((contrast_ratio([0, 0, 0, 255], [255, 255, 255, 255]) - 21.0).abs() < 1e-9);
assert!((contrast_ratio([255, 255, 255, 255], [255, 255, 255, 255]) - 1.0).abs() < 1e-9);
// #777777 on white is about 4.48:1.
assert!((contrast_ratio([0x77, 0x77, 0x77, 255], [255, 255, 255, 255]) - 4.48).abs() < 0.01);
}
#[test]
fn contrast_ok_cases() {
assert!(contrast_ok([0, 0, 0, 255], [255, 255, 255, 255]));
assert!(contrast_ok([16, 32, 96, 255], [255, 250, 225, 255]));
assert!(!contrast_ok([200, 200, 200, 255], [255, 255, 255, 255]), "too light");
assert!(!contrast_ok([255, 255, 255, 255], [0, 0, 0, 255]), "inverted");
assert!(!contrast_ok([0, 0, 0, 0], [255, 255, 255, 255]), "transparent dark");
assert!(contrast_ok([0, 0, 0, 255], [255, 255, 255, 0]), "a transparent background is allowed");
}
#[test]
fn low_contrast_is_refused() {
let style = Style { dark: [180, 180, 180, 255], light: [255, 255, 255, 255], ..Style::default() };
let err = render_rgba("hello", Level::M, &style, None).unwrap_err();
assert!(matches!(err, QrError::LowContrast { .. }), "{err:?}");
assert!(err.to_string().contains("contrast"), "{err}");
assert!(matches!(render_svg("hello", Level::M, &style, None), Err(QrError::LowContrast { .. })));
assert!(matches!(render_png("hello", Level::M, &style, None), Err(QrError::LowContrast { .. })));
}
#[test]
fn inverted_and_transparent_are_refused() {
let inverted = Style { dark: [255, 255, 255, 255], light: [0, 0, 0, 255], ..Style::default() };
assert_eq!(render_rgba("x", Level::M, &inverted, None).unwrap_err(), QrError::Inverted);
let invisible = Style { dark: [0, 0, 0, 0], ..Style::default() };
assert_eq!(render_rgba("x", Level::M, &invisible, None).unwrap_err(), QrError::TransparentDark);
}
#[test]
fn empty_input_is_refused() {
assert_eq!(render_rgba("", Level::M, &Style::default(), None).unwrap_err(), QrError::Empty);
assert_eq!(render_svg(" ", Level::M, &Style::default(), None).unwrap_err(), QrError::Empty);
assert!(!QrError::Empty.to_string().is_empty());
}
#[test]
fn data_too_long_is_refused() {
let text = "ž".repeat(700); // 1400 bytes: fits at L, not at H (max 1273 bytes)
let err = render_rgba(&text, Level::H, &Style::default(), None).unwrap_err();
assert_eq!(err, QrError::TooLong { level: Level::H, logo: false });
assert!(err.to_string().contains("too much"), "{err}");
let style = Style { size_px: 2000, ..Style::default() };
assert!(render_rgba(&text, Level::L, &style, None).is_ok());
// With a logo the level is H whatever was asked, and the message says why.
let err = render_rgba(&text, Level::L, &style, Some(&logo(32, 32))).unwrap_err();
assert_eq!(err, QrError::TooLong { level: Level::H, logo: true });
assert!(err.to_string().contains("logo"), "{err}");
let err = render_rgba(&"a".repeat(5000), Level::L, &Style::default(), None).unwrap_err();
assert_eq!(err, QrError::TooLong { level: Level::L, logo: false });
}
#[test]
fn size_too_small_is_refused() {
let style = Style { size_px: 20, ..Style::default() };
let err = render_rgba("hello", Level::M, &style, None).unwrap_err();
assert!(matches!(err, QrError::SizeTooSmall { min_px: 29 }), "{err:?}");
}
#[test]
fn size_too_large_is_refused() {
let style = Style { size_px: 100_000, ..Style::default() };
assert!(matches!(render_rgba("hello", Level::M, &style, None), Err(QrError::SizeTooLarge { .. })));
}
#[test]
fn empty_logo_is_refused() {
let empty = image::RgbaImage::new(0, 0);
assert!(matches!(render_rgba("x", Level::M, &Style::default(), Some(&empty)), Err(QrError::Logo(_))));
}
+114
View File
@@ -0,0 +1,114 @@
//! Payload builders: the exact strings, escaping, and the input errors.
use pictor_qr::{Level, Payload, QrError, WifiSecurity, payload_string};
fn contact(name: &str) -> Payload {
Payload::Contact {
name: name.into(),
phone: None,
email: None,
organisation: None,
url: None,
address: None,
note: None,
}
}
#[test]
fn text_is_kept_exactly() {
let s = payload_string(&Payload::Text(" Příliš žluťoučký kůň\n".into())).unwrap();
assert_eq!(s, " Příliš žluťoučký kůň\n");
}
#[test]
fn url_without_scheme_gets_https() {
assert_eq!(payload_string(&Payload::Url("example.com/a?b=1".into())).unwrap(), "https://example.com/a?b=1");
assert_eq!(payload_string(&Payload::Url(" localhost:8080/x ".into())).unwrap(), "https://localhost:8080/x");
}
#[test]
fn url_with_scheme_is_kept() {
assert_eq!(payload_string(&Payload::Url("http://example.com".into())).unwrap(), "http://example.com");
assert_eq!(payload_string(&Payload::Url("mailto:a@b.cz".into())).unwrap(), "mailto:a@b.cz");
assert_eq!(payload_string(&Payload::Url("HTTPS://X.CZ".into())).unwrap(), "HTTPS://X.CZ");
}
#[test]
fn wifi_escapes_special_characters() {
let p = Payload::Wifi {
ssid: r#"Café;"Net",1:2\x"#.into(),
password: "pa;ss:wo,rd\"\\".into(),
security: WifiSecurity::Wpa,
hidden: true,
};
assert_eq!(payload_string(&p).unwrap(), r#"WIFI:T:WPA;S:Café\;\"Net\"\,1\:2\\x;P:pa\;ss\:wo\,rd\"\\;H:true;;"#);
}
#[test]
fn wifi_open_and_wep() {
let open =
Payload::Wifi { ssid: "Guest".into(), password: "ignored".into(), security: WifiSecurity::Open, hidden: false };
assert_eq!(payload_string(&open).unwrap(), "WIFI:T:nopass;S:Guest;;");
let wep =
Payload::Wifi { ssid: "Old".into(), password: "12345".into(), security: WifiSecurity::Wep, hidden: false };
assert_eq!(payload_string(&wep).unwrap(), "WIFI:T:WEP;S:Old;P:12345;;");
}
#[test]
fn wifi_needs_ssid_and_password() {
let no_ssid = Payload::Wifi { ssid: "".into(), password: "x".into(), security: WifiSecurity::Wpa, hidden: false };
assert!(matches!(payload_string(&no_ssid), Err(QrError::EmptyField { .. })));
let no_pass =
Payload::Wifi { ssid: "Home".into(), password: "".into(), security: WifiSecurity::Wpa, hidden: false };
let err = payload_string(&no_pass).unwrap_err();
assert!(matches!(err, QrError::EmptyField { .. }));
assert!(err.to_string().contains("password"), "{err}");
}
#[test]
fn vcard_full_contact() {
let p = Payload::Contact {
name: " Jan Novák ".into(),
phone: Some("+420 777 123 456".into()),
email: Some("jan@example.cz".into()),
organisation: Some("Firma, s.r.o.; IT".into()),
url: Some("https://example.cz/a,b".into()),
address: Some("Dlouhá 1\nPraha".into()),
note: Some("Back\\slash; and, comma\r\nnew line".into()),
};
let expected = "BEGIN:VCARD\r\nVERSION:3.0\r\nN:Novák;Jan;;;\r\nFN:Jan Novák\r\nORG:Firma\\, s.r.o.\\; IT\r\n\
TEL:+420 777 123 456\r\nEMAIL:jan@example.cz\r\nURL:https://example.cz/a,b\r\n\
ADR:;;Dlouhá 1\\nPraha;;;;\r\nNOTE:Back\\\\slash\\; and\\, comma\\nnew line\r\nEND:VCARD\r\n";
assert_eq!(payload_string(&p).unwrap(), expected);
}
#[test]
fn vcard_name_only_skips_empty_fields() {
let mut p = contact("Acme");
if let Payload::Contact { phone, .. } = &mut p {
*phone = Some(" ".into());
}
assert_eq!(payload_string(&p).unwrap(), "BEGIN:VCARD\r\nVERSION:3.0\r\nN:Acme;;;;\r\nFN:Acme\r\nEND:VCARD\r\n");
}
#[test]
fn empty_inputs_are_rejected() {
assert_eq!(payload_string(&Payload::Text("".into())), Err(QrError::Empty));
assert_eq!(payload_string(&Payload::Text(" \n ".into())), Err(QrError::Empty));
assert!(matches!(payload_string(&Payload::Url(" ".into())), Err(QrError::EmptyField { .. })));
assert!(matches!(payload_string(&contact(" ")), Err(QrError::EmptyField { .. })));
}
#[test]
fn payload_too_long_for_any_qr_code() {
let err = payload_string(&Payload::Text("a".repeat(8000))).unwrap_err();
assert_eq!(err, QrError::TooLong { level: Level::L, logo: false });
assert!(!err.to_string().is_empty());
}
#[test]
fn payload_serde_round_trip() {
let p = Payload::Wifi { ssid: "A".into(), password: "B".into(), security: WifiSecurity::Wep, hidden: true };
let json = serde_json::to_string(&p).unwrap();
assert_eq!(serde_json::from_str::<Payload>(&json).unwrap(), p);
}
+145
View File
@@ -0,0 +1,145 @@
//! Every generated code must decode back to the exact payload string (rqrr), at every level, in colour and with a
//! logo.
mod common;
use common::{decode, decode_with_level, logo, rqrr_level};
use pictor_qr::{Level, Payload, Style, WifiSecurity, payload_string, render_png, render_rgba};
const LEVELS: [Level; 4] = [Level::L, Level::M, Level::Q, Level::H];
fn payloads() -> Vec<(&'static str, String)> {
vec![
("czech text", payload_string(&Payload::Text("Příliš žluťoučký kůň úpěl ďábelské ódy".into())).unwrap()),
("url", payload_string(&Payload::Url("www.example.cz/cesta?q=žluť&x=1".into())).unwrap()),
(
"wifi",
payload_string(&Payload::Wifi {
ssid: r#"Domov; "5G", 2:4\x"#.into(),
password: r#"heslo;:,"\ž"#.into(),
security: WifiSecurity::Wpa,
hidden: true,
})
.unwrap(),
),
(
"vcard",
payload_string(&Payload::Contact {
name: "Jan Novák".into(),
phone: Some("+420 777 123 456".into()),
email: Some("jan.novak@example.cz".into()),
organisation: Some("Domi, s.r.o.".into()),
url: Some("https://example.cz".into()),
address: Some("Dlouhá 12\n110 00 Praha 1".into()),
note: Some("Poznámka; s čárkou, a\nřádkem".into()),
})
.unwrap(),
),
("ascii", "HELLO 12345 hello".to_string()),
]
}
fn navy_on_cream() -> Style {
Style { dark: [16, 32, 96, 255], light: [255, 250, 225, 255], ..Style::default() }
}
#[test]
fn all_payloads_all_levels_black_on_white() {
for (name, text) in payloads() {
for level in LEVELS {
let r = render_rgba(&text, level, &Style::default(), None).unwrap();
assert_eq!(r.level_used, level);
let (decoded, ecc) = decode_with_level(&r.image);
assert_eq!(decoded, text, "{name} at {level:?}");
assert_eq!(ecc, rqrr_level(level), "{name} at {level:?}");
}
}
}
#[test]
fn all_payloads_all_levels_navy_on_cream() {
for (name, text) in payloads() {
for level in LEVELS {
let r = render_rgba(&text, level, &navy_on_cream(), None).unwrap();
assert_eq!(r.image.get_pixel(0, 0).0, [255, 250, 225, 255], "the quiet zone is the light colour");
assert_eq!(decode(&r.image), text, "{name} at {level:?}");
}
}
}
#[test]
fn with_logo_forces_level_h_and_still_decodes() {
let logos = [logo(200, 200), logo(300, 120), logo(40, 90)];
for (name, text) in payloads() {
for lg in &logos {
for level in [Level::L, Level::M] {
let r = render_rgba(&text, level, &navy_on_cream(), Some(lg)).unwrap();
assert_eq!(r.level_used, Level::H, "a logo forces level H");
let (decoded, ecc) = decode_with_level(&r.image);
assert_eq!(decoded, text, "{name} with a {}x{} logo", lg.width(), lg.height());
assert_eq!(ecc, rqrr_level(Level::H));
}
}
}
}
#[test]
fn logo_is_drawn_centred_and_bounded() {
let text = payloads()[0].1.clone();
let style = Style { size_px: 600, ..Style::default() };
let r = render_rgba(&text, Level::M, &style, Some(&logo(100, 100))).unwrap();
let size = r.image.width();
let module_px = r.module_px;
let code_px = r.modules * module_px;
// The logo's red circle is in the middle of the image.
let centre = r.image.get_pixel(size / 2, size / 2).0;
assert_eq!(centre, [200, 20, 40, 255]);
// Nothing red farther than 22% of the code's width / 2 from the centre (plus a pixel of resampling).
let half = (code_px as f64 * 0.22 / 2.0).ceil() as i64 + 1;
for (x, y, p) in r.image.enumerate_pixels() {
if p.0[0] > 150 && p.0[1] < 100 {
let (dx, dy) = (x as i64 - size as i64 / 2, y as i64 - size as i64 / 2);
assert!(dx.abs() <= half && dy.abs() <= half, "logo pixel at {x},{y} outside the 22% box");
}
}
}
#[test]
fn small_payload_with_logo_still_decodes() {
for text in ["Hi", "https://x.cz", "1234567890"] {
let r = render_rgba(text, Level::L, &Style::default(), Some(&logo(64, 64))).unwrap();
assert_eq!(r.level_used, Level::H);
assert_eq!(decode(&r.image), text);
}
}
#[test]
fn size_is_integer_scaled_and_reported() {
let style = Style { size_px: 500, quiet_zone: 4, ..Style::default() };
let r = render_rgba("hello", Level::M, &style, None).unwrap();
let total = r.modules + 2 * 4;
assert_eq!(r.image.width(), r.image.height());
assert_eq!(r.image.width(), r.size_px);
assert_eq!(r.size_px, total * r.module_px);
assert!(r.size_px <= 500 && r.size_px > 500 - total, "{} px", r.size_px);
assert_eq!(r.module_px, 500 / total);
}
#[test]
fn png_decodes_back() {
let text = payloads()[3].1.clone();
let png = render_png(&text, Level::Q, &navy_on_cream(), Some(&logo(50, 50))).unwrap();
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap().to_rgba8();
assert_eq!(decode(&img), text);
}
#[test]
fn quiet_zone_widths_decode() {
for qz in [1, 4, 10] {
let style = Style { quiet_zone: qz, ..Style::default() };
let r = render_rgba("quiet zone", Level::M, &style, None).unwrap();
assert_eq!(r.size_px, (r.modules + 2 * qz) * r.module_px);
assert_eq!(decode(&r.image), "quiet zone");
}
}
+113
View File
@@ -0,0 +1,113 @@
//! SVG output: the structure, and a rasterisation of its module path that must decode back.
mod common;
use common::{decode_gray, logo_png};
use image::{GrayImage, Luma};
use pictor_qr::{Level, QrError, Style, render_rgba, render_svg};
/// The SVG's dark modules as horizontal runs `(x, y, len)` in module units (quiet zone included), parsed from the
/// path's `M{x} {y}h{len}v1h-{len}z` segments.
fn runs(svg: &str) -> Vec<(u32, u32, u32)> {
let start = svg.find(" d=\"").expect("a path with d") + 4;
let end = start + svg[start..].find('"').unwrap();
let d = &svg[start..end];
d.split('M')
.filter(|s| !s.is_empty())
.map(|seg| {
let (xy, rest) = seg.split_once('h').expect("h after M");
let (x, y) = xy.split_once(' ').expect("x y");
let (len, tail) = rest.split_once('v').expect("v after h");
assert_eq!(tail, format!("1h-{len}z"), "segment {seg}");
(x.parse().unwrap(), y.parse().unwrap(), len.parse().unwrap())
})
.collect()
}
fn view_box_size(svg: &str) -> u32 {
let start = svg.find("viewBox=\"0 0 ").unwrap() + 13;
let rest = &svg[start..];
rest[..rest.find(' ').unwrap()].parse().unwrap()
}
fn rasterise(svg: &str, scale: u32) -> GrayImage {
let n = view_box_size(svg);
let mut img = GrayImage::from_pixel(n * scale, n * scale, Luma([255]));
for (x, y, len) in runs(svg) {
for py in y * scale..(y + 1) * scale {
for px in x * scale..(x + len) * scale {
img.put_pixel(px, py, Luma([0]));
}
}
}
img
}
#[test]
fn svg_structure() {
let text = "Příliš žluťoučký kůň";
let style = Style { size_px: 400, ..Style::default() };
let svg = render_svg(text, Level::M, &style, None).unwrap();
assert!(svg.starts_with("<svg "), "{}", &svg[..40]);
assert!(svg.trim_end().ends_with("</svg>"));
assert!(svg.contains("xmlns=\"http://www.w3.org/2000/svg\""));
assert_eq!(svg.matches("<path").count(), 1);
assert!(!svg.contains("<image"));
// Same geometry as the raster output, and as many dark modules as the raster has.
let r = render_rgba(text, Level::M, &style, None).unwrap();
assert_eq!(view_box_size(&svg), r.modules + 8);
assert!(svg.contains(&format!("width=\"{}\" height=\"{}\"", r.size_px, r.size_px)));
let dark_svg: u32 = runs(&svg).iter().map(|r| r.2).sum();
let mut dark_png = 0;
for my in 0..r.modules + 8 {
for mx in 0..r.modules + 8 {
let p = r.image.get_pixel(mx * r.module_px + r.module_px / 2, my * r.module_px + r.module_px / 2);
if p.0[0] < 128 {
dark_png += 1;
}
}
}
assert_eq!(dark_svg, dark_png);
}
#[test]
fn svg_rasterised_decodes_at_all_levels() {
let text = "WIFI:T:WPA;S:Domov\\;5G;P:heslo\\:x;;";
for level in [Level::L, Level::M, Level::Q, Level::H] {
let svg = render_svg(text, level, &Style::default(), None).unwrap();
assert_eq!(decode_gray(rasterise(&svg, 6)).0, text, "{level:?}");
}
}
#[test]
fn svg_colours() {
let style = Style { dark: [16, 32, 96, 255], light: [255, 250, 225, 128], ..Style::default() };
let svg = render_svg("colour", Level::M, &style, None).unwrap();
assert!(svg.contains("fill=\"#102060\""), "{svg}");
assert!(svg.contains("fill=\"#fffae1\" fill-opacity=\"0.502\""), "{svg}");
}
#[test]
fn svg_with_logo_embeds_data_uri_and_clears_modules() {
let text = "https://example.cz/logo";
let png = logo_png(120, 60);
let with = render_svg(text, Level::L, &Style::default(), Some(&png)).unwrap();
let without_h = render_svg(text, Level::H, &Style::default(), None).unwrap();
assert_eq!(with.matches("<image").count(), 1);
assert!(with.contains("xlink:href=\"data:image/png;base64,iVBORw0KGgo"), "a base64 PNG data URI");
assert!(with.contains("preserveAspectRatio=\"xMidYMid meet\""));
// Level H was used (same module count as an H code without a logo), and modules under the plate are gone.
assert_eq!(view_box_size(&with), view_box_size(&without_h));
let dark_with: u32 = runs(&with).iter().map(|r| r.2).sum();
let dark_without: u32 = runs(&without_h).iter().map(|r| r.2).sum();
assert!(dark_with < dark_without);
// The cleared code (without drawing the logo) still decodes.
assert_eq!(decode_gray(rasterise(&with, 6)).0, text);
}
#[test]
fn svg_rejects_a_broken_logo() {
let err = render_svg("x", Level::M, &Style::default(), Some(b"not a png")).unwrap_err();
assert!(matches!(err, QrError::Logo(_)), "{err:?}");
}