/** Part of Beyond. Collina Systems proprietary module. */ import { expect, test, describe } from "@odoo/hoot"; import { click, press, queryAll, queryFirst, setInputFiles } from "@odoo/hoot-dom"; import { animationFrame } from "@odoo/hoot-mock"; import { defineModels, fields, models, mountView, onRpc, patchWithCleanup, } from "@web/../tests/web_test_helpers"; import { browser } from "@web/core/browser/browser"; import { defineMailModels } from "@mail/../tests/mail_test_helpers"; /** * Unit tests for beyond_image_camera. * * The one that matters most is the secure-context one: production has no TLS * yet, so navigator.mediaDevices does not exist on the branch tablets and the * widget must not offer a button that would throw. That is the case a person * cannot easily check by hand — dev runs on localhost, where the camera * always works. */ describe.current.tags("desktop"); // Un modelo propio y NO res.partner: montar una vista sobre res.partner // arrastra la maquinaria de mail (el chatter pide discuss.channel) y las // pruebas mueren antes de llegar al widget. Al widget el modelo le da igual. class BeyondFoto extends models.Model { _name = "beyond.foto"; name = fields.Char(); image_1920 = fields.Binary(); _records = [ { id: 1, name: "Alejandro Mcdonald", image_1920: "FOTO==" }, { id: 2, name: "Ximena", image_1920: false }, ]; } // Montar CUALQUIER formulario despierta la maquinaria de mail (el chatter // pide discuss.channel) aunque la vista no lo lleve, porque mail parchea la // vista de formulario en el bundle de pruebas. Sin esto, todas las pruebas // mueren antes de llegar al widget. defineMailModels(); defineModels([BeyondFoto]); // Lleva el pie propio a propósito: guardar por ahí es lo que hace una // persona en la ficha, y de paso ejercita el widget del pie. const VISTA = /* xml */ `
`; /** * Fakes a camera: a REAL MediaStream whose track we can watch. * * It has to be a real one. Assigning a plain object to video.srcObject throws * in Chromium ("the provided value is not of type MediaStream"), which showed * up as an opaque "error in the owl lifecycle" and hid what was really being * tested. A canvas gives us a genuine stream with a genuine track. */ function camaraFalsa({ camaras = 1 } = {}) { const lienzo = document.createElement("canvas"); lienzo.width = 4; lienzo.height = 4; const stream = lienzo.captureStream(); const pista = stream.getVideoTracks()[0]; pista.detenida = false; const detenerReal = pista.stop.bind(pista); pista.stop = () => { pista.detenida = true; detenerReal(); }; pista.peticiones = []; patchWithCleanup(browser, { navigator: { ...browser.navigator, mediaDevices: { getUserMedia: async (restricciones) => { pista.peticiones.push(restricciones?.video?.facingMode); return stream; }, enumerateDevices: async () => Array.from({ length: camaras }, () => ({ kind: "videoinput" })), }, }, }); return pista; } /** Takes the camera away, the way an http:// page does. */ function sinCamara() { patchWithCleanup(browser, { navigator: { ...browser.navigator, mediaDevices: undefined }, }); } test("el menú de la foto se abre al pasar el mouse y se cierra al salir", async () => { camaraFalsa(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); expect(".beyond_foto_menu").toHaveCount(0); await queryFirst(".beyond_foto").dispatchEvent(new MouseEvent("mouseenter")); await animationFrame(); expect(".beyond_foto_menu").toHaveCount(1); await queryFirst(".beyond_foto").dispatchEvent(new MouseEvent("mouseleave")); await animationFrame(); expect(".beyond_foto_menu").toHaveCount(0); }); test("el contenedor de la foto no recorta el menú", async () => { // ESTA es la prueba que faltaba. El menú se renderizaba —el t-if pasaba y // el DOM lo tenía— pero el contenedor llevaba overflow:hidden para // redondear la imagen, y el menú cuelga por debajo con top:100%: quedaba // recortado y era inalcanzable. Contar elementos no lo detecta, porque el // nodo está ahí; ni :visible, porque un elemento recortado conserva su // tamaño. Lo que hay que afirmar es que nadie lo recorta. camaraFalsa(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); const menu = queryFirst(".beyond_foto_menu"); expect(menu).not.toBe(null); // Solo hasta la hoja del formulario: de ahí para arriba el cliente web // recorta a propósito (.o_form_view y .o_action_manager son sus // contenedores de desplazamiento). Lo que no puede recortar es el propio // widget, que es donde estaba el defecto. // Solo los dos nodos que este widget controla. De ahí para arriba el // cliente web recorta a propósito: .o_form_view y .o_action_manager son // sus contenedores de desplazamiento y siempre llevan overflow:hidden. for (const selector of [".beyond_foto", ".o_field_widget[name=image_1920]"]) { const nodo = queryFirst(selector); if (!nodo) { continue; } const estilo = getComputedStyle(nodo); expect(`${estilo.overflow} ${estilo.overflowY}`).not.toInclude("hidden", { message: `${selector} recorta el menú de la foto`, }); } }); test("un toque fija el menú y otro lo suelta (en táctil no hay hover)", async () => { camaraFalsa(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); expect(".beyond_foto_menu").toHaveCount(1); // Fijado: salir con el mouse ya no lo cierra. await queryFirst(".beyond_foto").dispatchEvent(new MouseEvent("mouseleave")); await animationFrame(); expect(".beyond_foto_menu").toHaveCount(1); await click(".beyond_foto"); await animationFrame(); expect(".beyond_foto_menu").toHaveCount(0); }); test("sin cámara no se ofrece «Tomar fotografía», y sí «Subir archivo»", async () => { // Es el caso de las tablets de sucursal mientras producción no tenga TLS: // fuera de contexto seguro el navegador ni siquiera define mediaDevices. sinCamara(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); const opciones = queryAll(".beyond_foto_opcion").map((b) => b.textContent.trim()); expect(opciones).not.toInclude("Tomar fotografía"); expect(opciones).toInclude("Subir archivo"); }); test("con cámara sí se ofrece «Tomar fotografía»", async () => { camaraFalsa(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); const opciones = queryAll(".beyond_foto_opcion").map((b) => b.textContent.trim()); expect(opciones).toInclude("Tomar fotografía"); }); test("«Subir archivo» pide la cámara trasera, no la frontal", async () => { // Coherencia con el diálogo propio: el caso de uso es el mostrador // fotografiando al cliente, no una selfie. sinCamara(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); expect("input[type=file]").toHaveAttribute("capture", "environment"); }); test("«Eliminar» limpia el campo", async () => { camaraFalsa(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); await click(".beyond_foto_borrar"); await animationFrame(); // Sin imagen no hay nada que borrar: la opción desaparece. expect(".beyond_foto_borrar").toHaveCount(0); }); test("cerrar el diálogo apaga la cámara", async () => { // Una cámara que se queda encendida deja el testigo del aparato prendido // y parece que el local está grabando. const pista = camaraFalsa(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); await click(".beyond_foto_opcion"); // «Tomar fotografía» await animationFrame(); await animationFrame(); expect(".beyond_camara_video").toHaveCount(1); expect(pista.detenida).toBe(false); await click(".beyond_camara_dialogo .modal-footer button:contains(Cancelar)"); await animationFrame(); expect(pista.detenida).toBe(true); }); test("con una sola cámara no se ofrece cambiarla", async () => { camaraFalsa({ camaras: 1 }); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); await click(".beyond_foto_opcion"); await animationFrame(); await animationFrame(); const botones = queryAll(".beyond_camara_dialogo .modal-footer .btn").map((b) => b.textContent.trim() ); expect(botones).not.toInclude("Cambiar de cámara"); }); test("el diálogo pide la cámara TRASERA por defecto", async () => { // El caso de uso es el mostrador retratando al cliente, no una selfie. const pista = camaraFalsa(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); await click(".beyond_foto_opcion"); await animationFrame(); await animationFrame(); expect(pista.peticiones[0]).toBe("environment"); }); test("el botón de cambio pasa a la cámara frontal", async () => { const pista = camaraFalsa({ camaras: 2 }); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); await click(".beyond_foto_opcion"); await animationFrame(); await animationFrame(); await click(".beyond_camara_dialogo .modal-footer button:contains(Cambiar)"); await animationFrame(); await animationFrame(); expect(pista.peticiones).toEqual(["environment", "user"]); }); test("cerrar con Escape también apaga la cámara", async () => { // Cerrar con el teclado es la salida que más se olvida, y una cámara // encendida deja el testigo del aparato prendido. const pista = camaraFalsa(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); await click(".beyond_foto_opcion"); await animationFrame(); await animationFrame(); expect(".beyond_camara_video").toHaveCount(1); await press("Escape"); await animationFrame(); expect(".beyond_camara_dialogo").toHaveCount(0); expect(pista.detenida).toBe(true); }); /** * Lo que se guarda de verdad. * * Las pruebas de arriba miran el menú; ninguna miraba el REGISTRO. Y ahí * estaba el defecto: subir un archivo pintaba la imagen y no la escribía, así * que al guardar no viajaba. Estas tres afirman lo único que le importa a * quien atiende el mostrador — que la foto quede — por las tres rutas. */ function capturarGuardado() { const guardado = { valores: null }; onRpc("beyond.foto", "web_save", ({ args }) => { guardado.valores = args[1]; }); return guardado; } const PIXEL = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; test("«Tomar fotografía» deja la imagen en el registro al guardar", async () => { camaraFalsa(); const guardado = capturarGuardado(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); await click(".beyond_foto_opcion"); await animationFrame(); await animationFrame(); await click(".beyond_camara_dialogo .modal-footer button:contains(Tomar)"); await animationFrame(); await click(".beyond_boton_guardar"); await animationFrame(); expect(guardado.valores).not.toBe(null); expect(guardado.valores.image_1920).toBeOfType("string"); }); test("«Subir archivo» deja la imagen en el registro al guardar", async () => { // La ruta que estaba rota: la imagen se pintaba y no se escribía. sinCamara(); const guardado = capturarGuardado(); await mountView({ type: "form", resModel: "beyond.foto", resId: 2, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); await click(".beyond_foto_opcion:contains(Subir)"); await animationFrame(); await setInputFiles([ new File([Uint8Array.from(atob(PIXEL), (c) => c.charCodeAt(0))], "cliente.png", { type: "image/png", }), ]); await animationFrame(); await animationFrame(); await click(".beyond_boton_guardar"); await animationFrame(); expect(guardado.valores).not.toBe(null); expect(guardado.valores.image_1920).toBeOfType("string"); }); test("«Eliminar» deja el campo vacío en el registro al guardar", async () => { // La tercera ruta, que nadie había probado. camaraFalsa(); const guardado = capturarGuardado(); await mountView({ type: "form", resModel: "beyond.foto", resId: 1, arch: VISTA }); await click(".beyond_foto"); await animationFrame(); await click(".beyond_foto_borrar"); await animationFrame(); await click(".beyond_boton_guardar"); await animationFrame(); expect(guardado.valores).not.toBe(null); expect(guardado.valores.image_1920).toBe(false); });