use super::*;
use crate::commands::new::{NewOptions, new_project};
fn read(dir: &Path, path: &str) -> String {
fs::read_to_string(dir.join(path)).unwrap_or_else(|e| panic!("{path}: {e}"))
}
fn project_with_producto(name: &str, options: NewOptions) -> (PathBuf, PathBuf) {
let dir = temp_dir(name);
cleanup(&dir);
fs::create_dir_all(&dir).unwrap();
let output = new_project(
Some(name.replace('_', "-")),
NewOptions {
no_portada: true,
..options
},
Some(dir.clone()),
)
.unwrap();
let fields = vec![puerto_toml::parse_field_arg("nombre:String").unwrap()];
scaffold::run_scaffold("Producto", &output, &fields, OverwritePolicy::Ask).unwrap();
(dir, output)
}
fn events() -> NewOptions {
NewOptions {
db: true,
events: Some("db".into()),
..Default::default()
}
}
const BOOTSTRAP: &str = "presentacion/api/src/generado/bootstrap.rs";
const FUENTE: &str = "web/src/api/en-vivo.ts";
const HOOK: &str = "web/src/compartido/en-vivo.ts";
#[test]
fn should_listen_and_serve_the_live_stream_in_a_project_with_events() {
let (dir, output) = project_with_producto("en_vivo_api", events());
let bootstrap = read(&output, BOOTSTRAP);
assert!(
bootstrap.contains("let en_vivo = puerto_web::en_vivo::canal();"),
"{bootstrap}"
);
assert!(
bootstrap.contains("puerto_sqlx::en_vivo::escuchar(&pool, en_vivo.clone())"),
"{bootstrap}"
);
assert!(
bootstrap.contains("let api_en_vivo = puerto_web::en_vivo::ApiEnVivo::new(en_vivo);"),
"{bootstrap}"
);
assert!(
bootstrap.contains("puerto_web::en_vivo::ApiEnVivo::new(puerto_web::en_vivo::canal())"),
"{bootstrap}"
);
assert_eq!(bootstrap.matches("api_en_vivo").count(), 4, "{bootstrap}");
cleanup(&dir);
}
#[test]
fn should_ask_for_a_session_on_the_live_stream_of_a_project_with_auth() {
let (dir, output) = project_with_producto(
"en_vivo_auth",
NewOptions {
auth: Some("oidc".into()),
..events()
},
);
let bootstrap = read(&output, BOOTSTRAP);
assert!(
bootstrap.contains("puerto_web::en_vivo::ApiEnVivoConSesion::new(en_vivo)"),
"{bootstrap}"
);
assert!(!bootstrap.contains("ApiEnVivo::new"), "{bootstrap}");
cleanup(&dir);
}
#[test]
fn should_reload_the_screens_of_a_project_with_events_when_what_they_show_changes() {
let (dir, output) = project_with_producto("en_vivo_web", events());
let fuente = read(&output, FUENTE);
assert!(fuente.contains("export function fuenteEnVivo("), "{fuente}");
assert!(fuente.contains(r#"api.GET("/en-vivo""#), "{fuente}");
assert!(output.join("web/src/api/en-vivo.test.ts").exists());
let hook = read(&output, HOOK);
assert!(hook.contains("export function useEnVivo("), "{hook}");
assert!(output.join("web/src/compartido/en-vivo.test.tsx").exists());
let dependencias = read(&output, "web/src/generado/dependencias.ts");
assert!(
dependencias.contains("enVivo?: FuenteEnVivo;"),
"{dependencias}"
);
assert!(
dependencias.contains("enVivo: fuenteEnVivo(api)"),
"{dependencias}"
);
let k = "web/src/contextos/producto/contenedores";
let lista = read(&output, &format!("{k}/lista-producto.tsx"));
assert!(
lista.contains(r#"useEnVivo("producto", productos.refrescar);"#),
"{lista}"
);
let detalle = read(&output, &format!("{k}/detalle-producto.tsx"));
assert!(
detalle.contains(r#"useEnVivo("producto", producto.refrescar, id);"#),
"{detalle}"
);
cleanup(&dir);
}
#[test]
fn should_leave_live_screens_out_of_a_project_without_events() {
let (dir, output) = project_with_producto(
"en_vivo_none",
NewOptions {
db: true,
..Default::default()
},
);
assert!(!read(&output, BOOTSTRAP).contains("en_vivo"));
assert!(!output.join(FUENTE).exists());
assert!(!output.join(HOOK).exists());
assert!(!read(&output, "web/src/generado/dependencias.ts").contains("enVivo"));
assert!(!read(&output, "web/src/generado/rutas.tsx").contains("Avisos"));
assert!(!output.join("web/src/compartido/ui/avisos.tsx").exists());
let lista = read(
&output,
"web/src/contextos/producto/contenedores/lista-producto.tsx",
);
assert!(!lista.contains("useEnVivo"), "{lista}");
cleanup(&dir);
}
#[test]
fn should_show_the_notices_with_a_message_over_the_app_of_a_project_with_events() {
let (dir, output) = project_with_producto("en_vivo_avisos", events());
let avisos = read(&output, "web/src/compartido/ui/avisos.tsx");
assert!(avisos.contains("export function Avisos("), "{avisos}");
assert!(
output
.join("web/src/compartido/ui/avisos.test.tsx")
.exists()
);
let rutas = read(&output, "web/src/generado/rutas.tsx");
assert!(
rutas.contains(" <Rutas />\n <Avisos />"),
"{rutas}"
);
assert!(rutas.contains("function Rutas() {"), "{rutas}");
cleanup(&dir);
}
fn auth_events() -> NewOptions {
NewOptions {
auth: Some("oidc".into()),
..events()
}
}
#[test]
fn should_add_the_inbox_to_a_project_with_auth_and_events() {
let (dir, output) = project_with_producto("notificaciones_alta", auth_events());
scaffold::run_generate_notifications(&output).unwrap();
assert!(read(&output, "puerto.toml").contains("notificaciones = true"));
let migration = fs::read_dir(output.join("migraciones"))
.unwrap()
.flatten()
.find(|e| {
e.file_name()
.to_string_lossy()
.ends_with("_crear_notificaciones.sql")
})
.expect("the inbox migration");
assert!(
fs::read_to_string(migration.path())
.unwrap()
.ends_with(include_str!(
"../templates/infrastructure/notifications.sql"
))
);
let bootstrap = read(&output, BOOTSTRAP);
assert!(
bootstrap
.contains("puerto_sqlx::notificaciones::NotificacionesPostgres::new(pool.clone())"),
"{bootstrap}"
);
assert!(
bootstrap.contains("MockNotificaciones::new()"),
"{bootstrap}"
);
assert_eq!(
bootstrap
.matches("(api_en_vivo, api_notificaciones)")
.count(),
2,
"{bootstrap}"
);
assert!(
read(&output, "presentacion/api/Cargo.toml")
.contains("puerto-nucleo = { workspace = true, features = [\"pruebas\"] }")
);
for file in [
"web/src/notificaciones/campana.tsx",
"web/src/notificaciones/campana.test.tsx",
"web/src/notificaciones/pagina-notificaciones.tsx",
"web/src/notificaciones/pagina-notificaciones.test.tsx",
"web/src/pruebas/api-notificaciones.ts",
] {
assert!(output.join(file).exists(), "{file}");
}
let rutas = read(&output, "web/src/generado/rutas.tsx");
assert!(
rutas.contains("<Marco menu={entradas} acciones={<Campana />}>"),
"{rutas}"
);
assert!(
rutas.contains(r#"<Route path="/notificaciones">"#),
"{rutas}"
);
let marco = read(&output, "web/src/compartido/ui/marco.tsx");
assert!(marco.contains("acciones?: ReactNode;"), "{marco}");
cleanup(&dir);
}
#[test]
fn should_refuse_the_inbox_without_auth_without_events_or_twice() {
let error_of = |result: Result<(), Box<dyn std::error::Error>>| {
result.err().map(|e| e.to_string()).unwrap_or_default()
};
let (dir, sin_auth) = project_with_producto("notificaciones_sin_auth", events());
assert!(error_of(scaffold::run_generate_notifications(&sin_auth)).contains("auth"));
cleanup(&dir);
let (dir, sin_eventos) = project_with_producto(
"notificaciones_sin_eventos",
NewOptions {
db: true,
auth: Some("oidc".into()),
..Default::default()
},
);
assert!(error_of(scaffold::run_generate_notifications(&sin_eventos)).contains("eventos"));
cleanup(&dir);
let (dir, output) = project_with_producto("notificaciones_dos_veces", auth_events());
scaffold::run_generate_notifications(&output).unwrap();
assert!(error_of(scaffold::run_generate_notifications(&output)).contains("ya tiene"));
cleanup(&dir);
}
#[test]
fn should_flag_an_inbox_without_auth_on_validate() {
let (dir, output) = project_with_producto("notificaciones_validar", events());
let path = output.join("puerto.toml");
let manifest = fs::read_to_string(&path).unwrap().replacen(
"[proyecto]\n",
"[proyecto]\nnotificaciones = true\n",
1,
);
fs::write(&path, manifest).unwrap();
let report = validate::report(&output).unwrap();
assert!(
report
.errors
.iter()
.any(|e| e.contains("proyecto.notificaciones necesita proyecto.auth")),
"{:?}",
report.errors
);
cleanup(&dir);
}
#[test]
fn should_write_the_live_files_a_project_from_before_lacks_when_its_wiring_is_regenerated() {
let (dir, output) = project_with_producto("en_vivo_de_antes", events());
for file in [FUENTE, HOOK, "web/src/compartido/ui/avisos.tsx"] {
fs::remove_file(output.join(file)).unwrap();
}
crate::generators::bootstrap::regenerate_bootstrap(&output).unwrap();
for file in [FUENTE, HOOK, "web/src/compartido/ui/avisos.tsx"] {
assert!(output.join(file).exists(), "{file}");
}
cleanup(&dir);
}
#[test]
fn should_open_the_pool_for_the_live_stream_before_any_postgres_entity() {
let dir = temp_dir("en_vivo_sin_entidades");
cleanup(&dir);
fs::create_dir_all(&dir).unwrap();
let output = new_project(
Some("en-vivo-sin-entidades".into()),
NewOptions {
no_web: true,
no_portada: true,
..events()
},
Some(dir.clone()),
)
.unwrap();
let bootstrap = read(&output, BOOTSTRAP);
assert!(
bootstrap.contains("puerto_sqlx::en_vivo::escuchar(&pool"),
"{bootstrap}"
);
assert!(
bootstrap.contains("let pool = puerto_sqlx::crear_pool_postgres(&database_url)"),
"{bootstrap}"
);
cleanup(&dir);
}