feat: finishing of M0

This commit is contained in:
2026-04-04 08:10:05 +02:00
parent 897577a369
commit fd744573dd
84 changed files with 143204 additions and 85 deletions

View File

@@ -28,7 +28,7 @@ impl Database {
}
/// Run all pending migrations.
pub fn migrate(&self) -> Result<(), Box<dyn std::error::Error>> {
pub fn migrate(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
migrations::run_migrations(&self.conn)
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +1,35 @@
use deunicode::deunicode;
use std::time::{SystemTime, UNIX_EPOCH};
/// Pre-process German characters to match TypeScript `transliteration` npm output.
/// deunicode maps ä→a, ö→o, ü→u but TypeScript produces ä→ae, ö→oe, ü→ue.
/// We replace these before deunicode so the slug output is compatible.
fn german_transliterate(input: &str) -> String {
let mut result = String::with_capacity(input.len() + 16);
for c in input.chars() {
match c {
'ä' => result.push_str("ae"),
'ö' => result.push_str("oe"),
'ü' => result.push_str("ue"),
'Ä' => result.push_str("Ae"),
'Ö' => result.push_str("Oe"),
'Ü' => result.push_str("Ue"),
_ => result.push(c),
}
}
result
}
/// Generate a URL-safe slug from a title string.
///
/// Transliterates Unicode to ASCII, lowercases, replaces non-alphanumeric
/// chars with hyphens, and collapses/trims hyphens.
///
/// German umlauts (ä/ö/ü/Ä/Ö/Ü) are pre-processed to ae/oe/ue/Ae/Oe/Ue
/// to match TypeScript `transliteration` npm output. ß→ss is handled by deunicode.
pub fn slugify(input: &str) -> String {
let ascii = deunicode(input);
let preprocessed = german_transliterate(input);
let ascii = deunicode(&preprocessed);
let lowered = ascii.to_lowercase();
let mut slug = String::with_capacity(lowered.len());
let mut prev_hyphen = true; // avoid leading hyphen
@@ -61,7 +84,7 @@ mod tests {
#[test]
fn unicode_slug() {
assert_eq!(slugify("Über die Brücke"), "uber-die-brucke");
assert_eq!(slugify("Über die Brücke"), "ueber-die-bruecke");
}
#[test]
@@ -102,6 +125,58 @@ mod tests {
assert_eq!(slug, "hello-4");
}
// German umlaut tests — spec: "only German and English letters are used.
// Verify deunicode handles ä/ö/ü/ß/ÄÖÜ correctly against transliteration npm."
// Pre-processing maps ä→ae, ö→oe, ü→ue to match TypeScript transliteration npm.
// ß→ss is handled correctly by deunicode without pre-processing.
#[test]
fn german_umlaut_ae() {
assert_eq!(slugify("Ärger"), "aerger");
}
#[test]
fn german_umlaut_oe() {
assert_eq!(slugify("Öffnung"), "oeffnung");
}
#[test]
fn german_umlaut_ue() {
assert_eq!(slugify("Über"), "ueber");
}
#[test]
fn german_eszett() {
assert_eq!(slugify("Straße"), "strasse");
}
#[test]
fn german_mixed_umlauts() {
assert_eq!(slugify("Größe über Maße"), "groesse-ueber-masse");
}
#[test]
fn german_uppercase_umlauts() {
assert_eq!(slugify("ÄÖÜ Test"), "aeoeue-test");
}
// spec: CreatePost uses Slug.generate(title ?? "untitled")
// When title is empty/whitespace, slugify should produce "untitled" equivalent
#[test]
fn whitespace_only_input() {
assert_eq!(slugify(" "), "");
}
#[test]
fn leading_trailing_special() {
assert_eq!(slugify("---hello---"), "hello");
}
#[test]
fn numeric_only() {
assert_eq!(slugify("2024"), "2024");
}
#[test]
fn ensure_unique_all_999_taken() {
let slug = ensure_unique("x", |s| {

View File

@@ -0,0 +1,561 @@
//! Integration tests that open the real fixture DB extracted from the TypeScript bDS app
//! and verify every table can be read correctly into Rust model structs.
//!
//! This validates the compatibility contract: the Rust app MUST read databases
//! created by the TypeScript app without modification.
use rusqlite::{Connection, OpenFlags};
use std::path::PathBuf;
fn fixture_db() -> Connection {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../fixtures/compatibility-projects/rfc1437-sample/bds.db");
assert!(path.exists(), "fixture DB not found at {}", path.display());
Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap()
}
const PROJECT_ID: &str = "1979237c-034d-41f6-99a0-f35eb57b3f6c";
// ── Project ─────────────────────────────────────────────────────────
#[test]
fn read_project() {
let conn = fixture_db();
let (id, name, slug, data_path, is_active): (String, String, String, String, bool) = conn
.query_row(
"SELECT id, name, slug, data_path, is_active FROM projects WHERE id = ?1",
[PROJECT_ID],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?, row.get(4)?)),
)
.unwrap();
assert_eq!(id, PROJECT_ID);
assert_eq!(name, "rfc1437");
assert_eq!(slug, "rfc1437");
assert!(data_path.contains("rfc1437.de"));
assert!(is_active);
}
// ── Posts ────────────────────────────────────────────────────────────
#[test]
fn read_published_post_has_null_content() {
let conn = fixture_db();
let (title, slug, status, content): (String, String, String, Option<String>) = conn
.query_row(
"SELECT title, slug, status, content FROM posts WHERE slug = 'esmeralda'",
[],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
)
.unwrap();
assert_eq!(title, "Esmeralda");
assert_eq!(slug, "esmeralda");
assert_eq!(status, "published");
assert!(content.is_none(), "published posts must have NULL content in DB");
}
#[test]
fn read_draft_post_has_content() {
let conn = fixture_db();
let (title, slug, status, content): (String, String, String, Option<String>) = conn
.query_row(
"SELECT title, slug, status, content FROM posts WHERE slug = 'draft-fixture-post'",
[],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)),
)
.unwrap();
assert_eq!(title, "Draft Fixture Post");
assert_eq!(slug, "draft-fixture-post");
assert_eq!(status, "draft");
assert!(content.is_some(), "draft posts must have content in DB");
assert!(content.unwrap().contains("**body**"));
}
#[test]
fn read_all_posts_count() {
let conn = fixture_db();
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM posts", [], |row| row.get(0))
.unwrap();
assert_eq!(count, 4); // 3 published + 1 draft
}
#[test]
fn published_posts_have_file_paths() {
let conn = fixture_db();
let mut stmt = conn
.prepare("SELECT slug, file_path FROM posts WHERE status = 'published'")
.unwrap();
let rows: Vec<(String, String)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert_eq!(rows.len(), 3);
for (slug, path) in &rows {
assert!(!path.is_empty(), "published post '{slug}' must have a file_path");
assert!(path.ends_with(&format!("{slug}.md")), "file_path must end with {slug}.md");
}
}
#[test]
fn post_tags_are_json_arrays() {
let conn = fixture_db();
let tags_json: Option<String> = conn
.query_row(
"SELECT tags FROM posts WHERE slug = 'esmeralda'",
[],
|row| row.get(0),
)
.unwrap();
if let Some(json) = tags_json {
let parsed: Vec<String> = serde_json::from_str(&json).unwrap();
assert!(!parsed.is_empty());
}
// tags can also be NULL — both are valid
}
#[test]
fn post_timestamps_are_unix_integers() {
let conn = fixture_db();
let (created_at, updated_at): (i64, i64) = conn
.query_row(
"SELECT created_at, updated_at FROM posts WHERE slug = 'esmeralda'",
[],
|row| Ok((row.get(0)?, row.get(1)?)),
)
.unwrap();
// Sanity: timestamps should be in reasonable Unix range (year 2000+)
assert!(created_at > 946_684_800, "created_at should be after year 2000");
assert!(updated_at > 946_684_800, "updated_at should be after year 2000");
}
#[test]
fn post_unique_constraint_on_project_slug() {
let conn = fixture_db();
let mut stmt = conn
.prepare("SELECT project_id, slug, COUNT(*) FROM posts GROUP BY project_id, slug HAVING COUNT(*) > 1")
.unwrap();
let dupes: Vec<(String, String, i64)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(dupes.is_empty(), "found duplicate (project_id, slug) pairs: {dupes:?}");
}
// ── Post Translations ───────────────────────────────────────────────
#[test]
fn read_post_translations() {
let conn = fixture_db();
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM post_translations", [], |row| row.get(0))
.unwrap();
assert_eq!(count, 4);
}
#[test]
fn translation_references_valid_post() {
let conn = fixture_db();
let mut stmt = conn
.prepare(
"SELECT pt.id, pt.translation_for FROM post_translations pt \
LEFT JOIN posts p ON pt.translation_for = p.id \
WHERE p.id IS NULL",
)
.unwrap();
let orphans: Vec<(String, String)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(orphans.is_empty(), "orphan translations referencing missing posts: {orphans:?}");
}
#[test]
fn published_translations_have_null_content() {
let conn = fixture_db();
let mut stmt = conn
.prepare("SELECT id, content FROM post_translations WHERE status = 'published'")
.unwrap();
let rows: Vec<(String, Option<String>)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
for (id, content) in &rows {
assert!(content.is_none(), "published translation {id} must have NULL content");
}
}
// ── Post Links ──────────────────────────────────────────────────────
#[test]
fn read_post_links() {
let conn = fixture_db();
let (source, target, text): (String, String, Option<String>) = conn
.query_row(
"SELECT source_post_id, target_post_id, link_text FROM post_links LIMIT 1",
[],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.unwrap();
// ghostty links to cmux
assert_eq!(source, "6745981d-da41-4cfd-80ec-95ad339acf6f");
assert_eq!(target, "2665bfaa-8251-468d-a710-a4cf34dd81e2");
assert!(text.is_some());
}
// ── Post Media ──────────────────────────────────────────────────────
#[test]
fn read_post_media() {
let conn = fixture_db();
let (post_id, media_id, sort_order): (String, String, i32) = conn
.query_row(
"SELECT post_id, media_id, sort_order FROM post_media LIMIT 1",
[],
|row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
)
.unwrap();
// esmeralda <-> spider photo
assert_eq!(post_id, "40a83ab1-423d-4310-aac4-642d84675007");
assert_eq!(media_id, "eb0cf9d7-6fbd-4b74-9be3-759d6e16f240");
assert_eq!(sort_order, 0);
}
// ── Media ───────────────────────────────────────────────────────────
#[test]
fn read_media() {
let conn = fixture_db();
let (id, filename, original_name, mime_type, title, alt): (
String,
String,
String,
String,
Option<String>,
Option<String>,
) = conn
.query_row(
"SELECT id, filename, original_name, mime_type, title, alt FROM media LIMIT 1",
[],
|row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
row.get(5)?,
))
},
)
.unwrap();
assert_eq!(id, "eb0cf9d7-6fbd-4b74-9be3-759d6e16f240");
assert!(filename.ends_with(".jpg"));
assert_eq!(original_name, "CRW_1121.jpg");
assert_eq!(mime_type, "image/jpeg");
assert!(title.is_some());
assert!(alt.is_some());
}
// ── Tags ────────────────────────────────────────────────────────────
#[test]
fn read_tags() {
let conn = fixture_db();
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM tags", [], |row| row.get(0))
.unwrap();
assert_eq!(count, 5);
}
#[test]
fn tag_names_are_expected() {
let conn = fixture_db();
let mut stmt = conn.prepare("SELECT name FROM tags ORDER BY name").unwrap();
let names: Vec<String> = stmt
.query_map([], |row| row.get(0))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert_eq!(names, vec!["fotografie", "mac-os-x", "natur", "programmierung", "sysadmin"]);
}
#[test]
fn tag_unique_constraint_on_project_name() {
let conn = fixture_db();
let mut stmt = conn
.prepare("SELECT project_id, name, COUNT(*) FROM tags GROUP BY project_id, name HAVING COUNT(*) > 1")
.unwrap();
let dupes: Vec<(String, String, i64)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(dupes.is_empty(), "found duplicate (project_id, name) tag pairs: {dupes:?}");
}
// ── Templates ───────────────────────────────────────────────────────
#[test]
fn read_template() {
let conn = fixture_db();
let (slug, title, kind, enabled, status, content): (
String,
String,
String,
bool,
String,
Option<String>,
) = conn
.query_row(
"SELECT slug, title, kind, enabled, status, content FROM templates LIMIT 1",
[],
|row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
row.get(5)?,
))
},
)
.unwrap();
assert_eq!(slug, "testvorlage");
assert_eq!(title, "Testvorlage");
assert_eq!(kind, "post");
assert!(enabled);
assert_eq!(status, "published");
assert!(content.is_none(), "published template content should be NULL in DB");
}
// ── Scripts ─────────────────────────────────────────────────────────
#[test]
fn read_scripts() {
let conn = fixture_db();
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM scripts", [], |row| row.get(0))
.unwrap();
assert_eq!(count, 2);
}
#[test]
fn read_script_fields() {
let conn = fixture_db();
let (slug, title, kind, entrypoint, enabled, status): (
String,
String,
String,
String,
bool,
String,
) = conn
.query_row(
"SELECT slug, title, kind, entrypoint, enabled, status FROM scripts WHERE slug = 'bgg_link'",
[],
|row| {
Ok((
row.get(0)?,
row.get(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
row.get(5)?,
))
},
)
.unwrap();
assert_eq!(slug, "bgg_link");
assert_eq!(title, "bgg link");
assert_eq!(kind, "transform");
assert_eq!(entrypoint, "normalize_blogmark");
assert!(enabled);
assert_eq!(status, "published");
}
// ── Settings ────────────────────────────────────────────────────────
#[test]
fn read_settings() {
let conn = fixture_db();
let count: i64 = conn
.query_row("SELECT COUNT(*) FROM settings", [], |row| row.get(0))
.unwrap();
assert_eq!(count, 5);
}
#[test]
fn settings_are_key_value_pairs() {
let conn = fixture_db();
let mut stmt = conn.prepare("SELECT key, value FROM settings").unwrap();
let pairs: Vec<(String, String)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
for (key, value) in &pairs {
assert!(!key.is_empty());
assert!(!value.is_empty());
}
// All setting keys should contain the project ID (namespaced)
let project_keys: Vec<_> = pairs.iter().filter(|(k, _)| k.contains(PROJECT_ID)).collect();
assert_eq!(project_keys.len(), 5);
}
// ── AI Catalog ──────────────────────────────────────────────────────
#[test]
fn read_ai_tables() {
let conn = fixture_db();
let providers: i64 = conn
.query_row("SELECT COUNT(*) FROM ai_providers", [], |row| row.get(0))
.unwrap();
let models: i64 = conn
.query_row("SELECT COUNT(*) FROM ai_models", [], |row| row.get(0))
.unwrap();
let meta: i64 = conn
.query_row("SELECT COUNT(*) FROM ai_catalog_meta", [], |row| row.get(0))
.unwrap();
assert_eq!(providers, 1);
assert_eq!(models, 1);
assert_eq!(meta, 2);
}
// ── Generated File Hashes ───────────────────────────────────────────
#[test]
fn read_generated_file_hashes_via_settings() {
// The fixture stores generation hashes as settings keys
let conn = fixture_db();
let count: i64 = conn
.query_row(
"SELECT COUNT(*) FROM settings WHERE key LIKE '%generation-hash%'",
[],
|row| row.get(0),
)
.unwrap();
assert!(count > 0, "expected generation hash entries in settings");
}
// ── Cross-table referential integrity ───────────────────────────────
#[test]
fn all_posts_belong_to_existing_project() {
let conn = fixture_db();
let mut stmt = conn
.prepare(
"SELECT p.id FROM posts p \
LEFT JOIN projects pr ON p.project_id = pr.id \
WHERE pr.id IS NULL",
)
.unwrap();
let orphans: Vec<String> = stmt
.query_map([], |row| row.get(0))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(orphans.is_empty(), "posts referencing missing projects: {orphans:?}");
}
#[test]
fn all_tags_belong_to_existing_project() {
let conn = fixture_db();
let mut stmt = conn
.prepare(
"SELECT t.id FROM tags t \
LEFT JOIN projects pr ON t.project_id = pr.id \
WHERE pr.id IS NULL",
)
.unwrap();
let orphans: Vec<String> = stmt
.query_map([], |row| row.get(0))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(orphans.is_empty(), "tags referencing missing projects: {orphans:?}");
}
#[test]
fn all_media_belong_to_existing_project() {
let conn = fixture_db();
let mut stmt = conn
.prepare(
"SELECT m.id FROM media m \
LEFT JOIN projects pr ON m.project_id = pr.id \
WHERE pr.id IS NULL",
)
.unwrap();
let orphans: Vec<String> = stmt
.query_map([], |row| row.get(0))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(orphans.is_empty(), "media referencing missing projects: {orphans:?}");
}
#[test]
fn post_links_reference_valid_posts() {
let conn = fixture_db();
let mut stmt = conn
.prepare(
"SELECT pl.id, pl.source_post_id, pl.target_post_id FROM post_links pl \
LEFT JOIN posts s ON pl.source_post_id = s.id \
LEFT JOIN posts t ON pl.target_post_id = t.id \
WHERE s.id IS NULL OR t.id IS NULL",
)
.unwrap();
let orphans: Vec<(String, String, String)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(orphans.is_empty(), "post_links with invalid references: {orphans:?}");
}
#[test]
fn post_media_references_valid_entities() {
let conn = fixture_db();
let mut stmt = conn
.prepare(
"SELECT pm.id FROM post_media pm \
LEFT JOIN posts p ON pm.post_id = p.id \
LEFT JOIN media m ON pm.media_id = m.id \
WHERE p.id IS NULL OR m.id IS NULL",
)
.unwrap();
let orphans: Vec<String> = stmt
.query_map([], |row| row.get(0))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(orphans.is_empty(), "post_media with invalid references: {orphans:?}");
}

View File

@@ -0,0 +1,505 @@
//! Tests that verify allium spec claims against the Rust model and DB code.
//!
//! Each test is annotated with the spec invariant or rule it validates.
use rusqlite::{Connection, OpenFlags};
use std::path::PathBuf;
fn fixture_db() -> Connection {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../fixtures/compatibility-projects/rfc1437-sample/bds.db");
Connection::open_with_flags(&path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap()
}
fn memory_db() -> Connection {
let conn = Connection::open_in_memory().unwrap();
conn.execute_batch("PRAGMA foreign_keys=ON;").unwrap();
bds_core::db::run_migrations(&conn).unwrap();
conn
}
// ── spec: post.allium — PostStatus serde matches DB string values ────
#[test]
fn post_status_serde_matches_db_values() {
// spec: status: draft | published | archived
use bds_core::model::PostStatus;
assert_eq!(serde_json::to_string(&PostStatus::Draft).unwrap(), "\"draft\"");
assert_eq!(serde_json::to_string(&PostStatus::Published).unwrap(), "\"published\"");
assert_eq!(serde_json::to_string(&PostStatus::Archived).unwrap(), "\"archived\"");
// round-trip
let d: PostStatus = serde_json::from_str("\"draft\"").unwrap();
assert_eq!(d, PostStatus::Draft);
let p: PostStatus = serde_json::from_str("\"published\"").unwrap();
assert_eq!(p, PostStatus::Published);
let a: PostStatus = serde_json::from_str("\"archived\"").unwrap();
assert_eq!(a, PostStatus::Archived);
}
// ── spec: schema.allium — Template kind: post | list | not_found | partial ──
#[test]
fn template_kind_serde_matches_db_values() {
use bds_core::model::TemplateKind;
assert_eq!(serde_json::to_string(&TemplateKind::Post).unwrap(), "\"post\"");
assert_eq!(serde_json::to_string(&TemplateKind::List).unwrap(), "\"list\"");
assert_eq!(serde_json::to_string(&TemplateKind::NotFound).unwrap(), "\"not_found\"");
assert_eq!(serde_json::to_string(&TemplateKind::Partial).unwrap(), "\"partial\"");
let nf: TemplateKind = serde_json::from_str("\"not_found\"").unwrap();
assert_eq!(nf, TemplateKind::NotFound);
}
// ── spec: schema.allium — Template status: draft | published ──
#[test]
fn template_status_serde_matches_db_values() {
use bds_core::model::TemplateStatus;
assert_eq!(serde_json::to_string(&TemplateStatus::Draft).unwrap(), "\"draft\"");
assert_eq!(serde_json::to_string(&TemplateStatus::Published).unwrap(), "\"published\"");
}
// ── spec: schema.allium — Script kind: macro | utility | transform ──
#[test]
fn script_kind_serde_matches_db_values() {
use bds_core::model::ScriptKind;
assert_eq!(serde_json::to_string(&ScriptKind::Macro).unwrap(), "\"macro\"");
assert_eq!(serde_json::to_string(&ScriptKind::Utility).unwrap(), "\"utility\"");
assert_eq!(serde_json::to_string(&ScriptKind::Transform).unwrap(), "\"transform\"");
let t: ScriptKind = serde_json::from_str("\"transform\"").unwrap();
assert_eq!(t, ScriptKind::Transform);
}
// ── spec: schema.allium — Script status: draft | published ──
#[test]
fn script_status_serde_matches_db_values() {
use bds_core::model::ScriptStatus;
assert_eq!(serde_json::to_string(&ScriptStatus::Draft).unwrap(), "\"draft\"");
assert_eq!(serde_json::to_string(&ScriptStatus::Published).unwrap(), "\"published\"");
}
// ── spec: post.allium — content_location invariant ──
// "if status = published: file_path else: content"
// Published posts have NULL content in DB; draft posts have content in DB.
#[test]
fn content_location_published_posts_null_content_in_fixture() {
let conn = fixture_db();
let mut stmt = conn
.prepare("SELECT slug, content FROM posts WHERE status = 'published'")
.unwrap();
let rows: Vec<(String, Option<String>)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(!rows.is_empty());
for (slug, content) in &rows {
assert!(content.is_none(), "spec: published post '{slug}' must have NULL content in DB");
}
}
#[test]
fn content_location_draft_posts_have_content_in_fixture() {
let conn = fixture_db();
let mut stmt = conn
.prepare("SELECT slug, content FROM posts WHERE status = 'draft'")
.unwrap();
let rows: Vec<(String, Option<String>)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(!rows.is_empty());
for (slug, content) in &rows {
assert!(content.is_some(), "spec: draft post '{slug}' must have content in DB");
}
}
// ── spec: post.allium — all status transitions allowed ──
// draft -> published, draft -> archived, published -> draft,
// published -> archived, archived -> draft, archived -> published
#[test]
fn post_status_transitions_all_valid() {
let conn = memory_db();
conn.execute(
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
[],
).unwrap();
conn.execute(
"INSERT INTO posts (id, project_id, title, slug, status, file_path, created_at, updated_at) \
VALUES ('post1', 'p1', 'Test', 'test', 'draft', '', 1000, 1000)",
[],
).unwrap();
let transitions = [
("draft", "published"),
("published", "draft"),
("draft", "archived"),
("archived", "draft"),
("draft", "published"),
("published", "archived"),
("archived", "published"),
];
for (from, to) in transitions {
// Set to 'from' state first
conn.execute("UPDATE posts SET status = ?1 WHERE id = 'post1'", [from]).unwrap();
// Transition to 'to' state
conn.execute("UPDATE posts SET status = ?1 WHERE id = 'post1'", [to]).unwrap();
let status: String = conn
.query_row("SELECT status FROM posts WHERE id = 'post1'", [], |r| r.get(0))
.unwrap();
assert_eq!(status, to, "transition {from} -> {to} failed");
}
}
// ── spec: post.allium — is_slug_frozen: published_at != null ──
// Slug changes only allowed before first publish
#[test]
fn slug_frozen_after_publish_semantics() {
let conn = memory_db();
conn.execute(
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
[],
).unwrap();
conn.execute(
"INSERT INTO posts (id, project_id, title, slug, status, file_path, created_at, updated_at, published_at) \
VALUES ('post1', 'p1', 'Test', 'test', 'published', 'posts/2024/01/test.md', 1000, 1000, 1000)",
[],
).unwrap();
// published_at is set — slug should be considered frozen
let published_at: Option<i64> = conn
.query_row("SELECT published_at FROM posts WHERE id = 'post1'", [], |r| r.get(0))
.unwrap();
assert!(published_at.is_some(), "spec: is_slug_frozen = published_at != null");
// A never-published draft has no published_at — slug is mutable
conn.execute(
"INSERT INTO posts (id, project_id, title, slug, status, file_path, created_at, updated_at) \
VALUES ('post2', 'p1', 'Draft', 'draft-post', 'draft', '', 1000, 1000)",
[],
).unwrap();
let draft_published_at: Option<i64> = conn
.query_row("SELECT published_at FROM posts WHERE id = 'post2'", [], |r| r.get(0))
.unwrap();
assert!(draft_published_at.is_none(), "spec: unpublished draft has no published_at");
}
// ── spec: project.allium — SingleActiveProject invariant ──
// "Exactly one project is active at any time"
#[test]
fn single_active_project_in_fixture() {
let conn = fixture_db();
let active_count: i64 = conn
.query_row("SELECT COUNT(*) FROM projects WHERE is_active = 1", [], |r| r.get(0))
.unwrap();
assert_eq!(active_count, 1, "spec: exactly one project is active");
}
// ── spec: project.allium — UniqueProjectSlug invariant ──
#[test]
fn unique_project_slug_in_fixture() {
let conn = fixture_db();
let mut stmt = conn
.prepare("SELECT slug, COUNT(*) FROM projects GROUP BY slug HAVING COUNT(*) > 1")
.unwrap();
let dupes: Vec<(String, i64)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(dupes.is_empty(), "spec: project slug must be unique");
}
// ── spec: translation.allium — UniqueTranslationPerLanguage ──
// "post_translations must have unique (translation_for, language)"
#[test]
fn unique_translation_per_post_language_in_fixture() {
let conn = fixture_db();
let mut stmt = conn
.prepare(
"SELECT translation_for, language, COUNT(*) FROM post_translations \
GROUP BY translation_for, language HAVING COUNT(*) > 1",
)
.unwrap();
let dupes: Vec<(String, String, i64)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
assert!(dupes.is_empty(), "spec: translation unique per (post, language)");
}
// ── spec: schema.allium — Post defaults ──
// status default 'draft', do_not_translate default false, file_path default ''
#[test]
fn post_defaults_match_spec() {
let conn = memory_db();
conn.execute(
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
[],
).unwrap();
// Insert with minimal columns to test defaults
conn.execute(
"INSERT INTO posts (id, project_id, title, slug, created_at, updated_at) \
VALUES ('min1', 'p1', 'Minimal', 'minimal', 1000, 1000)",
[],
).unwrap();
let (status, do_not_translate, file_path): (String, bool, String) = conn
.query_row(
"SELECT status, do_not_translate, file_path FROM posts WHERE id = 'min1'",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?)),
)
.unwrap();
assert_eq!(status, "draft", "spec: default status is draft");
assert!(!do_not_translate, "spec: default do_not_translate is false");
assert_eq!(file_path, "", "spec: default file_path is empty string");
}
// ── spec: schema.allium — Script defaults ──
// kind default 'utility', entrypoint default 'render', enabled default true,
// version default 1, status default 'published'
#[test]
fn script_defaults_match_spec() {
let conn = memory_db();
conn.execute(
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
[],
).unwrap();
conn.execute(
"INSERT INTO scripts (id, project_id, slug, title, file_path, created_at, updated_at) \
VALUES ('s1', 'p1', 'test', 'Test', 'scripts/test.lua', 1000, 1000)",
[],
).unwrap();
let (kind, entrypoint, enabled, version, status): (String, String, bool, i32, String) = conn
.query_row(
"SELECT kind, entrypoint, enabled, version, status FROM scripts WHERE id = 's1'",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?, r.get(4)?)),
)
.unwrap();
assert_eq!(kind, "utility", "spec: default kind is utility");
assert_eq!(entrypoint, "render", "spec: default entrypoint is 'render'");
assert!(enabled, "spec: default enabled is true");
assert_eq!(version, 1, "spec: default version is 1");
assert_eq!(status, "published", "spec: default status is published");
}
// ── spec: schema.allium — Template defaults ──
// kind default 'post', enabled default true, version default 1, status default 'published'
#[test]
fn template_defaults_match_spec() {
let conn = memory_db();
conn.execute(
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
[],
).unwrap();
conn.execute(
"INSERT INTO templates (id, project_id, slug, title, file_path, created_at, updated_at) \
VALUES ('t1', 'p1', 'test', 'Test', 'templates/test.liquid', 1000, 1000)",
[],
).unwrap();
let (kind, enabled, version, status): (String, bool, i32, String) = conn
.query_row(
"SELECT kind, enabled, version, status FROM templates WHERE id = 't1'",
[],
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)
.unwrap();
assert_eq!(kind, "post", "spec: default kind is post");
assert!(enabled, "spec: default enabled is true");
assert_eq!(version, 1, "spec: default version is 1");
assert_eq!(status, "published", "spec: default status is published");
}
// ── spec: tag.allium — UniqueTagNamePerProject (case-insensitive) ──
#[test]
fn tag_unique_name_per_project_enforced() {
let conn = memory_db();
conn.execute(
"INSERT INTO projects (id, name, slug, created_at, updated_at, is_active) \
VALUES ('p1', 'test', 'test', 1000, 1000, 1)",
[],
).unwrap();
conn.execute(
"INSERT INTO tags (id, project_id, name, created_at, updated_at) \
VALUES ('t1', 'p1', 'rust', 1000, 1000)",
[],
).unwrap();
// Same name, same project — must fail
let result = conn.execute(
"INSERT INTO tags (id, project_id, name, created_at, updated_at) \
VALUES ('t2', 'p1', 'rust', 1000, 1000)",
[],
);
assert!(result.is_err(), "spec: duplicate tag name in same project must fail");
}
// ── spec: post.allium — Slug generation algorithm ──
// "transliterate unicode to ASCII, lowercase, replace [^a-z0-9]+ with hyphens,
// strip leading/trailing hyphens"
#[test]
fn slug_generation_matches_spec_algorithm() {
use bds_core::util::slugify;
// Basic: lowercase + hyphen separation
assert_eq!(slugify("Hello World"), "hello-world");
// Non-alphanumeric replaced with single hyphen
assert_eq!(slugify("a --- b"), "a-b");
// Leading/trailing hyphens stripped
assert_eq!(slugify("---hello---"), "hello");
// Unicode transliteration
assert_eq!(slugify("café"), "cafe");
// German umlauts (spec: "only German and English letters used")
assert_eq!(slugify("über"), "ueber");
assert_eq!(slugify("Ärger"), "aerger");
assert_eq!(slugify("Öffnung"), "oeffnung");
assert_eq!(slugify("Straße"), "strasse");
}
// ── spec: post.allium — Slug uniqueness algorithm ──
// "tries base, then {slug}-2 .. {slug}-999, then {slug}-{timestamp}"
#[test]
fn slug_uniqueness_matches_spec() {
use bds_core::util::ensure_unique;
// Base available
assert_eq!(ensure_unique("test", |_| false), "test");
// Base taken → -2
assert_eq!(ensure_unique("test", |s| s == "test"), "test-2");
// -2 and -3 taken → -4
assert_eq!(
ensure_unique("test", |s| s == "test" || s == "test-2" || s == "test-3"),
"test-4"
);
}
// ── spec: frontmatter.allium — PostFileLayout ──
// "posts/{YYYY}/{MM}/{slug}.md"
#[test]
fn published_post_file_paths_follow_date_layout() {
let conn = fixture_db();
let mut stmt = conn
.prepare("SELECT slug, file_path, created_at FROM posts WHERE status = 'published' AND file_path != ''")
.unwrap();
let rows: Vec<(String, String, i64)> = stmt
.query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
.unwrap()
.map(|r| r.unwrap())
.collect();
for (slug, path, _created_at) in &rows {
// Path should end with {slug}.md
assert!(
path.ends_with(&format!("{slug}.md")),
"spec: file_path must end with {{slug}}.md, got: {path}"
);
// Path should contain posts/YYYY/MM/ pattern
assert!(
path.contains("/posts/"),
"spec: file_path must contain /posts/, got: {path}"
);
}
}
// ── spec: cli_sync.allium — DbNotification entity_type values ──
#[test]
fn notification_entity_serde_matches_db_values() {
use bds_core::model::{NotificationEntity, NotificationAction};
assert_eq!(serde_json::to_string(&NotificationEntity::Post).unwrap(), "\"post\"");
assert_eq!(serde_json::to_string(&NotificationEntity::Media).unwrap(), "\"media\"");
assert_eq!(serde_json::to_string(&NotificationEntity::Script).unwrap(), "\"script\"");
assert_eq!(serde_json::to_string(&NotificationEntity::Template).unwrap(), "\"template\"");
assert_eq!(serde_json::to_string(&NotificationAction::Created).unwrap(), "\"created\"");
assert_eq!(serde_json::to_string(&NotificationAction::Updated).unwrap(), "\"updated\"");
assert_eq!(serde_json::to_string(&NotificationAction::Deleted).unwrap(), "\"deleted\"");
}
// ── spec: generation.allium / publishing.allium — SshMode values ──
#[test]
fn ssh_mode_serde_matches_spec() {
use bds_core::model::SshMode;
assert_eq!(serde_json::to_string(&SshMode::Scp).unwrap(), "\"scp\"");
assert_eq!(serde_json::to_string(&SshMode::Rsync).unwrap(), "\"rsync\"");
}
// ── spec: i18n.allium — SplitLocalization ──
// Verify that the 5 supported UI languages exist as config
#[test]
fn supported_languages_match_spec() {
// spec: en, de, fr, it, es — the 5 supported UI languages
let supported = ["en", "de", "fr", "it", "es"];
assert_eq!(supported.len(), 5);
// This test documents the spec constraint; actual locale loading
// will be tested when i18n module is implemented in M2+
}
// ── spec: schema.allium — FTS5 virtual tables exist in fixture ──
#[test]
fn fts5_tables_exist_in_fixture() {
let conn = fixture_db();
// posts_fts
let result = conn.query_row(
"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='posts_fts'",
[],
|r| r.get::<_, i64>(0),
);
assert_eq!(result.unwrap(), 1, "spec: posts_fts virtual table must exist");
// media_fts
let result = conn.query_row(
"SELECT count(*) FROM sqlite_master WHERE type='table' AND name='media_fts'",
[],
|r| r.get::<_, i64>(0),
);
assert_eq!(result.unwrap(), 1, "spec: media_fts virtual table must exist");
}