Files
Liber-public/crates/liber-format/tests/formats.rs
T

180 lines
8.8 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Every format opens into the same model.
mod common;
use common::*;
use liber_format::{Format, FormatError, Limits, open, sniff};
#[test]
fn epub_metadata_toc_images_cover() {
let mut e = Epub::new("R.U.R.")
.chapter("Předmluva", "<p>První <img src=\"../images/a.png\" alt=\"obr\"/> text.</p>")
.chapter("Druhá", "<h2>Heading two</h2><p>Text <a href=\"ch0.xhtml\">back</a>.</p>")
.file("OEBPS/images/a.png", PNG)
.file("OEBPS/images/cover.png", PNG);
e.extra_manifest =
r#"<item id="cover" href="images/cover.png" media-type="image/png" properties="cover-image"/>"#.into();
let d = open(&e.build(), Some("rur.epub"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Epub);
assert_eq!(d.metadata.title.as_deref(), Some("R.U.R."));
assert_eq!(d.metadata.authors, vec!["Karel Čapek"], "translators are not authors");
assert_eq!(d.metadata.language.as_deref(), Some("cs"));
assert_eq!(d.metadata.isbn.as_deref(), Some("9788020712479"));
assert_eq!(d.metadata.description.as_deref(), Some("A play about robots."));
assert_eq!(d.metadata.series.as_ref().map(|s| (s.name.as_str(), s.index)), Some(("Plays", Some(2.0))));
assert_eq!(d.toc.len(), 2);
assert_eq!(d.chapters[0].title.as_deref(), Some("Předmluva"));
assert_eq!(d.images.len(), 2);
assert!(d.chapters[0].xhtml.contains("data-img=\"0\""));
assert_eq!(d.cover, Some(1));
assert!(d.chapters[1].xhtml.contains("data-href=\"0\""));
}
#[test]
fn fb2_in_windows_1251_with_notes_and_images() {
let fb2 = format!(
r##"<?xml version="1.0" encoding="windows-1251"?>
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink">
<description><title-info><genre>sf</genre><author><first-name>Аркадий</first-name><last-name>Стругацкий</last-name></author>
<book-title>Пикник на обочине</book-title><lang>ru</lang><sequence name="Мир Полудня" number="3"/>
<coverpage><image l:href="#cover.png"/></coverpage></title-info>
<publish-info><isbn>978-0-441-17271-9</isbn></publish-info></description>
<body><title><p>Пикник</p><p>на обочине</p></title>
<section id="s1"><title><p>Глава 1</p></title><p>Текст с <emphasis>ударением</emphasis><a l:href="#n1" type="note">1</a>.</p>
<image l:href="#cover.png"/></section>
<section><title><p>Глава 2</p></title><p>Ещё текст.</p><empty-line/><poem><stanza><v>Строка</v></stanza></poem></section>
</body>
<body name="notes"><section id="n1"><title><p>1</p></title><p>Примечание.</p></section></body>
<binary id="cover.png" content-type="image/png">{}</binary>
</FictionBook>"##,
b64(PNG)
);
let (bytes, _, _) = encoding_rs::WINDOWS_1251.encode(&fb2);
let d = open(&bytes, Some("piknik.fb2"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Fb2);
assert_eq!(d.metadata.title.as_deref(), Some("Пикник на обочине"));
assert_eq!(d.metadata.authors, vec!["Аркадий Стругацкий"]);
assert_eq!(d.metadata.series.as_ref().map(|s| s.index), Some(Some(3.0)));
assert_eq!(d.metadata.isbn.as_deref(), Some("9780441172719"));
assert_eq!(d.chapters.len(), 4, "title page, two sections, notes");
assert_eq!(d.chapters[1].title.as_deref(), Some("Глава 1"));
assert!(d.chapters[1].xhtml.contains("<em>ударением</em>"));
let notes = d.chapters.len() - 1;
assert!(d.chapters[1].xhtml.contains(&format!("data-href=\"{notes}#n1\"")), "{}", d.chapters[1].xhtml);
assert!(d.footnotes.get(&format!("{notes}#n1")).is_some_and(|n| n.contains("Примечание")));
assert!(!d.chapters[notes].linear);
assert_eq!(d.images.len(), 1);
assert_eq!(d.cover, Some(0));
// The same book zipped.
let mut w = liber_format::zip::ZipWriter::new(Vec::new());
w.add("piknik.fb2", &bytes, true).unwrap();
let z = w.finish().unwrap();
let dz = open(&z, Some("piknik.fb2.zip"), &Limits::default()).unwrap();
assert_eq!(dz.format, Format::Fb2);
assert_eq!(dz.fingerprint(), d.fingerprint());
}
fn b64(d: &[u8]) -> String {
const A: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut s = String::new();
for c in d.chunks(3) {
let n = (c[0] as u32) << 16 | (*c.get(1).unwrap_or(&0) as u32) << 8 | *c.get(2).unwrap_or(&0) as u32;
for i in 0..4 {
if i <= c.len() {
s.push(A[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
s.push('=');
}
}
}
s
}
#[test]
fn txt_in_windows_1250_with_chapters() {
let text = "Title: Válka s mloky\r\nAuthor: Karel Čapek\r\n\r\nKAPITOLA I.\r\n\r\nKapitán van Toch šel\r\npo břehu.\r\n\r\nŘekl: „Ano.“\r\n\r\nKAPITOLA II.\r\n\r\nMloci přišli.\r\n";
let (bytes, _, _) = encoding_rs::WINDOWS_1250.encode(text);
let d = open(&bytes, Some("valka_s_mloky.txt"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Txt);
assert_eq!(d.metadata.title.as_deref(), Some("Válka s mloky"));
assert_eq!(d.metadata.authors, vec!["Karel Čapek"]);
assert_eq!(d.chapters.len(), 3, "front matter and two chapters");
assert_eq!(d.chapters[1].title.as_deref(), Some("KAPITOLA I."));
assert!(d.chapters[1].text().contains("Kapitán van Toch šel po břehu."), "hard wraps joined");
assert!(d.chapters[1].text().contains("„Ano.“"));
// Plain UTF-8 without headings: one chapter, the file name as title.
let d =
open("Just one line of text.\nAnd another.".as_bytes(), Some("C:\\books\\my_notes.txt"), &Limits::default())
.unwrap();
assert_eq!(d.chapters.len(), 1);
assert_eq!(d.metadata.title.as_deref(), Some("my notes"));
}
#[test]
fn mobi6_with_pagebreaks_images_and_exth() {
let mut m = Mobi::new(
"<html><head><guide></guide></head><body><h1>Jedna</h1><p>Příliš žluťoučký kůň.</p><img recindex=\"00001\"/>\
<mbp:pagebreak/><h1>Dvě</h1><p>Second <b>part</b>.<p>Unclosed para</body></html>",
);
m.images.push(PNG.to_vec());
m.exth.push((201, 0u32.to_be_bytes().to_vec()));
m.exth.push((503, b"Updated Title".to_vec()));
let d = open(&m.build(), Some("kun.mobi"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Mobi);
assert_eq!(d.metadata.title.as_deref(), Some("Updated Title"));
assert_eq!(d.metadata.authors, vec!["Karel Čapek"]);
assert_eq!(d.metadata.isbn.as_deref(), Some("9788020712479"));
assert_eq!(d.chapters.len(), 2);
assert_eq!(d.chapters[0].title.as_deref(), Some("Jedna"));
assert!(d.chapters[0].text().contains("Příliš žluťoučký kůň."));
assert!(d.chapters[0].xhtml.contains("data-img=\"0\""), "{}", d.chapters[0].xhtml);
assert!(d.chapters[1].xhtml.contains("<b>part</b>"));
assert_eq!(d.cover, Some(0));
// Uncompressed records read the same.
m.compression = 1;
let d1 = open(&m.build(), None, &Limits::default()).unwrap();
assert_eq!(d1.fingerprint(), d.fingerprint());
}
#[test]
fn azw3_splits_at_documents_and_reads_kindle_embed() {
let mut m = Mobi::new(
"<?xml version=\"1.0\"?><html><head></head><body aid=\"0\"></body></html><p>First file text.</p>\
<img src=\"kindle:embed:0001?mime=image/png\"/>\
<html><head></head><body aid=\"1\"></body></html><p>Second file text.</p>",
);
m.version = 8;
m.images.push(PNG.to_vec());
let d = open(&m.build(), Some("x.azw3"), &Limits::default()).unwrap();
assert_eq!(d.format, Format::Azw3);
assert_eq!(d.chapters.len(), 2);
assert!(d.chapters[0].text().contains("First file text."));
assert!(d.chapters[0].xhtml.contains("data-img=\"0\""));
assert!(d.chapters[1].text().contains("Second file text."));
}
#[test]
fn the_same_text_in_two_formats_has_one_fingerprint() {
let html = "<h1>Kapitola</h1><p>Stejný text, jiný formát.</p>";
let epub = open(&Epub::new("x").chapter("Kapitola", html).build(), None, &Limits::default()).unwrap();
let mobi =
open(&Mobi::new(&format!("<html><body>{html}</body></html>")).build(), None, &Limits::default()).unwrap();
assert_eq!(epub.fingerprint(), mobi.fingerprint());
let other =
open(&Epub::new("x").chapter("Kapitola", "<p>Jiný text.</p>").build(), None, &Limits::default()).unwrap();
assert_ne!(epub.fingerprint(), other.fingerprint());
}
#[test]
fn pdf_is_handed_to_the_pdf_view() {
assert_eq!(sniff(b"%PDF-1.7\n...", None), Some(Format::Pdf));
assert_eq!(open(b"%PDF-1.7\n...", None, &Limits::default()).unwrap_err(), FormatError::Pdf);
}
#[test]
fn binary_garbage_is_not_a_book() {
let junk: Vec<u8> = (0..10_000u32).map(|i| (i * 7 % 256) as u8).collect();
let r = open(&junk, Some("junk.bin"), &Limits::default());
assert!(r.is_err() || r.unwrap().chapters.len() <= 1);
}