puerto 0.34.0

Puerto: la CLI de un framework full-stack DDD en Rust. Genera proyectos con Clean Architecture, la inyección de dependencias cableada sola y soporte de SQLx, sin cablear nada a mano. Antes, puerto-framework.
use super::*;
use compile_matrix::{
    AUTH_LOCAL, AUTH_OIDC, AUTH_OIDC_DB, AUTH_OIDC_EVENTS, CUSTOM_USE_CASE, ENUM_ONLY, ENUM_VO,
    EVENTS_DB, EVENTS_KAFKA, EVENTS_MAIL, EVENTS_MAIL_KAFKA, FILES, FILES_AUTH, FILES_EVENTS_DB,
    FILES_OWNER_DB, MAIL, MULTI_ENTITY, NO_DEMO, NO_WEB, NOTIFICATION, OPT_VEC_PRIM, OPT_VEC_VO,
    PLAIN_VO, POSTGRES_EVERY_TYPE, PRIMITIVES, REFERENCES, REFERENCES_AUTH, REFERENCES_AUTH_DB,
    REFERENCES_DB, REFERENCES_EVENTS, SCHEDULED_DB, SCHEDULED_KAFKA, SHARED_VO, Scenario, UUID_VO,
    VO_KITCHEN_SINK, WEB_BLOCKS, WEB_BLOCKS_LOCAL, WEB_BLOCKS_PLAIN, WEB_CRUD, WEB_EVERY_TYPE,
    apply_scenario,
};
use std::collections::BTreeMap;

// ── T-18: snapshots of the generated output ───────────────────────────────
//
// The compile matrix proves the generated code builds; it cannot see a change that still builds.
// These snapshots lock the exact output of every matrix scenario: each one is every file the
// generators create, rewrite or delete relative to the raw template — the template's static files
// are not Puerto's generation logic and would only bury the signal.
//
// After an intended change to generated output: `INSTA_UPDATE=always make test`, then read the
// `.snap` diff in full before committing — it is exactly what lands in users' projects.

pub(super) fn project_tree(root: &Path) -> BTreeMap<String, String> {
    fn walk(root: &Path, dir: &Path, out: &mut BTreeMap<String, String>) {
        let mut entries: Vec<_> = fs::read_dir(dir).unwrap().map(|e| e.unwrap()).collect();
        entries.sort_by_key(|e| e.file_name());
        for entry in entries {
            let path = entry.path();
            if path.is_dir() {
                walk(root, &path, out);
            } else {
                let rel = path
                    .strip_prefix(root)
                    .unwrap()
                    .to_string_lossy()
                    .into_owned();
                let content = String::from_utf8_lossy(&fs::read(&path).unwrap()).into_owned();
                out.insert(rel, content);
            }
        }
    }
    let mut out = BTreeMap::new();
    walk(root, root, &mut out);
    out
}

/// Migration versions are timestamps; everything else Puerto writes is deterministic.
fn normalize_path(path: &str) -> String {
    match path.rsplit_once('/') {
        Some((dir, file)) if dir.ends_with("migraciones") => match file.split_once('_') {
            Some((version, rest)) if version.chars().all(|c| c.is_ascii_digit()) => {
                format!("{dir}/<version>_{rest}")
            }
            _ => path.to_string(),
        },
        _ => path.to_string(),
    }
}

/// Everything the scenario changed in a freshly generated project, as one reviewable document.
fn generated_output(scenario: &Scenario) -> String {
    let dir = temp_dir(&format!("snapshot_{}", scenario.name));
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();
    let output = generate_project("snapshot", &dir).unwrap();

    let before = project_tree(&output);
    apply_scenario(scenario, &output);
    let after = project_tree(&output);
    cleanup(&dir);

    let mut sections = BTreeMap::new();
    for (path, content) in &after {
        if before.get(path) != Some(content) {
            sections.insert(normalize_path(path), content.clone());
        }
    }
    for path in before.keys().filter(|p| !after.contains_key(*p)) {
        sections.insert(normalize_path(path), "(borrado)\n".to_string());
    }
    sections
        .iter()
        .map(|(path, content)| format!("=== {path} ===\n{content}"))
        .collect::<Vec<_>>()
        .join("\n")
}

macro_rules! snapshot_scenarios {
    ($($test:ident => $scenario:ident),* $(,)?) => {$(
        #[test]
        fn $test() {
            insta::assert_snapshot!($scenario.name, generated_output(&$scenario));
        }
    )*};
}

snapshot_scenarios! {
    snapshot_no_demo => NO_DEMO,
    snapshot_no_web => NO_WEB,
    snapshot_primitives => PRIMITIVES,
    snapshot_uuid_vo => UUID_VO,
    snapshot_opt_vec_prim => OPT_VEC_PRIM,
    snapshot_plain_vo => PLAIN_VO,
    snapshot_opt_vec_vo => OPT_VEC_VO,
    snapshot_enum_vo => ENUM_VO,
    snapshot_shared_vo => SHARED_VO,
    snapshot_multi_entity => MULTI_ENTITY,
    snapshot_references => REFERENCES,
    snapshot_references_db => REFERENCES_DB,
    snapshot_references_events => REFERENCES_EVENTS,
    snapshot_references_auth => REFERENCES_AUTH,
    snapshot_references_auth_db => REFERENCES_AUTH_DB,
    snapshot_vo_kitchen_sink => VO_KITCHEN_SINK,
    snapshot_enum_only => ENUM_ONLY,
    snapshot_custom_use_case => CUSTOM_USE_CASE,
    snapshot_postgres_every_type => POSTGRES_EVERY_TYPE,
    snapshot_events_db => EVENTS_DB,
    snapshot_events_kafka => EVENTS_KAFKA,
    snapshot_web_crud => WEB_CRUD,
    snapshot_web_every_type => WEB_EVERY_TYPE,
    snapshot_mail => MAIL,
    snapshot_events_mail => EVENTS_MAIL,
    snapshot_events_mail_kafka => EVENTS_MAIL_KAFKA,
    snapshot_auth_oidc => AUTH_OIDC,
    snapshot_auth_oidc_db => AUTH_OIDC_DB,
    snapshot_auth_oidc_events => AUTH_OIDC_EVENTS,
    snapshot_auth_local => AUTH_LOCAL,
    snapshot_web_blocks => WEB_BLOCKS,
    snapshot_web_blocks_plain => WEB_BLOCKS_PLAIN,
    snapshot_web_blocks_local => WEB_BLOCKS_LOCAL,
    snapshot_files => FILES,
    snapshot_files_auth => FILES_AUTH,
    snapshot_files_owner_db => FILES_OWNER_DB,
    snapshot_files_events_db => FILES_EVENTS_DB,
    snapshot_scheduled_db => SCHEDULED_DB,
    snapshot_scheduled_kafka => SCHEDULED_KAFKA,
    snapshot_notification => NOTIFICATION,
}

/// ADR-0026: a use case logs through its `#[tracing::instrument]` span, never by hand.
#[test]
fn every_use_case_logs_through_its_span_and_writes_no_start_or_done_line() {
    for scenario in [&PRIMITIVES, &EVENTS_DB, &CUSTOM_USE_CASE, &AUTH_LOCAL] {
        let dir = temp_dir(&format!("use_case_span_{}", scenario.name));
        cleanup(&dir);
        fs::create_dir_all(&dir).unwrap();
        let output = generate_project("snapshot", &dir).unwrap();
        apply_scenario(scenario, &output);
        let tree = project_tree(&output);
        cleanup(&dir);

        for (path, content) in tree.iter().filter(|(p, _)| p.ends_with(".rs")) {
            for line in [
                ": inicio\"",
                ": fin\"",
                ": rechazado\"",
                "fallo del repositorio\"",
            ] {
                assert!(
                    !content.contains(line),
                    "{}: {path} has {line}",
                    scenario.name
                );
            }
            let use_case = path.contains("/aplicacion/src/") && !path.ends_with("/lib.rs");
            if use_case {
                assert!(
                    content.contains("#[tracing::instrument(name = \""),
                    "{}: {path}",
                    scenario.name
                );
            }
        }
    }
}

/// 36.4: the tests of a use case build its `Impl` in one place, so a dependency more is one line.
#[test]
fn every_use_case_test_module_builds_its_impl_once_in_caso_de_uso() {
    for scenario in [
        &PRIMITIVES,
        &EVENTS_DB,
        &CUSTOM_USE_CASE,
        &AUTH_LOCAL,
        &AUTH_OIDC_EVENTS,
    ] {
        let dir = temp_dir(&format!("use_case_impl_{}", scenario.name));
        cleanup(&dir);
        fs::create_dir_all(&dir).unwrap();
        let output = generate_project("snapshot", &dir).unwrap();
        apply_scenario(scenario, &output);
        let tree = project_tree(&output);
        cleanup(&dir);

        let use_cases = tree.iter().filter(|(p, _)| {
            p.contains("/aplicacion/src/") && p.ends_with(".rs") && !p.ends_with("/lib.rs")
        });
        for (path, content) in use_cases {
            let Some(at) = content.find("#[cfg(test)]\nmod tests {") else {
                continue;
            };
            let tests = &content[at..];
            let built = tests
                .lines()
                .filter(|l| l.trim_end().ends_with("Impl {") && !l.contains("-> "))
                .count();
            assert!(
                built <= 1,
                "{}: {path} builds its Impl {built} times",
                scenario.name
            );
            if built == 1 {
                assert!(
                    tests.contains("    fn caso_de_uso("),
                    "{}: {path}",
                    scenario.name
                );
            }
        }
    }
}

#[test]
fn should_hide_only_the_migration_version_from_snapshots() {
    assert_eq!(
        normalize_path("migraciones/20261011093000_crear_tabla_producto.sql"),
        "migraciones/<version>_crear_tabla_producto.sql"
    );
    assert_eq!(
        normalize_path("contextos/producto/dominio/src/modelo.rs"),
        "contextos/producto/dominio/src/modelo.rs"
    );
}