use super::*;
#[test]
fn should_parse_a_file_as_an_optional_fichero() {
let field = puerto_toml::parse_field_arg("foto:fichero").unwrap();
assert_eq!(field.field_type, "Option<Fichero>");
assert!(field.value_object.is_none());
assert!(field.references.is_none());
}
#[test]
fn should_parse_a_list_of_files_as_a_vec_of_fichero() {
let field = puerto_toml::parse_field_arg("anexos:vec:fichero").unwrap();
assert_eq!(field.field_type, "Vec<Fichero>");
}
#[test]
fn should_say_a_file_is_already_optional_when_it_is_written_with_opt() {
let error = puerto_toml::parse_field_arg("foto:opt:fichero").unwrap_err();
assert!(error.contains("ya es opcional"), "{error}");
assert!(error.contains("`foto:fichero`"), "{error}");
}
#[test]
fn should_refuse_a_unique_file_or_an_optional_list_of_files() {
for arg in [
"foto:fichero!",
"anexos:vec:fichero!",
"anexos:vec:opt:fichero",
] {
assert!(puerto_toml::parse_field_arg(arg).is_err(), "{arg}");
}
}
fn validate_documento_with(
name: &str,
project_extra: &str,
entity_extra: &str,
field: &str,
) -> Result<(), String> {
let dir = temp_dir(name);
cleanup(&dir);
fs::create_dir_all(&dir).unwrap();
fs::write(
dir.join("puerto.toml"),
format!(
r#"[proyecto]
nombre = "archivo"
{project_extra}
[[entidad]]
nombre = "Saludo"
casos_de_uso = ["obtener_saludo"]
[[entidad]]
nombre = "Documento"
casos_de_uso = ["crear_documento", "obtener_documento", "listar_documentos", "actualizar_documento", "borrar_documento"]
{entity_extra}
[[entidad.campos]]
nombre = "titulo"
tipo = "String"
[[entidad.campos]]
{field}
"#
),
)
.unwrap();
let result = validate::run_validate(&dir).map_err(|e| e.to_string());
cleanup(&dir);
result
}
#[test]
fn should_validate_a_file_and_a_list_of_files_on_a_crud_entity() {
for ty in ["Option<Fichero>", "Vec<Fichero>"] {
let result = validate_documento_with(
"files_validate_ok",
"",
"",
&format!("nombre = \"portada\"\ntipo = \"{ty}\""),
);
if let Err(error) = &result {
assert!(
!error.contains("portada") || error.contains("no tiene código"),
"{ty}: {error}"
);
}
}
}
#[test]
fn should_refuse_a_file_with_an_option_that_does_not_fit_it() {
for (option, auth) in [
("unico = true", ""),
("privado = true", "auth = \"oidc\""),
("por_defecto = \"x\"", ""),
("generado = true", ""),
("ejemplo = \"x\"", ""),
("textos = { A = \"a\" }", ""),
] {
let result = validate_documento_with(
"files_validate_option",
auth,
"",
&format!("nombre = \"portada\"\ntipo = \"Option<Fichero>\"\n{option}"),
);
let error = result.expect_err(option);
assert!(error.contains("portada"), "{option}: {error}");
assert!(error.contains("fichero"), "{option}: {error}");
}
}
#[test]
fn should_refuse_a_file_in_the_order_the_unique_set_or_as_the_owner() {
for (entity_extra, auth) in [
("orden = [\"portada\"]", ""),
("unicos = [[\"titulo\", \"portada\"]]", ""),
("propietario = \"portada\"", "auth = \"oidc\""),
] {
let result = validate_documento_with(
"files_validate_entity_option",
auth,
entity_extra,
"nombre = \"portada\"\ntipo = \"Option<Fichero>\"",
);
let error = result.expect_err(entity_extra);
assert!(error.contains("portada"), "{entity_extra}: {error}");
}
}
#[test]
fn should_refuse_a_file_wrapped_in_a_value_object() {
let result = validate_documento_with(
"files_validate_vo",
"",
"",
"nombre = \"portada\"\ntipo = \"Option<Fichero>\"\nobjeto_valor = \"Portada\"",
);
let error = result.unwrap_err();
assert!(error.contains("portada"), "{error}");
}
#[test]
fn should_refuse_a_file_on_an_entity_without_crud() {
let dir = temp_dir("files_validate_no_crud");
cleanup(&dir);
fs::create_dir_all(&dir).unwrap();
fs::write(
dir.join("puerto.toml"),
r#"[proyecto]
nombre = "archivo"
[[entidad]]
nombre = "Documento"
casos_de_uso = ["obtener_documento"]
[[entidad.campos]]
nombre = "portada"
tipo = "Option<Fichero>"
"#,
)
.unwrap();
let result = validate::run_validate(&dir).map_err(|e| e.to_string());
cleanup(&dir);
let error = result.unwrap_err();
assert!(error.contains("portada"), "{error}");
assert!(error.contains("CRUD"), "{error}");
}
#[test]
fn should_refuse_a_use_case_named_like_the_ones_a_file_brings() {
let result = validate_documento_with(
"files_validate_clash",
"",
"",
"nombre = \"portada\"\ntipo = \"Option<Fichero>\"",
);
assert!(
result
.as_ref()
.map_or_else(|e| !e.contains("choca"), |_| true),
"{result:?}"
);
let dir = temp_dir("files_validate_clash_uc");
cleanup(&dir);
fs::create_dir_all(&dir).unwrap();
fs::write(
dir.join("puerto.toml"),
r#"[proyecto]
nombre = "archivo"
[[entidad]]
nombre = "Documento"
casos_de_uso = ["crear_documento", "obtener_documento", "listar_documentos", "actualizar_documento", "borrar_documento", "subir_portada_documento"]
[[entidad.campos]]
nombre = "portada"
tipo = "Option<Fichero>"
"#,
)
.unwrap();
let result = validate::run_validate(&dir).map_err(|e| e.to_string());
cleanup(&dir);
let error = result.unwrap_err();
assert!(error.contains("subir_portada_documento"), "{error}");
}
#[test]
fn should_name_the_three_use_cases_of_each_file_field() {
use crate::generators::naming::file_use_cases;
assert_eq!(
file_use_cases("portada", "documento"),
[
"subir_portada_documento".to_string(),
"descargar_portada_documento".to_string(),
"quitar_portada_documento".to_string(),
]
);
}
use crate::commands::new::{NewOptions, new_project};
fn documento_with_files(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::Field> =
["titulo:String", "portada:fichero", "anexos:vec:fichero"]
.iter()
.map(|arg| puerto_toml::parse_field_arg(arg).unwrap())
.collect();
scaffold::run_scaffold("Documento", &output, &fields, OverwritePolicy::Force).unwrap();
(dir, output)
}
fn read(base: &Path, path: &str) -> String {
fs::read_to_string(base.join(path)).unwrap_or_else(|e| panic!("{path}: {e}"))
}
#[test]
fn should_keep_the_files_on_the_entity_but_out_of_its_props() {
let (dir, output) = documento_with_files(
"files_domain",
NewOptions {
no_db: true,
no_web: true,
..Default::default()
},
);
let modelo = read(&output, "contextos/documento/dominio/src/modelo.rs");
let props = &modelo[modelo.find("pub struct PropsDocumento").unwrap()..];
let props = &props[..props.find('}').unwrap()];
assert!(!props.contains("portada"), "{props}");
assert!(modelo.contains("pub portada: Option<Fichero>,"), "{modelo}");
assert!(modelo.contains("pub anexos: Vec<Fichero>,"), "{modelo}");
assert!(modelo.contains("pub fn cambiar_portada("), "{modelo}");
assert!(modelo.contains("pub fn anadir_anexos("), "{modelo}");
assert!(modelo.contains("pub fn quitar_anexos("), "{modelo}");
let errores = read(&output, "contextos/documento/dominio/src/errores.rs");
assert!(errores.contains("FicheroNoEncontrado(String)"), "{errores}");
assert!(errores.contains("AlmacenNoDisponible"), "{errores}");
cleanup(&dir);
}
#[test]
fn should_write_three_use_cases_and_a_route_file_per_entity_with_files() {
let (dir, output) = documento_with_files(
"files_layers",
NewOptions {
no_db: true,
no_web: true,
..Default::default()
},
);
for field in ["portada", "anexos"] {
for uc in crate::generators::naming::file_use_cases(field, "documento") {
assert!(
output
.join(format!("contextos/documento/aplicacion/src/{uc}.rs"))
.exists(),
"{uc}"
);
}
}
let lib = read(&output, "contextos/documento/aplicacion/src/lib.rs");
assert!(lib.contains("pub mod subir_portada_documento;"), "{lib}");
let rutas = read(&output, "contextos/documento/rest/src/ficheros.rs");
assert!(rutas.contains("pub struct ApiFicherosDocumento"), "{rutas}");
assert!(
rutas.contains(r#"path = "/documentos/:id/portada", method = "put""#),
"{rutas}"
);
assert!(
rutas.contains(r#"path = "/documentos/:id/anexos", method = "post""#),
"{rutas}"
);
assert!(
rutas.contains(r#"path = "/documentos/:id/anexos/:id_fichero", method = "delete""#),
"{rutas}"
);
let dto = read(&output, "contextos/documento/rest/src/dto.rs");
assert!(dto.contains("pub portada: Option<DtoFichero>,"), "{dto}");
let crear = &dto[dto.find("pub struct PeticionCrearDocumento").unwrap()..];
assert!(
!crear[..crear.find('}').unwrap()].contains("portada"),
"{dto}"
);
cleanup(&dir);
}
#[test]
fn should_wire_the_file_store_from_the_environment_once() {
let (dir, output) = documento_with_files(
"files_wiring",
NewOptions {
no_db: true,
no_web: true,
..Default::default()
},
);
let cableado = read(&output, "presentacion/cableado/src/lib.rs");
assert!(
cableado.contains("pub fn construir_con_ficheros("),
"{cableado}"
);
assert!(cableado.contains("pub struct CasosFicheros"), "{cableado}");
let casos = read(&output, "presentacion/cableado/src/documento/casos.rs");
assert!(casos.contains("pub fn subir_portada_documento("), "{casos}");
let bootstrap = read(&output, "presentacion/api/src/generado/bootstrap.rs");
assert!(
bootstrap.contains("ConfigFicheros::from_env()"),
"{bootstrap}"
);
assert!(bootstrap.contains("ApiFicherosDocumento"), "{bootstrap}");
let api = read(&output, "presentacion/api/Cargo.toml");
assert!(
api.contains(r#"puerto-ficheros = { workspace = true, features = ["s3"] }"#),
"{api}"
);
assert!(read(&output, "Cargo.toml").contains("puerto-ficheros = \""));
for env in [".env", ".env.example"] {
let content = read(&output, env);
assert_eq!(
content.matches("FICHEROS_URL=").count(),
1,
"{env}: {content}"
);
}
assert!(
read(&output, ".gitignore")
.lines()
.any(|l| l == "/ficheros")
);
cleanup(&dir);
}
#[test]
fn should_store_each_file_in_a_jsonb_column_when_the_project_has_a_database() {
let (dir, output) = documento_with_files(
"files_db",
NewOptions {
db: true,
no_web: true,
..Default::default()
},
);
let migration = fs::read_dir(output.join("migraciones"))
.unwrap()
.flatten()
.find(|e| {
e.file_name()
.to_string_lossy()
.ends_with("crear_tabla_documento.sql")
})
.map(|e| fs::read_to_string(e.path()).unwrap())
.unwrap();
assert!(migration.contains(" portada JSONB,"), "{migration}");
assert!(
migration.contains(" anexos JSONB NOT NULL DEFAULT '[]',"),
"{migration}"
);
let repositorio = read(
&output,
"contextos/documento/infraestructura/src/repositorio.rs",
);
assert!(
repositorio.contains(r#"portada as \"portada: Json<Fichero>\""#),
"{repositorio}"
);
assert!(
repositorio.contains("async fn deberia_guardar_y_releer_sus_ficheros("),
"{repositorio}"
);
let fila = read(&output, "contextos/documento/infraestructura/src/fila.rs");
assert!(
fila.contains("pub portada: Option<Json<Fichero>>,"),
"{fila}"
);
assert!(fila.contains("pub anexos: Json<Vec<Fichero>>,"), "{fila}");
cleanup(&dir);
}
#[test]
fn should_show_the_files_on_the_detail_and_write_what_they_share_once() {
let (dir, output) = documento_with_files(
"files_web",
NewOptions {
no_db: true,
..Default::default()
},
);
let k = "web/src/contextos/documento";
let detalle = read(&output, &format!("{k}/contenedores/detalle-documento.tsx"));
assert!(
detalle.contains("<ContenedorFicherosDocumento"),
"{detalle}"
);
let ficheros = read(&output, &format!("{k}/contenedores/ficheros-documento.tsx"));
assert!(
ficheros.contains(r#"const RUTA_PORTADA = "/documentos/{id}/portada" as const;"#),
"{ficheros}"
);
assert!(ficheros.contains("<CampoFicheros"), "{ficheros}");
assert!(
output
.join(format!("{k}/contenedores/ficheros-documento.test.tsx"))
.exists()
);
for shared in [
"web/src/compartido/ui/fichero.tsx",
"web/src/api/ficheros.ts",
"web/src/pruebas/api-que-apunta.ts",
] {
assert!(output.join(shared).exists(), "{shared}");
}
let madre = read(&output, "web/src/pruebas/documento.ts");
assert!(madre.contains("anexos: [],"), "{madre}");
let mensajes = read(&output, &format!("{k}/mensajes.ts"));
assert!(
mensajes.contains(r#""documento.portada_demasiado_grande""#),
"{mensajes}"
);
assert!(
mensajes.contains(r#""documento.almacen_no_disponible""#),
"{mensajes}"
);
cleanup(&dir);
}
#[test]
fn should_leave_the_shared_file_components_out_of_a_project_without_files() {
let dir = temp_dir("files_web_none");
cleanup(&dir);
fs::create_dir_all(&dir).unwrap();
let output = new_project(
Some("files-web-none".into()),
NewOptions {
no_db: true,
no_portada: true,
..Default::default()
},
Some(dir.clone()),
)
.unwrap();
let fields = [puerto_toml::parse_field_arg("titulo:String").unwrap()];
scaffold::run_scaffold("Documento", &output, &fields, OverwritePolicy::Force).unwrap();
assert!(!output.join("web/src/compartido/ui/fichero.tsx").exists());
assert!(
!output
.join("web/src/contextos/documento/contenedores/ficheros-documento.tsx")
.exists()
);
cleanup(&dir);
}
#[test]
fn should_refuse_a_use_case_or_a_transition_named_like_a_file_use_case() {
let (dir, output) = documento_with_files(
"files_clash_commands",
NewOptions {
no_db: true,
no_web: true,
..Default::default()
},
);
let path = output.join("contextos/documento/aplicacion/src/subir_portada_documento.rs");
fs::remove_file(&path).unwrap();
let use_case = scaffold::run_use_case("Documento", "subir_portada_documento", &output);
let transition = scaffold::run_generate_transition(
"Documento",
"subir_portada",
None,
&[],
false,
false,
&output,
);
cleanup(&dir);
assert!(use_case.unwrap_err().to_string().contains("ya existe"));
assert!(transition.unwrap_err().to_string().contains("ya existe"));
}