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.
// Fase 42.2: `puerto generar ciclo-cuenta` — the local account cycle (Fase 39) in a `--auth local`
// project from before it.
use super::*;
use crate::commands::new::{NewOptions, new_project};
use crate::generators::auth::run_generate_account_cycle;

const MARKER: &str = "contextos/usuario/aplicacion/src/solicitar_restablecimiento.rs";

fn read(dir: &Path, path: &str) -> String {
    fs::read_to_string(dir.join(path)).unwrap_or_else(|e| panic!("{path}: {e}"))
}

fn project(name: &str, auth: &str) -> (PathBuf, PathBuf) {
    let dir = temp_dir(name);
    cleanup(&dir);
    fs::create_dir_all(&dir).unwrap();
    let output = new_project(
        Some(name.replace('_', "-")),
        NewOptions {
            db: true,
            auth: Some(auth.into()),
            no_portada: true,
            ..Default::default()
        },
        Some(dir.clone()),
    )
    .unwrap();
    (dir, output)
}

/// A local project whose `usuario` context lacks the cycle's first use case: what `generar
/// ciclo-cuenta` looks for.
fn without_the_cycle(name: &str) -> (PathBuf, PathBuf) {
    let (dir, output) = project(name, "local");
    // Formatted, as `puerto nuevo` leaves it.
    crate::generators::format::format_project(&output).unwrap();
    fs::remove_file(output.join(MARKER)).unwrap();
    let lib = output.join("contextos/usuario/aplicacion/src/lib.rs");
    let without = fs::read_to_string(&lib)
        .unwrap()
        .replace("pub mod solicitar_restablecimiento;\n", "");
    fs::write(&lib, without).unwrap();
    // The 0.33 tables: no verified email, no single-use tokens.
    let auth = fs::read_dir(output.join("migraciones"))
        .unwrap()
        .flatten()
        .find(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_crear_tablas_auth.sql")
        })
        .unwrap()
        .path();
    let sql = fs::read_to_string(&auth).unwrap();
    let before = sql[..sql.find("CREATE TABLE tokens").unwrap()]
        .replace("    email_verificado_en TIMESTAMPTZ,\n", "");
    fs::write(&auth, before).unwrap();
    (dir, output)
}

fn migration_named(output: &Path, suffix: &str) -> Option<String> {
    fs::read_dir(output.join("migraciones"))
        .unwrap()
        .flatten()
        .find(|e| e.file_name().to_string_lossy().ends_with(suffix))
        .map(|e| fs::read_to_string(e.path()).unwrap())
}

#[test]
fn should_write_the_account_cycle_into_a_local_project_that_lacks_it() {
    let (dir, output) = without_the_cycle("ciclo_cuenta_alta");

    // Without --forzar: the other files it writes are the ones the project already has.
    run_generate_account_cycle(&output, OverwritePolicy::Ask).unwrap();

    assert!(output.join(MARKER).exists());
    let migration = migration_named(&output, "_ciclo_cuenta.sql").expect("its migration");
    assert!(
        migration.ends_with(include_str!("../templates/auth/local/ciclo_cuenta.sql")),
        "{migration}"
    );
    let bootstrap = read(&output, "presentacion/api/src/generado/bootstrap.rs");
    assert!(
        bootstrap.contains("solicitar_restablecimiento"),
        "{bootstrap}"
    );
    assert_eq!(read(&output, ".env").matches("APP_URL=").count(), 1);
    cleanup(&dir);
}

#[test]
fn should_add_app_url_to_a_project_from_before_the_cycle() {
    let (dir, output) = without_the_cycle("ciclo_cuenta_app_url");
    for file in [".env", ".env.example"] {
        let path = output.join(file);
        let env: String = fs::read_to_string(&path)
            .unwrap()
            .lines()
            .filter(|l| !l.starts_with("APP_URL="))
            .map(|l| format!("{l}\n"))
            .collect();
        fs::write(&path, env).unwrap();
    }

    run_generate_account_cycle(&output, OverwritePolicy::Force).unwrap();

    for file in [".env", ".env.example"] {
        assert_eq!(
            read(&output, file)
                .matches("APP_URL=http://localhost:5173")
                .count(),
            1,
            "{file}"
        );
    }
    cleanup(&dir);
}

#[test]
fn should_refuse_to_overwrite_a_file_of_yours_without_forzar() {
    let (dir, output) = without_the_cycle("ciclo_cuenta_sin_forzar");
    let mine = "contextos/usuario/aplicacion/src/registrar_usuario.rs";
    let edited = format!("{}// mío\n", read(&output, mine));
    fs::write(output.join(mine), &edited).unwrap();

    let error = run_generate_account_cycle(&output, OverwritePolicy::Ask)
        .unwrap_err()
        .to_string();

    assert!(error.contains("--forzar"), "{error}");
    assert!(!output.join(MARKER).exists(), "nothing is written");
    assert_eq!(read(&output, mine), edited);

    run_generate_account_cycle(&output, OverwritePolicy::Force).unwrap();
    assert!(output.join(MARKER).exists());
    assert!(!read(&output, mine).contains("// mío"));
    cleanup(&dir);
}

#[test]
fn should_refuse_the_cycle_in_an_oidc_project_and_in_one_that_has_it() {
    let (dir, oidc) = project("ciclo_cuenta_oidc", "oidc");
    let error = run_generate_account_cycle(&oidc, OverwritePolicy::Force)
        .unwrap_err()
        .to_string();
    assert!(error.contains("--auth local"), "{error}");
    cleanup(&dir);

    let (dir, local) = project("ciclo_cuenta_ya", "local");
    let error = run_generate_account_cycle(&local, OverwritePolicy::Force)
        .unwrap_err()
        .to_string();
    assert!(error.contains("ya tiene el ciclo"), "{error}");
    cleanup(&dir);
}

#[test]
fn should_not_write_the_migration_twice_when_a_migration_already_creates_the_tokens() {
    // The guide's step 1 has a project write `ciclo_cuenta` by hand before the runtime goes up.
    let (dir, output) = without_the_cycle("ciclo_cuenta_paso_1");
    crate::generators::migration::run_migration(
        "ciclo_cuenta",
        &output,
        Some(include_str!("../templates/auth/local/ciclo_cuenta.sql")),
    )
    .unwrap();

    run_generate_account_cycle(&output, OverwritePolicy::Force).unwrap();

    let written = fs::read_dir(output.join("migraciones"))
        .unwrap()
        .flatten()
        .filter(|e| {
            e.file_name()
                .to_string_lossy()
                .ends_with("_ciclo_cuenta.sql")
        })
        .count();
    assert_eq!(written, 1);
    assert!(output.join(MARKER).exists());
    cleanup(&dir);
}