Repository Public
1import { expect, test, type Page } from "@playwright/test";23const PASSWORD = process.env.SPTV_PASSWORD ?? "";4test.skip(!PASSWORD, "SPTV_PASSWORD requis");56async function login(page: Page) {7 await page.goto("/connexion");8 await page.fill('input[name="username"]', process.env.SPTV_USERNAME ?? "sp");9 await page.fill('input[name="password"]', PASSWORD);10 await page.click('button[type="submit"]');11 await page.waitForURL((u) => u.pathname === "/");12}13const apiGet = <T,>(page: Page, path: string) => page.evaluate(async (p) => (await fetch(p, { credentials: "same-origin" })).json(), `/api${path}`) as Promise<T>;14interface Ch { id: string; name: string; status: string; web: boolean }15const canDecode = (name: string) => !name.startsWith("chromium");1617test("accès refusé sans session ; mot de passe erroné rejeté", async ({ page, request }) => {18 await page.goto("/admin");19 await expect(page).toHaveURL(/\/connexion\?next=%2Fadmin/);20 expect((await request.get("/api/channels")).status()).toBe(401);21 expect((await request.get("/api/admin/overview")).status()).toBe(401);22 expect((await request.post("/api/admin/jobs", { data: { type: "sync" } })).status()).toBeGreaterThanOrEqual(401);23 await page.fill('input[name="username"]', "sp"); await page.fill('input[name="password"]', "mauvais-mot-de-passe"); await page.click('button[type="submit"]');24 await expect(page.locator("form [role=alert]")).toContainText("incorrect");25});2627test("connexion, accueil et rangées du catalogue réel", async ({ page }) => {28 await login(page);29 await expect(page.getByRole("heading", { name: "Chaînes canadiennes" })).toBeVisible();30 await expect(page.getByRole("heading", { name: "Chaînes françaises" })).toBeVisible();31 await expect(page.getByRole("heading", { name: "Informations et actualités" })).toBeVisible();32 const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);33 expect(overflow).toBeLessThanOrEqual(1);34 const cookies = await page.context().cookies();35 const s = cookies.find((c) => c.name.endsWith("sptv"))!;36 expect(s.httpOnly).toBe(true); expect(s.sameSite).toBe("Lax");37 if (new URL(page.url()).protocol === "https:") { expect(s.secure).toBe(true); expect(s.name).toBe("__Host-sptv"); }38});3940test("recherche tolérante aux fautes et filtres", async ({ page }) => {41 await login(page);42 await page.goto("/chaines");43 await page.getByLabel("Rechercher une chaîne").fill("frnace 24");44 await expect(page.getByRole("button", { name: /^France 24 —/ }).first()).toBeVisible();45 await page.getByLabel("Rechercher une chaîne").fill("");46 await page.getByLabel("Pays").selectOption("CA");47 await expect(page).toHaveURL(/country=CA/);48 await expect(page.getByText(/\d+ chaînes? sur/)).toBeVisible();49 const r = await apiGet<{ total: number; items: { country: string }[]; tookMs: number }>(page, "/channels?country=CA&limit=200");50 expect(r.total).toBeGreaterThan(50); expect(r.items.every((c) => c.country === "CA")).toBe(true);51 const all = await apiGet<{ total: number; tookMs: number }>(page, "/channels?q=news&limit=60");52 expect(all.tookMs).toBeLessThan(150);53});5455test("favoris persistants après rechargement et nouvelle session", async ({ page, browser }) => {56 await login(page);57 const { items } = await apiGet<{ items: Ch[] }>(page, "/channels?country=CA&limit=3");58 const target = items[1];59 await page.evaluate(async (id) => { await fetch("/api/favorites", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ channelId: id, on: false }) }); }, target.id);60 await page.goto(`/chaines?q=${encodeURIComponent(target.name)}`);61 await page.getByRole("button", { name: `Ajouter ${target.name} aux favoris` }).first().click();62 await expect(page.getByRole("button", { name: `Retirer ${target.name} des favoris` }).first()).toBeVisible();63 await page.goto("/favoris");64 await expect(page.getByRole("button", { name: new RegExp(`^${target.name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} —`) })).toBeVisible();65 const ctx = await browser.newContext({ baseURL: test.info().project.use.baseURL }); const p2 = await ctx.newPage();66 await login(p2);67 const fav = await apiGet<{ items: Ch[] }>(p2, "/lists/1");68 expect(fav.items.map((c) => c.id)).toContain(target.id);69 await ctx.close();70 await page.evaluate(async (id) => { await fetch("/api/favorites", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ channelId: id, on: false }) }); }, target.id);71});7273test("lecture réelle de flux publics, zapping sans rechargement", async ({ page }, info) => {74 test.skip(!canDecode(info.project.name), "Chromium de Playwright : pas de décodeur H.264");75 await login(page);76 await page.evaluate(() => { (window as unknown as { __marker: number }).__marker = 42; });77 const { items } = await apiGet<{ items: Ch[] }>(page, "/channels?status=up&web=1&category=news&limit=40");78 expect(items.length).toBeGreaterThan(3);79 await page.goto("/chaines?status=up&web=1&category=news");80 await page.evaluate(() => { (window as unknown as { __marker: number }).__marker = 42; });81 const played: string[] = [], failed: string[] = [];82 for (const c of items.slice(0, 6)) {83 if (played.length >= 2) break;84 const card = page.getByRole("button", { name: `${c.name} — Disponible lors du dernier test`, exact: true }).first();85 if (played.length + failed.length === 0) await card.click();86 else await page.keyboard.press("ArrowUp"); // zap to the next channel of the list87 // Real playback = decoded frames and a clock that advances (a live stream starts at a non-zero position, so the position alone proves nothing).88 await page.evaluate(() => { (window as unknown as { __t0?: number }).__t0 = undefined; });89 const ok = await page.waitForFunction(() => {90 const v = document.querySelector("video"); const w = window as unknown as { __t0?: number };91 if (!v || v.paused || v.readyState < 3 || !v.videoWidth) { w.__t0 = undefined; return false; }92 w.__t0 ??= v.currentTime; return v.currentTime - w.__t0 > 2;93 }, null, { timeout: 30_000, polling: 250 }).then(() => true, () => false);94 if (!ok) console.log("état vidéo :", await page.evaluate(() => { const v = document.querySelector("video")!; return { rs: v.readyState, paused: v.paused, t: v.currentTime, w: v.videoWidth, t0: (window as unknown as { __t0?: number }).__t0, mode: document.querySelector("[data-player]")?.getAttribute("data-player"), alert: document.querySelector("[data-player] [role=alert] h2")?.textContent }; }));95 const name = await page.locator('[data-player="full"] h2').first().innerText().catch(() => c.name);96 (ok ? played : failed).push(name.trim());97 }98 info.annotations.push({ type: "lecture", description: `lues : ${played.join(", ") || "aucune"} · non lues : ${failed.join(", ") || "aucune"}` });99 console.log(`[${info.project.name}] lues : ${played.join(" | ")} — non lues : ${failed.join(" | ")}`);100 expect(played.length, "au moins un flux public doit être lu").toBeGreaterThanOrEqual(1);101 expect(await page.evaluate(() => (window as unknown as { __marker?: number }).__marker)).toBe(42); // page never reloaded102 await expect.poll(async () => (await apiGet<{ last: Ch | null }>(page, "/home")).last?.name, { timeout: 10_000 }).toBeTruthy(); // last watched channel recorded103});104105test("flux indisponible : erreur expliquée, pas de chargement infini", async ({ page }) => {106 await login(page);107 const { items } = await apiGet<{ items: Ch[] }>(page, "/channels?status=down&limit=5");108 test.skip(!items.length, "aucun flux indisponible connu pour l'instant");109 await page.goto(`/chaines?status=down&q=${encodeURIComponent(items[0].name)}`);110 await page.getByRole("button", { name: `${items[0].name} — Indisponible lors du dernier test`, exact: true }).first().click();111 const alert = page.locator('[data-player="full"] [role="alert"]');112 await expect(alert).toBeVisible({ timeout: 60_000 });113 await expect(alert.getByRole("button", { name: "Réessayer" })).toBeVisible();114 await expect(alert.getByRole("button", { name: /Tester le flux maintenant/ })).toBeVisible();115 expect((await alert.innerText()).length).toBeGreaterThan(60);116});117118test("navigation au clavier / télécommande", async ({ page }, info) => {119 test.skip(info.project.name.includes("iphone"), "écran tactile");120 await login(page);121 await page.goto("/chaines?country=FR");122 await expect(page.locator("main button[data-nav]").first()).toBeVisible();123 await page.getByLabel("Rechercher une chaîne").focus();124 await page.keyboard.press("ArrowDown"); // → first filter (a select: ↑/↓ change its value, ←/→ leave it)125 for (let i = 0; i < 4; i++) await page.keyboard.press("ArrowRight"); // → « Favoris » chip126 await page.keyboard.press("ArrowDown"); // → a channel card127 const first = await page.evaluate(() => document.activeElement?.getAttribute("aria-label") ?? document.activeElement?.tagName);128 expect(first).toMatch(/ — /);129 await page.keyboard.press("ArrowRight");130 let second = await page.evaluate(() => document.activeElement?.getAttribute("aria-label"));131 if (second === first) { await page.keyboard.press("ArrowLeft"); second = await page.evaluate(() => document.activeElement?.getAttribute("aria-label")); } // card was in the last column132 expect(second).toBeTruthy(); expect(second).not.toBe(first);133 const outline = await page.evaluate(() => getComputedStyle(document.activeElement!).outlineStyle);134 expect(outline).not.toBe("none");135 await page.keyboard.press("Enter");136 await expect(page.locator('[data-player="full"]')).toBeVisible();137 await page.keyboard.press("Escape");138 await expect(page.locator('[data-player="mini"]')).toBeVisible();139 await page.getByRole("button", { name: "Fermer le lecteur" }).click();140 await expect(page.locator("[data-player]")).toBeHidden();141});142143test("guide TV : données réelles ou indisponibilité déclarée", async ({ page }) => {144 await login(page);145 const g = await apiGet<{ channels: Ch[]; programmes: Record<string, { title: string; start: number; stop: number }[]>; withData: number }>(page, "/guide");146 await page.goto("/guide");147 if (g.withData > 0) {148 const [id, progs] = Object.entries(g.programmes)[0];149 expect(id).toBeTruthy(); expect(progs[0].stop).toBeGreaterThan(progs[0].start);150 await expect(page.getByText(/chaînes? avec programmes/)).toBeVisible();151 await expect(page.getByRole("button", { name: /^Regarder / }).first()).toBeVisible();152 } else await expect(page.getByText("Aucun programme disponible pour l'instant")).toBeVisible();153 await page.getByRole("tab", { name: "Favoris" }).click();154 await expect(page.getByText(/Programme indisponible|Aucun favori/).first()).toBeVisible();155});156157test("administration : statistiques, SSRF refusé, journaux", async ({ page }) => {158 await login(page);159 await page.goto("/admin");160 await expect(page.getByText("Disponibles au dernier test", { exact: true })).toBeVisible();161 await expect(page.getByRole("button", { name: "Synchroniser maintenant" })).toBeVisible();162 for (const url of ["http://192.168.2.1/list.m3u", "http://127.0.0.1:8670/api/health", "http://localhost/x.m3u", "file:///etc/passwd", "http://169.254.169.254/latest/meta-data"]) {163 const r = await page.evaluate(async (u) => { const res = await fetch("/api/admin/sources", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "test ssrf", url: u, authorized: true }) }); return { status: res.status, body: await res.json() }; }, url);164 expect(r.status, url).toBe(400);165 }166 const noConsent = await page.evaluate(async () => (await fetch("/api/admin/sources", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ name: "x", url: "https://example.org/a.m3u" }) })).status);167 expect(noConsent).toBe(400);168 await page.getByRole("tab", { name: "Journaux" }).click();169 await expect(page.getByText(/Connexion réussie/).first()).toBeVisible();170 await page.getByRole("tab", { name: "Sécurité" }).click();171 await expect(page.getByText("Cette session")).toBeVisible();172});173174test("déconnexion", async ({ page }) => {175 await login(page);176 await page.evaluate(async () => { await fetch("/api/auth/logout", { method: "POST" }); });177 await page.goto("/favoris", { waitUntil: "commit" }).catch(() => {});178 await expect(page).toHaveURL(/\/connexion/);179});180