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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
// Las variantes de éxito llevan el DTO o los bytes del fichero.
#![allow(clippy::large_enum_variant)]

use std::sync::Arc;

{% for f in files %}use aplicacion_{{ snake }}::{{ f.descargar }}::{{ "{" }}{{ f.descargar_pascal }}, Params{{ f.descargar_pascal }}};
use aplicacion_{{ snake }}::{{ f.quitar }}::{{ "{" }}{{ f.quitar_pascal }}, Params{{ f.quitar_pascal }}};
use aplicacion_{{ snake }}::{{ f.subir }}::{{ "{" }}{{ f.subir_pascal }}, Params{{ f.subir_pascal }}};
{% endfor %}use dominio_{{ snake }}::modelo::Id{{ pascal }};
use poem::http::StatusCode;
use poem::{Body, Request};
use poem_openapi::param::{Path, Query};
use poem_openapi::payload::{Binary, Json};
use poem_openapi::{ApiResponse, OpenApi, Tags};
{% if protected %}use puerto_web::auth::BearerAuth;
{% endif %}use puerto_web::ficheros::{Descarga, DtoFichero, ErrorSubida, leer_subida, tipo_de};
{% if any_roles %}use puerto_web::requiere_rol;
{% endif %}use puerto_web::RespuestaError;
use uuid::Uuid;

use crate::errores::a_respuesta_error;

/// La misma etiqueta que `rutas.rs`: poem-openapi junta las dos por su nombre.
#[derive(Tags)]
enum ApiTags {
    {{ pascal }},
}

/// Las rutas de los ficheros de {{ pascal }} (ADR-0034 de Puerto). Subir es el fichero tal cual en el
/// cuerpo (`Content-Type`, su tipo; `?nombre=`, su nombre); descargar responde sus bytes, en línea
/// solo si es una imagen o un PDF. Va en su propio `Api` para que `rutas.rs` no cambie;
/// `generado/bootstrap.rs` lo monta junto a `Api{{ pascal }}`.
pub struct ApiFicheros{{ pascal }} {
{% for f in files %}    pub {{ f.subir }}: Arc<dyn {{ f.subir_pascal }}>,
    pub {{ f.descargar }}: Arc<dyn {{ f.descargar_pascal }}>,
    pub {{ f.quitar }}: Arc<dyn {{ f.quitar_pascal }}>,
{% endfor %}    /// El tamaño máximo de una subida, en bytes (`FICHEROS_TAMANO_MAXIMO`): más es un 413.
    pub tamano_maximo: u64,
}

#[OpenApi]
impl ApiFicheros{{ pascal }} {
{%- for f in files %}
    /// Subir {% if f.list %}un fichero a{% else %}el fichero de{% endif %} `{{ f.name }}`: {{ pascal }}
    #[oai(path = "/{{ plural }}/:id/{{ f.name }}", method = "{% if f.list %}post{% else %}put{% endif %}", tag = "ApiTags::{{ pascal }}")]
{% for role in subir_roles %}    #[requiere_rol("{{ role }}")]
{% endfor %}    async fn {{ f.subir }}(
        &self,
{% if subir_protected %}        auth: BearerAuth,
{% endif %}        id: Path<Uuid>,
        nombre: Query<Option<String>>,
        peticion: &Request,
        cuerpo: Binary<Body>,
    ) -> Respuesta{{ f.subir_pascal }} {
        let contenido = match leer_subida(cuerpo.0, self.tamano_maximo).await {
            Ok(contenido) => contenido,
            Err(ErrorSubida::DemasiadoGrande) => {
                return Respuesta{{ f.subir_pascal }}::DemasiadoGrande(Json(RespuestaError::from_codigo(
                    "{{ snake }}.{{ f.name }}_demasiado_grande",
                )));
            }
            Err(ErrorSubida::Ilegible) => {
                return Respuesta{{ f.subir_pascal }}::PeticionIncorrecta(Json(RespuestaError::from_codigo(
                    "{{ snake }}.{{ f.name }}_ilegible",
                )));
            }
        };
        let params = Params{{ f.subir_pascal }} {
{% if subir_protected %}            actor: auth.0,
{% endif %}            id: Id{{ pascal }}::from_uuid(id.0),
            nombre: nombre.0.unwrap_or_default(),
            tipo_contenido: tipo_de(peticion),
            contenido,
        };
        match self.{{ f.subir }}.ejecutar(params).await {
            Ok(fichero) => Respuesta{{ f.subir_pascal }}::{% if f.list %}Creado{% else %}Ok{% endif %}(Json(DtoFichero::from_dominio(&fichero))),
            Err(err) => {
                let (status, error) = a_respuesta_error(err);
                Respuesta{{ f.subir_pascal }}::from_status(status, error)
            }
        }
    }

    /// Descargar {% if f.list %}un fichero de{% else %}el fichero de{% endif %} `{{ f.name }}`: {{ pascal }}
    #[oai(path = "/{{ plural }}/:id/{{ f.name }}{% if f.list %}/:id_fichero{% endif %}", method = "get", tag = "ApiTags::{{ pascal }}")]
{% for role in descargar_roles %}    #[requiere_rol("{{ role }}")]
{% endfor %}    async fn {{ f.descargar }}(
        &self,
{% if descargar_protected %}        auth: BearerAuth,
{% endif %}        id: Path<Uuid>,
{% if f.list %}        id_fichero: Path<Uuid>,
{% endif %}    ) -> Respuesta{{ f.descargar_pascal }} {
        let params = Params{{ f.descargar_pascal }} {
{% if descargar_protected %}            actor: auth.0,
{% endif %}            id: Id{{ pascal }}::from_uuid(id.0),
{% if f.list %}            id_fichero: id_fichero.0,
{% endif %}        };
        match self.{{ f.descargar }}.ejecutar(params).await {
            Ok((fichero, contenido)) => Respuesta{{ f.descargar_pascal }}::Ok(Descarga::new(fichero, contenido)),
            Err(err) => {
                let (status, error) = a_respuesta_error(err);
                Respuesta{{ f.descargar_pascal }}::from_status(status, error)
            }
        }
    }

    /// Quitar {% if f.list %}un fichero de{% else %}el fichero de{% endif %} `{{ f.name }}`: {{ pascal }}
    #[oai(path = "/{{ plural }}/:id/{{ f.name }}{% if f.list %}/:id_fichero{% endif %}", method = "delete", tag = "ApiTags::{{ pascal }}")]
{% for role in subir_roles %}    #[requiere_rol("{{ role }}")]
{% endfor %}    async fn {{ f.quitar }}(
        &self,
{% if subir_protected %}        auth: BearerAuth,
{% endif %}        id: Path<Uuid>,
{% if f.list %}        id_fichero: Path<Uuid>,
{% endif %}    ) -> Respuesta{{ f.quitar_pascal }} {
        let params = Params{{ f.quitar_pascal }} {
{% if subir_protected %}            actor: auth.0,
{% endif %}            id: Id{{ pascal }}::from_uuid(id.0),
{% if f.list %}            id_fichero: id_fichero.0,
{% endif %}        };
        match self.{{ f.quitar }}.ejecutar(params).await {
            Ok(()) => Respuesta{{ f.quitar_pascal }}::SinContenido,
            Err(err) => {
                let (status, error) = a_respuesta_error(err);
                Respuesta{{ f.quitar_pascal }}::from_status(status, error)
            }
        }
    }
{%- endfor %}
}
{% for f in files %}
#[derive(ApiResponse)]
pub enum Respuesta{{ f.subir_pascal }} {
    #[oai(status = {% if f.list %}201{% else %}200{% endif %})]
    {% if f.list %}Creado{% else %}Ok{% endif %}(Json<DtoFichero>),
    /// El cuerpo no se pudo leer entero.
    #[oai(status = 400)]
    PeticionIncorrecta(Json<RespuestaError>),
    #[oai(status = 401)]
    NoAutorizado(Json<RespuestaError>),
    #[oai(status = 403)]
    Prohibido(Json<RespuestaError>),
    #[oai(status = 404)]
    NoEncontrado(Json<RespuestaError>),
    /// Más grande que `FICHEROS_TAMANO_MAXIMO`.
    #[oai(status = 413)]
    DemasiadoGrande(Json<RespuestaError>),
    #[oai(status = 422)]
    NoProcesable(Json<RespuestaError>),
    /// El almacén de ficheros{% if subir_protected %}, o quien comprueba el token,{% endif %} no responde.
    #[oai(status = 503)]
    NoDisponible(Json<RespuestaError>),
    #[oai(status = 500)]
    ErrorInterno(Json<RespuestaError>),
}

impl Respuesta{{ f.subir_pascal }} {
    pub fn from_status(status: StatusCode, error: Json<RespuestaError>) -> Self {
        match status {
            StatusCode::UNAUTHORIZED => Self::NoAutorizado(error),
            StatusCode::FORBIDDEN => Self::Prohibido(error),
            StatusCode::NOT_FOUND => Self::NoEncontrado(error),
            StatusCode::UNPROCESSABLE_ENTITY => Self::NoProcesable(error),
            StatusCode::SERVICE_UNAVAILABLE => Self::NoDisponible(error),
            _ => Self::ErrorInterno(error),
        }
    }
}

#[derive(ApiResponse)]
pub enum Respuesta{{ f.descargar_pascal }} {
    /// El contenido: en línea si es una imagen o un PDF; si no, como descarga.
    #[oai(status = 200)]
    Ok(Descarga),
    #[oai(status = 401)]
    NoAutorizado(Json<RespuestaError>),
    #[oai(status = 403)]
    Prohibido(Json<RespuestaError>),
    #[oai(status = 404)]
    NoEncontrado(Json<RespuestaError>),
    /// El almacén de ficheros{% if descargar_protected %}, o quien comprueba el token,{% endif %} no responde.
    #[oai(status = 503)]
    NoDisponible(Json<RespuestaError>),
    #[oai(status = 500)]
    ErrorInterno(Json<RespuestaError>),
}

impl Respuesta{{ f.descargar_pascal }} {
    pub fn from_status(status: StatusCode, error: Json<RespuestaError>) -> Self {
        match status {
            StatusCode::UNAUTHORIZED => Self::NoAutorizado(error),
            StatusCode::FORBIDDEN => Self::Prohibido(error),
            StatusCode::NOT_FOUND => Self::NoEncontrado(error),
            StatusCode::SERVICE_UNAVAILABLE => Self::NoDisponible(error),
            _ => Self::ErrorInterno(error),
        }
    }
}

#[derive(ApiResponse)]
pub enum Respuesta{{ f.quitar_pascal }} {
    #[oai(status = 204)]
    SinContenido,
    #[oai(status = 401)]
    NoAutorizado(Json<RespuestaError>),
    #[oai(status = 403)]
    Prohibido(Json<RespuestaError>),
    #[oai(status = 404)]
    NoEncontrado(Json<RespuestaError>),
    /// El almacén de ficheros{% if subir_protected %}, o quien comprueba el token,{% endif %} no responde.
    #[oai(status = 503)]
    NoDisponible(Json<RespuestaError>),
    #[oai(status = 500)]
    ErrorInterno(Json<RespuestaError>),
}

impl Respuesta{{ f.quitar_pascal }} {
    pub fn from_status(status: StatusCode, error: Json<RespuestaError>) -> Self {
        match status {
            StatusCode::UNAUTHORIZED => Self::NoAutorizado(error),
            StatusCode::FORBIDDEN => Self::Prohibido(error),
            StatusCode::NOT_FOUND => Self::NoEncontrado(error),
            StatusCode::SERVICE_UNAVAILABLE => Self::NoDisponible(error),
            _ => Self::ErrorInterno(error),
        }
    }
}
{% endfor %}
#[cfg(test)]
mod tests {
{% for f in files %}    use aplicacion_{{ snake }}::{{ f.descargar }}::dobles::Mock{{ f.descargar_pascal }};
    use aplicacion_{{ snake }}::{{ f.quitar }}::dobles::Mock{{ f.quitar_pascal }};
    use aplicacion_{{ snake }}::{{ f.subir }}::dobles::Mock{{ f.subir_pascal }};
{% endfor %}    use dominio_{{ snake }}::errores::Error{{ pascal }};
{% if protected %}    use poem::{EndpointExt, Route, test::TestClient};
    use poem_openapi::OpenApiService;
    use puerto_nucleo::auth::dobles::{MadrePrincipal, MockAutenticador};
    use puerto_nucleo::auth::{Autenticador, ErrorAuth};
{% else %}    use poem::{Route, test::TestClient};
    use poem_openapi::OpenApiService;
{% endif %}    use puerto_nucleo::ficheros::Fichero;

    use super::*;

    /// El máximo de los tests: 4 bytes.
    const TAMANO_MAXIMO: u64 = 4;

    /// Los casos de uso de las rutas, doblados: sin expectativas, fallan si se les llama.
    struct Dobles {
{% for f in files %}        {{ f.subir }}: Mock{{ f.subir_pascal }},
        {{ f.descargar }}: Mock{{ f.descargar_pascal }},
        {{ f.quitar }}: Mock{{ f.quitar_pascal }},
{% endfor %}    }

    impl Dobles {
        fn new() -> Self {
            Self {
{% for f in files %}                {{ f.subir }}: Mock{{ f.subir_pascal }}::new(),
                {{ f.descargar }}: Mock{{ f.descargar_pascal }}::new(),
                {{ f.quitar }}: Mock{{ f.quitar_pascal }}::new(),
{% endfor %}            }
        }

        fn api(self) -> ApiFicheros{{ pascal }} {
            ApiFicheros{{ pascal }} {
{% for f in files %}                {{ f.subir }}: Arc::new(self.{{ f.subir }}),
                {{ f.descargar }}: Arc::new(self.{{ f.descargar }}),
                {{ f.quitar }}: Arc::new(self.{{ f.quitar }}),
{% endfor %}                tamano_maximo: TAMANO_MAXIMO,
            }
        }
    }
{% if protected %}
    /// Acepta `llamante`{% if caller_roles %} (con los roles de las rutas){% endif %} y `nadie` (sin roles).
    fn autenticador() -> Arc<dyn Autenticador> {
        let mut doble = MockAutenticador::new();
        doble.expect_autenticar().returning(|token| match token {
            "llamante" => Ok({% if caller_roles %}MadrePrincipal::new()
                .con_roles([{% for role in caller_roles %}"{{ role }}"{% if not loop.last %}, {% endif %}{% endfor %}])
                .construir(){% else %}MadrePrincipal::aleatorio(){% endif %}),
            "nadie" => Ok(MadrePrincipal::aleatorio()),
            _ => Err(ErrorAuth::Invalido),
        });
        Arc::new(doble)
    }

    /// Las rutas sobre `dobles`; `autorizacion`, la cabecera de cada petición (`None`: ninguna).
    fn cliente_con(dobles: Dobles, autorizacion: Option<&str>) -> TestClient<impl poem::Endpoint> {
        let cliente = TestClient::new(
            Route::new()
                .nest("/", OpenApiService::new(dobles.api(), "test", "1.0"))
                .data(autenticador()),
        );
        match autorizacion {
            Some(valor) => cliente.default_header("Authorization", valor),
            None => cliente,
        }
    }

    /// Las rutas sobre `dobles`, con la sesión de quien tiene los roles de todas.
    fn cliente(dobles: Dobles) -> TestClient<impl poem::Endpoint> {
        cliente_con(dobles, Some("Bearer llamante"))
    }
{% else %}
    /// Las rutas sobre `dobles`.
    fn cliente(dobles: Dobles) -> TestClient<Route> {
        TestClient::new(Route::new().nest("/", OpenApiService::new(dobles.api(), "test", "1.0")))
    }
{% endif %}{% for f in files %}
    fn ruta_{{ f.name }}() -> String {
        format!("/{{ plural }}/{}/{{ f.name }}", Uuid::new_v4())
    }
{% if f.list %}
    fn ruta_{{ f.name }}_fichero() -> String {
        format!("/{{ plural }}/{}/{{ f.name }}/{}", Uuid::new_v4(), Uuid::new_v4())
    }
{% endif %}
    #[tokio::test]
    async fn deberia_responder_{% if f.list %}201{% else %}200{% endif %}_con_el_fichero_cuando_se_sube_a_{{ f.name }}() {
        // Preparar
        let mut dobles = Dobles::new();
        dobles
            .{{ f.subir }}
            .expect_ejecutar()
            .withf(|params| params.nombre == "foto.png" && params.tipo_contenido == "image/png")
            .return_once(|params| Ok(Fichero::nuevo(&params.nombre, &params.tipo_contenido, 3)));
        let cliente = cliente(dobles);

        // Actuar
        let respuesta = cliente
            .{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
            .query("nombre", &"foto.png")
            .content_type("image/png")
            .body(vec![1u8, 2, 3])
            .send()
            .await;

        // Comprobar
        respuesta.assert_status(StatusCode::{% if f.list %}CREATED{% else %}OK{% endif %});
        let json = respuesta.json().await;
        let fichero = json.value().object();
        fichero.get("nombre").assert_string("foto.png");
        fichero.get("tipoContenido").assert_string("image/png");
        fichero.get("tamano").assert_i64(3);
    }

    #[tokio::test]
    async fn deberia_responder_413_sin_llamar_al_caso_de_uso_cuando_{{ f.name }}_pasa_del_maximo() {
        // Preparar — sin expectativas: nunca se llega al caso de uso
        let cliente = cliente(Dobles::new());

        // Actuar
        let respuesta = cliente
            .{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
            .content_type("application/octet-stream")
            .body(vec![0u8; TAMANO_MAXIMO as usize + 1])
            .send()
            .await;

        // Comprobar
        respuesta.assert_status(StatusCode::PAYLOAD_TOO_LARGE);
        respuesta
            .json()
            .await
            .value()
            .object()
            .get("codigo")
            .assert_string("{{ snake }}.{{ f.name }}_demasiado_grande");
    }

    #[tokio::test]
    async fn deberia_responder_422_cuando_{{ f.name }}_llega_vacio() {
        // Preparar
        let mut dobles = Dobles::new();
        dobles
            .{{ f.subir }}
            .expect_ejecutar()
            .return_once(|_| Err(Error{{ pascal }}::Validacion("{{ f.name }}_vacio".into())));
        let cliente = cliente(dobles);

        // Actuar
        let respuesta = cliente
            .{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
            .content_type("application/octet-stream")
            .body(Vec::<u8>::new())
            .send()
            .await;

        // Comprobar
        respuesta.assert_status(StatusCode::UNPROCESSABLE_ENTITY);
        respuesta
            .json()
            .await
            .value()
            .object()
            .get("codigo")
            .assert_string("{{ snake }}.validacion.{{ f.name }}_vacio");
    }

    #[tokio::test]
    async fn deberia_servir_en_linea_una_imagen_de_{{ f.name }}() {
        // Preparar
        let mut dobles = Dobles::new();
        dobles
            .{{ f.descargar }}
            .expect_ejecutar()
            .return_once(|_| Ok((Fichero::nuevo("foto.png", "image/png", 3), vec![1, 2, 3])));
        let cliente = cliente(dobles);

        // Actuar
        let respuesta = cliente.get(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;

        // Comprobar
        respuesta.assert_status_is_ok();
        respuesta.assert_header("content-type", "image/png");
        respuesta.assert_header("content-disposition", "inline; filename*=UTF-8''foto.png");
        respuesta.assert_header("x-content-type-options", "nosniff");
        respuesta.assert_bytes(vec![1u8, 2, 3]).await;
    }

    #[tokio::test]
    async fn deberia_servir_como_descarga_un_html_de_{{ f.name }}() {
        // Preparar
        let mut dobles = Dobles::new();
        dobles
            .{{ f.descargar }}
            .expect_ejecutar()
            .return_once(|_| Ok((Fichero::nuevo("pagina.html", "text/html", 3), vec![1, 2, 3])));
        let cliente = cliente(dobles);

        // Actuar
        let respuesta = cliente.get(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;

        // Comprobar
        respuesta.assert_status_is_ok();
        respuesta.assert_header("content-type", "application/octet-stream");
        respuesta.assert_header("content-disposition", "attachment; filename*=UTF-8''pagina.html");
        respuesta.assert_header("x-content-type-options", "nosniff");
    }

    #[tokio::test]
    async fn deberia_responder_404_cuando_{{ f.name }}_no_tiene_el_fichero() {
        // Preparar
        let mut dobles = Dobles::new();
        dobles
            .{{ f.descargar }}
            .expect_ejecutar()
            .return_once(|_| Err(Error{{ pascal }}::FicheroNoEncontrado("{{ f.name }}".into())));
        let cliente = cliente(dobles);

        // Actuar
        let respuesta = cliente.get(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;

        // Comprobar
        respuesta.assert_status(StatusCode::NOT_FOUND);
        respuesta
            .json()
            .await
            .value()
            .object()
            .get("codigo")
            .assert_string("{{ snake }}.{{ f.name }}_no_encontrado");
    }

    #[tokio::test]
    async fn deberia_responder_204_cuando_se_quita_{{ f.name }}() {
        // Preparar
        let mut dobles = Dobles::new();
        dobles.{{ f.quitar }}.expect_ejecutar().return_once(|_| Ok(()));
        let cliente = cliente(dobles);

        // Actuar
        let respuesta = cliente.delete(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;

        // Comprobar
        respuesta.assert_status(StatusCode::NO_CONTENT);
    }

    #[tokio::test]
    async fn deberia_responder_503_cuando_el_almacen_de_{{ f.name }}_no_responde() {
        // Preparar
        let mut dobles = Dobles::new();
        dobles
            .{{ f.quitar }}
            .expect_ejecutar()
            .return_once(|_| Err(Error{{ pascal }}::AlmacenNoDisponible));
        let cliente = cliente(dobles);

        // Actuar
        let respuesta = cliente.delete(ruta_{{ f.name }}{% if f.list %}_fichero{% endif %}()).send().await;

        // Comprobar
        respuesta.assert_status(StatusCode::SERVICE_UNAVAILABLE);
    }
{%- if subir_protected %}

    #[tokio::test]
    async fn deberia_responder_401_cuando_se_sube_a_{{ f.name }}_sin_token() {
        // Preparar — sin expectativas: nunca se llega al caso de uso
        let cliente = cliente_con(Dobles::new(), None);

        // Actuar
        let respuesta = cliente
            .{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
            .content_type("application/octet-stream")
            .body(vec![1u8])
            .send()
            .await;

        // Comprobar
        respuesta.assert_status(StatusCode::UNAUTHORIZED);
    }
{%- endif %}
{%- if subir_roles %}

    #[tokio::test]
    async fn deberia_responder_403_cuando_se_sube_a_{{ f.name }}_sin_el_rol() {
        // Preparar — sin expectativas: nunca se llega al caso de uso
        let cliente = cliente_con(Dobles::new(), Some("Bearer nadie"));

        // Actuar
        let respuesta = cliente
            .{% if f.list %}post{% else %}put{% endif %}(ruta_{{ f.name }}())
            .content_type("application/octet-stream")
            .body(vec![1u8])
            .send()
            .await;

        // Comprobar
        respuesta.assert_status(StatusCode::FORBIDDEN);
    }
{%- endif %}
{% endfor %}}