pub mod error;
pub mod open;
pub mod query;
pub use error::ServiceError;
pub use open::{
format_token, DocumentInfo, DocumentService, DocumentSource, OpenOptions, OpenedDocument,
DEFAULT_MAX_BYTES,
};
pub use query::{PageText, SearchOptions, SearchOutcome, TextExport, TextExportOptions};
#[cfg(test)]
mod tests {
use super::*;
use crate::parser::FileFormat;
use std::path::{Path, PathBuf};
fn sample(relative: &str) -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR")).join(relative)
}
fn hwpx_sample() -> PathBuf {
sample("samples/hwpx/143E433F503322BD33.hwpx")
}
fn hwp_sample() -> PathBuf {
sample("samples/143E433F503322BD33.hwp")
}
fn service() -> DocumentService {
DocumentService::new().with_max_bytes(None)
}
#[test]
fn open_path_reads_and_parses_hwpx_sample() {
let path = hwpx_sample();
let expected_size = std::fs::metadata(&path).expect("샘플 메타").len() as usize;
let opened = service()
.open_path(&path, &OpenOptions::new())
.expect("HWPX 샘플은 열려야 한다");
assert_eq!(opened.format(), FileFormat::Hwpx);
assert_eq!(opened.size_bytes(), expected_size);
assert_eq!(
opened.source(),
&DocumentSource::Path(path),
"경로에서 열었으면 출처가 경로여야 한다"
);
assert!(opened.page_count() >= 1);
}
#[test]
fn format_is_auto_detected_from_bytes_alone() {
let hwpx = std::fs::read(hwpx_sample()).expect("HWPX 샘플 읽기");
let hwp = std::fs::read(hwp_sample()).expect("HWP 샘플 읽기");
let opened_hwpx = service()
.open_bytes(&hwpx, &OpenOptions::new())
.expect("HWPX 바이트");
let opened_hwp = service()
.open_bytes(&hwp, &OpenOptions::new())
.expect("HWP 바이트");
assert_eq!(opened_hwpx.format(), FileFormat::Hwpx);
assert_eq!(opened_hwp.format(), FileFormat::Hwp);
assert_eq!(opened_hwpx.info().format, "hwpx");
assert_eq!(opened_hwp.info().format, "hwp5");
assert_eq!(opened_hwpx.source(), &DocumentSource::Bytes);
}
#[test]
fn missing_path_is_not_found_not_parse_failure() {
let missing = sample("samples/이런파일은없다_87f3.hwpx");
let error = service()
.open_path(&missing, &OpenOptions::new())
.expect_err("없는 파일은 실패해야 한다");
assert_eq!(
error,
ServiceError::NotFound {
path: missing.clone()
}
);
assert_eq!(error.code(), "NOT_FOUND");
assert!(error.is_usage_error());
assert!(!error.needs_password());
}
#[test]
fn unrecognized_bytes_are_unsupported_format() {
let service = service();
let junk = service
.open_bytes(b"this is not a hwp document at all", &OpenOptions::new())
.expect_err("미상 바이트는 실패해야 한다");
assert_eq!(
junk,
ServiceError::UnsupportedFormat {
detected: FileFormat::Unknown
}
);
assert_eq!(junk.code(), "UNSUPPORTED_FORMAT");
let empty = service
.open_bytes(&[], &OpenOptions::new())
.expect_err("빈 입력은 실패해야 한다");
assert_eq!(
empty,
ServiceError::UnsupportedFormat {
detected: FileFormat::Empty
}
);
}
#[test]
fn size_limit_rejects_before_parsing() {
let bytes = std::fs::read(hwpx_sample()).expect("HWPX 샘플 읽기");
let limit = 1024;
assert!(
bytes.len() > limit,
"샘플이 상한보다 커야 의미 있는 검증이다"
);
let error = DocumentService::new()
.open_bytes(&bytes, &OpenOptions::new().with_max_bytes(limit))
.expect_err("상한 초과는 실패해야 한다");
assert_eq!(
error,
ServiceError::TooLarge {
size_bytes: bytes.len(),
limit_bytes: limit,
}
);
assert_eq!(error.code(), "TOO_LARGE");
let tight = DocumentService::new().with_max_bytes(Some(limit));
assert!(tight.open_bytes(&bytes, &OpenOptions::new()).is_err());
assert!(tight
.open_bytes(&bytes, &OpenOptions::new().with_max_bytes(bytes.len()))
.is_ok());
}
#[test]
fn info_reports_format_size_and_counts() {
let path = hwpx_sample();
let expected_size = std::fs::metadata(&path).expect("샘플 메타").len() as usize;
let opened = service()
.open_path(&path, &OpenOptions::new())
.expect("HWPX 샘플");
let info = opened.info();
assert_eq!(info.format, "hwpx");
assert_eq!(info.size_bytes, expected_size);
assert!(info.sections >= 1, "구역이 최소 하나는 있어야 한다");
assert_eq!(info.page_count, opened.page_count());
assert!(info.para_count >= 1, "문단이 최소 하나는 있어야 한다");
assert!(!info.encrypted, "평문 샘플이다");
assert!(info.version.is_some(), "HWPX 는 버전 문자열을 갖는다");
let json = serde_json::to_value(&info).expect("직렬화");
for key in ["format", "sizeBytes", "pageCount", "paraCount", "fonts"] {
assert!(json.get(key).is_some(), "{key} 필드가 있어야 한다");
}
}
#[test]
fn title_scan_can_be_disabled() {
let path = hwpx_sample();
let scanned = service()
.open_path(&path, &OpenOptions::new())
.expect("HWPX 샘플")
.info();
let unscanned = service()
.with_title_scan(false)
.open_path(&path, &OpenOptions::new())
.expect("HWPX 샘플")
.info();
assert!(
unscanned.title.is_none(),
"제목 추정을 끄면 언제나 None 이다"
);
assert_eq!(scanned.page_count, unscanned.page_count);
assert_eq!(scanned.fonts, unscanned.fonts);
}
#[test]
fn export_text_keeps_one_entry_per_page() {
let opened = service()
.open_path(&hwpx_sample(), &OpenOptions::new())
.expect("HWPX 샘플");
let export = opened.export_text(&TextExportOptions::new());
assert_eq!(
export.page_count as u32,
opened.page_count(),
"쪽 항목을 빼면 pageCount 가 문서를 실제보다 짧게 말한다"
);
assert_eq!(export.pages.len(), export.page_count);
for (index, page) in export.pages.iter().enumerate() {
assert_eq!(page.page, index as u32, "쪽 번호는 0부터 연속이다");
}
assert!(!export.truncated);
assert_eq!(export.omitted_count, 0);
assert_eq!(export.next_offset, None, "무제한이면 더 읽을 것이 없다");
assert!(export.out_of_range.is_empty());
assert!(!export.has_failures());
assert!(
!export.concatenated().trim().is_empty(),
"샘플에는 본문 텍스트가 있다"
);
}
#[test]
fn export_text_truncation_reports_omission_and_next_offset() {
let opened = service()
.open_path(&hwpx_sample(), &OpenOptions::new())
.expect("HWPX 샘플");
let full = opened.export_text(&TextExportOptions::new());
let full_chars: usize = full.pages.iter().map(|p| p.text.chars().count()).sum();
assert!(full_chars > 40, "절단을 검증하려면 본문이 충분해야 한다");
let cut = opened.export_text(&TextExportOptions::new().with_max_chars(20));
let cut_chars: usize = cut.pages.iter().map(|p| p.text.chars().count()).sum();
assert_eq!(cut_chars, 20);
assert!(cut.truncated);
assert_eq!(cut.omitted_count, full_chars - 20);
assert_eq!(cut.next_offset, Some(20), "이어읽기 지점을 명시한다");
assert_eq!(
cut.page_count, full.page_count,
"예산이 떨어져도 쪽 주소는 남는다"
);
}
#[test]
fn export_text_out_of_range_page_is_data_not_error() {
let opened = service()
.open_path(&hwpx_sample(), &OpenOptions::new())
.expect("HWPX 샘플");
let beyond = opened.page_count() + 100;
let export = opened.export_text(&TextExportOptions::new().with_pages(vec![0, beyond]));
assert_eq!(export.pages.len(), 1, "유효한 쪽만 실린다");
assert_eq!(export.pages[0].page, 0);
assert_eq!(
export.out_of_range,
vec![beyond],
"건너뛴 쪽을 조용히 숨기지 않는다"
);
}
#[test]
fn search_returns_matches_with_coordinates() {
let opened = service()
.open_path(&hwpx_sample(), &OpenOptions::new())
.expect("HWPX 샘플");
let text = opened.export_text(&TextExportOptions::new()).concatenated();
let seed = text
.chars()
.find(|c| {
!c.is_whitespace()
&& !opened
.search(&c.to_string(), &SearchOptions::new())
.is_empty()
})
.expect("본문 글자가 문단에서도 찾혀야 한다");
let seeded = opened.search(&seed.to_string(), &SearchOptions::new());
let anchor = &seeded.matches[0];
let needle: String = anchor
.text
.chars()
.skip(anchor.char_offset)
.take(2)
.collect();
let found = opened.search(&needle, &SearchOptions::new());
assert!(!found.is_empty(), "문단에서 뽑은 문자열은 찾혀야 한다");
assert_eq!(found.query, needle);
assert_eq!(found.match_count, found.matches.len());
assert_eq!(found.match_count, found.total_match_count);
assert!(!found.truncated);
assert_eq!(found.omitted_count, 0);
let first = &found.matches[0];
assert_eq!(first.length, needle.chars().count());
assert!(
first.text.contains(&needle),
"매치가 속한 문단 텍스트가 함께 온다"
);
assert!(
found.matches.iter().any(|m| m.page.is_some()),
"매치에 쪽 좌표가 붙어야 한다"
);
}
#[test]
fn search_without_match_is_ok_not_error() {
let opened = service()
.open_path(&hwpx_sample(), &OpenOptions::new())
.expect("HWPX 샘플");
let none = opened.search("존재하지않는문자열_9f2c1b7e", &SearchOptions::new());
assert!(none.is_empty());
assert_eq!(none.total_match_count, 0);
assert_eq!(none.match_count, 0);
assert!(none.matches.is_empty());
assert!(!none.truncated, "0건은 절단이 아니다");
assert_eq!(none.next_offset, None);
let empty = opened.search("", &SearchOptions::new());
assert!(empty.is_empty());
}
#[test]
fn search_window_walks_all_matches_without_moving_the_total() {
let opened = service()
.open_path(&hwpx_sample(), &OpenOptions::new())
.expect("HWPX 샘플");
let text = opened.export_text(&TextExportOptions::new()).concatenated();
let needle = text
.chars()
.find(|c| {
!c.is_whitespace()
&& opened
.search(&c.to_string(), &SearchOptions::new())
.total_match_count
>= 3
})
.map(|c| c.to_string())
.expect("3건 이상 나오는 글자가 있어야 한다");
let all = opened.search(&needle, &SearchOptions::new());
let total = all.total_match_count;
let first = opened.search(&needle, &SearchOptions::new().with_limit(2));
assert_eq!(first.match_count, 2);
assert_eq!(
first.total_match_count, total,
"총량은 창과 무관하게 고정이다"
);
assert!(first.truncated);
assert_eq!(first.omitted_count, total - 2);
assert_eq!(first.next_offset, Some(2));
let second = opened.search(&needle, &SearchOptions::new().with_limit(2).with_offset(2));
assert_eq!(second.total_match_count, total);
assert_eq!(second.offset, 2);
assert_ne!(
first.matches[0].char_offset.to_string() + &first.matches[0].paragraph.to_string(),
second.matches[0].char_offset.to_string() + &second.matches[0].paragraph.to_string(),
);
let past_end = opened.search(&needle, &SearchOptions::new().with_offset(total));
assert_eq!(past_end.match_count, 0);
assert_eq!(past_end.total_match_count, total);
assert_eq!(past_end.next_offset, None);
}
#[test]
fn error_codes_and_severity_are_stable() {
let cases: [(ServiceError, &str, bool, bool); 7] = [
(
ServiceError::NotFound {
path: PathBuf::from("x"),
},
"NOT_FOUND",
true,
false,
),
(
ServiceError::Io {
path: PathBuf::from("x"),
kind: std::io::ErrorKind::PermissionDenied,
},
"IO",
false,
false,
),
(
ServiceError::UnsupportedFormat {
detected: FileFormat::DrmProtected,
},
"UNSUPPORTED_FORMAT",
true,
false,
),
(
ServiceError::PasswordRequired,
"PASSWORD_REQUIRED",
true,
true,
),
(
ServiceError::PasswordMismatch,
"PASSWORD_MISMATCH",
false,
true,
),
(
ServiceError::TooLarge {
size_bytes: 2,
limit_bytes: 1,
},
"TOO_LARGE",
true,
false,
),
(ServiceError::Parse("깨짐".into()), "PARSE", false, false),
];
for (error, code, usage, needs_password) in cases {
assert_eq!(error.code(), code);
assert_eq!(error.is_usage_error(), usage, "{code}");
assert_eq!(error.needs_password(), needs_password, "{code}");
assert!(
!error.to_string().is_empty(),
"{code} 는 사람용 문장도 준다"
);
}
}
#[test]
fn open_failure_classification_derives_needles_from_types() {
use crate::parser::crypto::CryptoError;
use crate::parser::ParseError;
use crate::HwpError;
let encrypted = HwpError::from(ParseError::EncryptedDocument);
assert_eq!(
ServiceError::from_open_failure(&encrypted, false),
ServiceError::PasswordRequired
);
assert_eq!(
ServiceError::from_open_failure(&encrypted, true),
ServiceError::PasswordMismatch
);
let wrong = HwpError::from(ParseError::CryptoError(CryptoError::WrongPassword));
assert_eq!(
ServiceError::from_open_failure(&wrong, true),
ServiceError::PasswordMismatch
);
let other = HwpError::InvalidFile("레코드 손상".into());
assert_eq!(
ServiceError::from_open_failure(&other, false),
ServiceError::Parse("레코드 손상".into())
);
}
#[test]
fn service_is_deterministic_and_read_only() {
let bytes = std::fs::read(hwpx_sample()).expect("HWPX 샘플 읽기");
let service = service();
let first = service
.open_bytes(&bytes, &OpenOptions::new())
.expect("첫 열기");
let second = service
.open_bytes(&bytes, &OpenOptions::new())
.expect("둘째 열기");
assert_eq!(first.info(), second.info());
assert_eq!(
first.export_text(&TextExportOptions::new()),
second.export_text(&TextExportOptions::new())
);
assert_eq!(
serde_json::to_value(first.search("가", &SearchOptions::new())).expect("직렬화"),
serde_json::to_value(second.search("가", &SearchOptions::new())).expect("직렬화")
);
assert_eq!(bytes, std::fs::read(hwpx_sample()).expect("재읽기"));
}
}