gradio-pr-bot commited on
Commit
137dd73
·
verified ·
1 Parent(s): 8876ade

Upload folder using huggingface_hub

Browse files
6.14.1/tootils/package.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@self/tootils",
3
+ "version": "0.14.0",
4
+ "description": "Internal test utilities",
5
+ "type": "module",
6
+ "main": "src/index.ts",
7
+ "author": "",
8
+ "license": "ISC",
9
+ "private": true,
10
+ "dependencies": {
11
+ "@gradio/statustracker": "workspace:^",
12
+ "@gradio/utils": "workspace:^"
13
+ },
14
+ "peerDependencies": {
15
+ "svelte": "^5.48.0"
16
+ },
17
+ "exports": {
18
+ ".": "./src/index.ts",
19
+ "./render": "./src/render.ts",
20
+ "./shared-prop-tests": "./src/shared-prop-tests.ts",
21
+ "./app-launcher": "./src/app-launcher.ts",
22
+ "./download-command": "./src/download-command.ts"
23
+ },
24
+ "scripts": {
25
+ "package": "svelte-package --input=. --tsconfig=../../tsconfig.json"
26
+ }
27
+ }
6.14.1/tootils/src/app-launcher.ts ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { spawn, spawnSync, type ChildProcess } from "node:child_process";
2
+ import http from "http";
3
+ import net from "net";
4
+ import path from "path";
5
+ import fs from "fs";
6
+ import os from "os";
7
+ import url from "url";
8
+
9
+ const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
10
+ const ROOT_DIR = path.resolve(__dirname, "../../..");
11
+
12
+ export interface GradioApp {
13
+ port: number;
14
+ process: ChildProcess;
15
+ }
16
+
17
+ export function killGradioApp(process: ChildProcess): void {
18
+ try {
19
+ process.kill("SIGTERM");
20
+ } catch {
21
+ // Process may already be dead
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Sweep orphaned gradio demo python processes — i.e. processes running
27
+ * `python <demo>/run.py` whose parent has died (PPID == 1, reparented to
28
+ * init/launchd). Without this, a Playwright worker that crashes (e.g.
29
+ * after a test timeout) leaves its spawned demo apps behind: the new
30
+ * worker has an empty appCache and won't kill them, ports get squatted,
31
+ * and resources accumulate. Documented behavior, not a guess: in the SSR
32
+ * profile run, this orphaning produced 100+ leaked python procs / 7.5GB.
33
+ *
34
+ * Best-effort: failures in the sweep are swallowed so they can't block
35
+ * the spawn path itself.
36
+ */
37
+ function reapOrphanedDemos(): void {
38
+ try {
39
+ const result = spawnSync("ps", ["-A", "-o", "pid=,ppid=,command="], {
40
+ encoding: "utf8"
41
+ });
42
+ if (result.status !== 0 || !result.stdout) return;
43
+
44
+ for (const line of result.stdout.split("\n")) {
45
+ const trimmed = line.trim();
46
+ if (!trimmed) continue;
47
+ const match = trimmed.match(/^(\d+)\s+(\d+)\s+(.*)$/);
48
+ if (!match) continue;
49
+ const [, pidStr, ppidStr, cmd] = match;
50
+ if (ppidStr !== "1") continue;
51
+ // Only target our test demo apps (python running gradio demo files).
52
+ // Match `gradio/.../demo/<name>/<file>.py` to avoid accidentally
53
+ // killing unrelated python processes.
54
+ if (!/python.*\/demo\/[^/]+\/[^/]+\.py/.test(cmd)) continue;
55
+ if (!cmd.includes("/gradio/")) continue;
56
+ try {
57
+ process.kill(Number(pidStr), "SIGTERM");
58
+ } catch {
59
+ // already dead, or not ours to kill
60
+ }
61
+ }
62
+ } catch {
63
+ // ps unavailable or parse error — non-fatal
64
+ }
65
+ }
66
+
67
+ export async function findFreePort(
68
+ startPort: number,
69
+ endPort: number
70
+ ): Promise<number> {
71
+ for (let port = startPort; port < endPort; port++) {
72
+ if (await isPortFree(port)) {
73
+ return port;
74
+ }
75
+ }
76
+ throw new Error(`Could not find free port in range ${startPort}-${endPort}`);
77
+ }
78
+
79
+ function isPortFree(port: number): Promise<boolean> {
80
+ return new Promise((resolve) => {
81
+ const sock = net.createConnection(port, "127.0.0.1");
82
+ sock.once("connect", () => {
83
+ sock.end();
84
+ resolve(false);
85
+ });
86
+ sock.once("error", (e: NodeJS.ErrnoException) => {
87
+ sock.destroy();
88
+ // ECONNREFUSED → no listener (free). Anything else (ECONNRESET from
89
+ // a half-closed socket left by a SIGTERM'd demo, ETIMEDOUT, etc.)
90
+ // → don't trust the port, skip to the next one. Previously we
91
+ // rejected on non-ECONNREFUSED errors, which aborted the whole
92
+ // findFreePort scan and surfaced as "Failed to launch app".
93
+ resolve(e.code === "ECONNREFUSED");
94
+ });
95
+ });
96
+ }
97
+
98
+ /**
99
+ * Poll the server with HTTP GET requests until it returns a response.
100
+ * Gradio prints "Running on local URL:" before the server is fully ready,
101
+ * so we need to verify it actually responds to HTTP requests.
102
+ */
103
+ async function waitForServerReady(
104
+ port: number,
105
+ timeoutMs: number = 15000
106
+ ): Promise<void> {
107
+ const start = Date.now();
108
+ const pollInterval = 200;
109
+
110
+ while (Date.now() - start < timeoutMs) {
111
+ try {
112
+ await new Promise<void>((resolve, reject) => {
113
+ // Use HEAD on /gradio_api/info to avoid triggering SSR rendering on
114
+ // the root URL, which could block Gradio's own startup health check.
115
+ const req = http.request(
116
+ `http://127.0.0.1:${port}/gradio_api/info`,
117
+ { method: "HEAD", timeout: 2000 },
118
+ (res) => {
119
+ res.resume(); // drain the response
120
+ resolve();
121
+ }
122
+ );
123
+ req.on("error", reject);
124
+ req.on("timeout", () => {
125
+ req.destroy();
126
+ reject(new Error("request timeout"));
127
+ });
128
+ req.end();
129
+ });
130
+ return; // Server responded successfully
131
+ } catch {
132
+ // Server not ready yet, wait and retry
133
+ await new Promise((r) => setTimeout(r, pollInterval));
134
+ }
135
+ }
136
+ throw new Error(
137
+ `Server on port ${port} did not become ready within ${timeoutMs}ms`
138
+ );
139
+ }
140
+
141
+ export function getTestcases(demoName: string): string[] {
142
+ const demoDir = path.join(ROOT_DIR, "demo", demoName);
143
+ if (!fs.existsSync(demoDir)) {
144
+ return [];
145
+ }
146
+
147
+ return fs
148
+ .readdirSync(demoDir)
149
+ .filter((f) => f.endsWith("_testcase.py"))
150
+ .map((f) => path.basename(f, ".py"));
151
+ }
152
+
153
+ // Check if a testcase file exists for this demo
154
+ export function hasTestcase(demoName: string, testcaseName: string): boolean {
155
+ const testcaseFile = path.join(
156
+ ROOT_DIR,
157
+ "demo",
158
+ demoName,
159
+ `${testcaseName}_testcase.py`
160
+ );
161
+ return fs.existsSync(testcaseFile);
162
+ }
163
+
164
+ // Get the path to a demo's Python file
165
+ function getDemoFilePath(demoName: string, testcaseName?: string): string {
166
+ if (testcaseName) {
167
+ return path.join(ROOT_DIR, "demo", demoName, `${testcaseName}_testcase.py`);
168
+ }
169
+ return path.join(ROOT_DIR, "demo", demoName, "run.py");
170
+ }
171
+
172
+ export async function launchGradioApp(
173
+ demoName: string,
174
+ workerIndex: number = 0,
175
+ timeout: number = 60000,
176
+ testcaseName?: string
177
+ ): Promise<GradioApp> {
178
+ // Sweep orphaned demo apps from previous (crashed) worker generations
179
+ // before claiming a port — see reapOrphanedDemos() for rationale.
180
+ reapOrphanedDemos();
181
+
182
+ // Partition ports by worker index to avoid collisions
183
+ const basePort = 7860 + workerIndex * 100;
184
+ const port = await findFreePort(basePort, basePort + 99);
185
+
186
+ // Get the path to the demo file
187
+ const demoFilePath = getDemoFilePath(demoName, testcaseName);
188
+
189
+ // Create unique directories for this instance to avoid cache conflicts
190
+ const instanceId = testcaseName
191
+ ? `${demoName}_${testcaseName}_${port}`
192
+ : `${demoName}_${port}`;
193
+ const instanceDir = path.join(os.tmpdir(), `gradio_test_${instanceId}`);
194
+ const cacheDir = path.join(instanceDir, "cached_examples");
195
+ const tempDir = path.join(instanceDir, "temp");
196
+
197
+ if (!fs.existsSync(instanceDir)) {
198
+ fs.mkdirSync(instanceDir, { recursive: true });
199
+ }
200
+
201
+ // Run the demo via _demo_runner.py instead of directly. The wrapper
202
+ // watches its stdin pipe: if the playwright worker that spawned us
203
+ // dies (cleanly or via SIGKILL on timeout), the kernel closes the pipe,
204
+ // stdin returns EOF and the demo self-exits immediately — instead of
205
+ // becoming an orphan that survives the rest of the suite.
206
+ const demoRunnerPath = path.join(__dirname, "_demo_runner.py");
207
+ const childProcess = spawn("python", [demoRunnerPath, demoFilePath], {
208
+ stdio: "pipe",
209
+ cwd: ROOT_DIR,
210
+ env: {
211
+ ...process.env,
212
+ PYTHONUNBUFFERED: "true",
213
+ GRADIO_ANALYTICS_ENABLED: "False",
214
+ GRADIO_IS_E2E_TEST: "1",
215
+ GRADIO_RESET_EXAMPLES_CACHE: "True",
216
+ // Control the port via environment variable
217
+ GRADIO_SERVER_PORT: port.toString(),
218
+ // Use unique directories per instance to avoid conflicts
219
+ GRADIO_EXAMPLES_CACHE: cacheDir,
220
+ GRADIO_TEMP_DIR: tempDir
221
+ }
222
+ });
223
+
224
+ childProcess.stdout?.setEncoding("utf8");
225
+ childProcess.stderr?.setEncoding("utf8");
226
+
227
+ // Wait for app to be ready
228
+ return new Promise<GradioApp>((resolve, reject) => {
229
+ const timeoutId = setTimeout(() => {
230
+ killGradioApp(childProcess);
231
+ reject(
232
+ new Error(`Gradio app ${demoName} failed to start within ${timeout}ms`)
233
+ );
234
+ }, timeout);
235
+
236
+ let output = "";
237
+ let startupDetected = false;
238
+
239
+ function handleOutput(data: string): void {
240
+ output += data;
241
+ // Check for Gradio's startup message
242
+ if (
243
+ !startupDetected &&
244
+ (data.includes("Running on local URL:") ||
245
+ data.includes(`Uvicorn running on`))
246
+ ) {
247
+ startupDetected = true;
248
+ clearTimeout(timeoutId);
249
+ // The startup message is printed before the server is fully ready.
250
+ // Poll with HTTP requests to ensure it actually responds.
251
+ waitForServerReady(port)
252
+ .then(() => resolve({ port, process: childProcess }))
253
+ .catch(reject);
254
+ }
255
+ }
256
+
257
+ childProcess.stdout?.on("data", handleOutput);
258
+ childProcess.stderr?.on("data", handleOutput);
259
+
260
+ childProcess.on("error", (err) => {
261
+ clearTimeout(timeoutId);
262
+ reject(err);
263
+ });
264
+
265
+ childProcess.on("exit", (code) => {
266
+ if (code !== 0 && code !== null) {
267
+ clearTimeout(timeoutId);
268
+ reject(
269
+ new Error(
270
+ `Gradio app ${demoName} exited with code ${code}.\nOutput: ${output}`
271
+ )
272
+ );
273
+ }
274
+ });
275
+ });
276
+ }
6.14.1/tootils/src/download-command.ts ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { BrowserCommand } from "vitest/node";
2
+ import { resolve } from "path";
3
+ import { readFile } from "fs/promises";
4
+
5
+ /**
6
+ * Vitest browser command that captures a real file download triggered by
7
+ * clicking an element. Runs server-side with access to the Playwright page.
8
+ *
9
+ * Sets up page.waitForEvent("download") BEFORE clicking, so the download
10
+ * event is never missed.
11
+ */
12
+ export const expect_download: BrowserCommand<
13
+ [selector: string, options?: { timeout?: number }],
14
+ { suggested_filename: string; content: string | null }
15
+ > = async (context, selector, options) => {
16
+ const timeout = options?.timeout ?? 5000;
17
+ const provider = context.provider as any;
18
+ const page = provider.getPage(context.sessionId);
19
+ // Tests run inside an iframe; use the iframe locator to click
20
+ // but listen for the download event on the parent page.
21
+ const iframe = (context as any).iframe;
22
+
23
+ const [download] = await Promise.all([
24
+ page.waitForEvent("download", { timeout }),
25
+ iframe.locator(selector).click()
26
+ ]);
27
+
28
+ const suggested_filename = download.suggestedFilename();
29
+ const path = await download.path();
30
+
31
+ let content: string | null = null;
32
+ if (path) {
33
+ const fs = await import("fs/promises");
34
+ content = await fs.readFile(path, "utf-8");
35
+ }
36
+
37
+ return {
38
+ suggested_filename,
39
+ content
40
+ };
41
+ };
42
+
43
+ /**
44
+ * Vitest browser command that sets files on an <input type="file"> element.
45
+ * Resolves fixture URL paths (e.g. "/test/test_files/bus.png") to absolute
46
+ * disk paths and uses Playwright's setInputFiles().
47
+ */
48
+ export const set_file_inputs: BrowserCommand<
49
+ [file_urls: string[], selector?: string]
50
+ > = async (context, file_urls, selector) => {
51
+ const root = context.project.config.root;
52
+ const iframe = (context as any).iframe;
53
+
54
+ const paths = file_urls.map((url) => resolve(root, url.replace(/^\//, "")));
55
+
56
+ await iframe
57
+ .locator(selector ?? 'input[type="file"]')
58
+ .first()
59
+ .setInputFiles(paths);
60
+ };
61
+
62
+ interface Drop_file_spec {
63
+ data: string; // base64
64
+ name: string;
65
+ mime_type: string;
66
+ }
67
+
68
+ /**
69
+ * Vitest browser command that simulates dropping files onto an element.
70
+ * Reads files from disk, transfers them as base64 into the browser context,
71
+ * and dispatches dragenter, dragover, and drop events with a real DataTransfer.
72
+ */
73
+ export const drop_files: BrowserCommand<
74
+ [file_urls: string[], selector: string]
75
+ > = async (context, file_urls, selector) => {
76
+ const root = context.project.config.root;
77
+
78
+ const files: Drop_file_spec[] = await Promise.all(
79
+ file_urls.map(async (url) => {
80
+ const abs = resolve(root, url.replace(/^\//, ""));
81
+ const data = (await readFile(abs)).toString("base64");
82
+ const name = abs.split("/").pop()!;
83
+ const ext = name.split(".").pop()!.toLowerCase();
84
+ const mime_type = MIME_TYPES[ext] || "application/octet-stream";
85
+ return { data, name, mime_type };
86
+ })
87
+ );
88
+
89
+ const iframe = (context as any).iframe;
90
+ await iframe
91
+ .locator(selector)
92
+ .first()
93
+ .evaluate((target: Element, files: Drop_file_spec[]) => {
94
+ const dt = new DataTransfer();
95
+ for (const f of files) {
96
+ const bytes = Uint8Array.from(atob(f.data), (c) => c.charCodeAt(0));
97
+ dt.items.add(new File([bytes], f.name, { type: f.mime_type }));
98
+ }
99
+
100
+ target.dispatchEvent(
101
+ new DragEvent("dragenter", {
102
+ dataTransfer: dt,
103
+ bubbles: true
104
+ })
105
+ );
106
+ target.dispatchEvent(
107
+ new DragEvent("dragover", {
108
+ dataTransfer: dt,
109
+ bubbles: true
110
+ })
111
+ );
112
+ target.dispatchEvent(
113
+ new DragEvent("drop", { dataTransfer: dt, bubbles: true })
114
+ );
115
+ }, files);
116
+ };
117
+
118
+ const MIME_TYPES: Record<string, string> = {
119
+ txt: "text/plain",
120
+ csv: "text/csv",
121
+ json: "application/json",
122
+ pdf: "application/pdf",
123
+ jpg: "image/jpeg",
124
+ jpeg: "image/jpeg",
125
+ png: "image/png",
126
+ gif: "image/gif",
127
+ webp: "image/webp",
128
+ svg: "image/svg+xml",
129
+ mp4: "video/mp4",
130
+ webm: "video/webm",
131
+ ogg: "video/ogg",
132
+ avi: "video/x-msvideo",
133
+ wav: "audio/wav",
134
+ mp3: "audio/mpeg",
135
+ flac: "audio/flac"
136
+ };
6.14.1/tootils/src/download.ts ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { commands } from "vitest/browser";
2
+ import type { FileData } from "@gradio/client";
3
+
4
+ export interface DownloadResult {
5
+ suggested_filename: string;
6
+ content: string | null;
7
+ }
8
+
9
+ /**
10
+ * Clicks an element and captures the resulting file download.
11
+ *
12
+ * Uses a real browser download via Playwright under the hood —
13
+ * the file is actually downloaded and its content is readable.
14
+ *
15
+ * @param selector - CSS selector for the element to click
16
+ * @param options - Optional timeout (default 5000ms)
17
+ * @returns The downloaded file's suggested filename and text content
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const { suggested_filename, content } = await download_file("a.download-link");
22
+ * expect(suggested_filename).toBe("data.csv");
23
+ * expect(content).toContain("col1,col2");
24
+ * ```
25
+ */
26
+ export async function download_file(
27
+ selector: string,
28
+ options?: { timeout?: number }
29
+ ): Promise<DownloadResult> {
30
+ return (commands as any).expect_download(selector, options);
31
+ }
32
+
33
+ /**
34
+ * Sets files on an `<input type="file">` element using real file fixtures.
35
+ *
36
+ * Accepts one or more FileData fixtures (e.g. TEST_JPG, TEST_PNG) and
37
+ * sets them on the file input, triggering the browser's native change event.
38
+ *
39
+ * @param files - One or more FileData fixtures to upload
40
+ * @param selector - CSS selector for the file input (default: 'input[type="file"]')
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { render, upload_file, TEST_JPG } from "@self/tootils/render";
45
+ *
46
+ * const { listen } = await render(ImageUpload, { interactive: true });
47
+ * const upload = listen("upload");
48
+ *
49
+ * await upload_file(TEST_JPG);
50
+ *
51
+ * expect(upload).toHaveBeenCalled();
52
+ * ```
53
+ */
54
+ export async function upload_file(
55
+ files: FileData | FileData[],
56
+ selector?: string
57
+ ): Promise<void> {
58
+ const file_list = Array.isArray(files) ? files : [files];
59
+ const urls = file_list.map((f) => f.url ?? f.path);
60
+ return (commands as any).set_file_inputs(urls, selector);
61
+ }
62
+
63
+ /**
64
+ * Simulates dragging and dropping files onto an element.
65
+ *
66
+ * Reads the fixture files from disk, constructs a real DataTransfer
67
+ * with File objects, and dispatches dragenter, dragover, and drop events
68
+ * on the target element.
69
+ *
70
+ * @param files - One or more FileData fixtures to drop
71
+ * @param selector - CSS selector for the drop target element
72
+ *
73
+ * @example
74
+ * ```ts
75
+ * import { render, drop_file, TEST_JPG } from "@self/tootils/render";
76
+ *
77
+ * const { listen } = await render(ImageUpload, { interactive: true });
78
+ * const upload = listen("upload");
79
+ *
80
+ * await drop_file(TEST_JPG, "[aria-label='Click to upload or drop files']");
81
+ *
82
+ * await vi.waitFor(() => expect(upload).toHaveBeenCalled());
83
+ * ```
84
+ */
85
+ export async function drop_file(
86
+ files: FileData | FileData[],
87
+ selector: string
88
+ ): Promise<void> {
89
+ const file_list = Array.isArray(files) ? files : [files];
90
+ const urls = file_list.map((f) => f.url ?? f.path);
91
+ return (commands as any).drop_files(urls, selector);
92
+ }
6.14.1/tootils/src/fixtures.ts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { FileData } from "@gradio/client";
2
+
3
+ const BASE = "/test/test_files";
4
+
5
+ function fixture(filename: string, mime_type: string, size: number): FileData {
6
+ const url = `${BASE}/${filename}`;
7
+ return new FileData({
8
+ path: url,
9
+ url,
10
+ orig_name: filename,
11
+ size,
12
+ mime_type
13
+ });
14
+ }
15
+
16
+ export const TEST_TXT = fixture("alphabet.txt", "text/plain", 26);
17
+ export const TEST_JPG = fixture("cheetah1.jpg", "image/jpeg", 20552);
18
+ export const TEST_PNG = fixture("bus.png", "image/png", 1951);
19
+ export const TEST_MP4 = fixture("video_sample.mp4", "video/mp4", 261179);
20
+ export const TEST_WAV = fixture("audio_sample.wav", "audio/wav", 16136);
21
+ export const TEST_PDF = fixture("sample_file.pdf", "application/pdf", 10558);
22
+ export const TEST_GLTF = fixture("Box.gltf", "model/gltf+json", 5249);
23
+ export const TEST_PLY = fixture("model.ply", "application/octet-stream", 413);
24
+ export const TEST_SPLAT = fixture(
25
+ "model.splat",
26
+ "application/octet-stream",
27
+ 32
28
+ );
6.14.1/tootils/src/index.ts ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test as base, type Locator, type Page } from "@playwright/test";
2
+ import { spy } from "tinyspy";
3
+ import url from "url";
4
+ import path from "path";
5
+ import fsPromises from "fs/promises";
6
+ import type { ChildProcess } from "node:child_process";
7
+
8
+ import type { SvelteComponent } from "svelte";
9
+ import type { SpyFn } from "tinyspy";
10
+
11
+ import { launchGradioApp, killGradioApp, hasTestcase } from "./app-launcher";
12
+
13
+ export function get_text<T extends HTMLElement>(el: T): string {
14
+ return el.innerText.trim();
15
+ }
16
+
17
+ export function wait(n: number): Promise<void> {
18
+ return new Promise((r) => setTimeout(r, n));
19
+ }
20
+
21
+ const ROOT_DIR = path.resolve(
22
+ url.fileURLToPath(import.meta.url),
23
+ "../../../.."
24
+ );
25
+
26
+ // Extract testcase name from test title if present
27
+ // Test titles can be:
28
+ // - "case eager_caching_examples: ..."
29
+ // - "test case multimodal_messages chatinterface works..."
30
+ function extractTestcaseFromTitle(
31
+ title: string,
32
+ demoName: string
33
+ ): string | undefined {
34
+ // Try pattern: "case <name>:" or "test case <name> "
35
+ const patterns = [/^case\s+(\w+):/, /^test case\s+(\w+)\s/];
36
+
37
+ for (const pattern of patterns) {
38
+ const match = title.match(pattern);
39
+ if (match) {
40
+ const caseName = match[1];
41
+ // Check if this is a testcase (not the main demo)
42
+ if (hasTestcase(demoName, caseName)) {
43
+ return caseName;
44
+ }
45
+ }
46
+ }
47
+ return undefined;
48
+ }
49
+
50
+ // Cache for launched apps - key is "demoName" or "demoName_testcaseName"
51
+ const appCache = new Map<
52
+ string,
53
+ { port: number; process: ChildProcess; refCount: number }
54
+ >();
55
+
56
+ // Track the cacheKey of the currently-running spec file so we can kill the
57
+ // previous spec's gradio app when the worker moves on. Without this, every
58
+ // app spawned during a worker's lifetime stayed resident until process exit
59
+ // (~50 python procs / 5GB RSS by end of suite — the tail of the run starved
60
+ // for CPU and tests timed out).
61
+ let currentCacheKey: string | null = null;
62
+
63
+ function killAndEvict(cacheKey: string): void {
64
+ const info = appCache.get(cacheKey);
65
+ if (!info) return;
66
+ killGradioApp(info.process);
67
+ appCache.delete(cacheKey);
68
+ }
69
+
70
+ // Test fixture that launches Gradio app per test
71
+ const test_normal = base.extend<{ setup: void }>({
72
+ setup: [
73
+ async ({ page }, use, testInfo): Promise<void> => {
74
+ const { file, title } = testInfo;
75
+ const demoName = path.basename(file, ".spec.ts");
76
+
77
+ // Check if this is a reload test (they manage their own apps)
78
+ if (demoName.endsWith(".reload")) {
79
+ // For reload tests, don't launch an app - they handle it themselves
80
+ await use();
81
+ return;
82
+ }
83
+
84
+ // Check if this test is for a specific testcase
85
+ const testcaseName = extractTestcaseFromTitle(title, demoName);
86
+
87
+ // Cache key includes testcase if present
88
+ const cacheKey = testcaseName ? `${demoName}_${testcaseName}` : demoName;
89
+
90
+ // First test of a new spec file → previous file's app is no longer
91
+ // needed on this worker. fullyParallel=false in playwright.config
92
+ // guarantees a worker finishes a file before starting the next, so
93
+ // the kill is unconditional on the transition (we don't gate on
94
+ // refCount: a throw before `await use()` — e.g. a flaky SSR
95
+ // hydration wait — can leak refCount, which would otherwise pin
96
+ // the previous spec's app forever).
97
+ if (currentCacheKey !== null && currentCacheKey !== cacheKey) {
98
+ killAndEvict(currentCacheKey);
99
+ }
100
+ currentCacheKey = cacheKey;
101
+
102
+ let appInfo = appCache.get(cacheKey);
103
+
104
+ if (!appInfo) {
105
+ // Launch the app for this test
106
+ const workerIndex = testInfo.workerIndex;
107
+ try {
108
+ const { port, process } = await launchGradioApp(
109
+ demoName,
110
+ workerIndex,
111
+ 60000,
112
+ testcaseName
113
+ );
114
+ appInfo = { port, process, refCount: 0 };
115
+ appCache.set(cacheKey, appInfo);
116
+ } catch (error) {
117
+ console.error(`Failed to launch app for ${cacheKey}:`, error);
118
+ throw error;
119
+ }
120
+ }
121
+
122
+ try {
123
+ // Navigate to the app
124
+ await page.goto(`http://localhost:${appInfo.port}`);
125
+
126
+ if (
127
+ process.env?.GRADIO_SSR_MODE?.toLowerCase() === "true" &&
128
+ !(
129
+ demoName.includes("multipage") ||
130
+ demoName.includes("chatinterface_deep_link")
131
+ )
132
+ ) {
133
+ await page.waitForSelector("#svelte-announcer");
134
+ }
135
+ await page.waitForLoadState("load");
136
+
137
+ await use();
138
+ } finally {
139
+ }
140
+ },
141
+ { auto: true }
142
+ ]
143
+ });
144
+
145
+ // Cleanup apps when the process exits
146
+ process.on("exit", () => {
147
+ for (const [, appInfo] of appCache) {
148
+ killGradioApp(appInfo.process);
149
+ }
150
+ });
151
+
152
+ process.on("SIGINT", () => {
153
+ for (const [, appInfo] of appCache) {
154
+ killGradioApp(appInfo.process);
155
+ }
156
+ process.exit(0);
157
+ });
158
+
159
+ process.on("SIGTERM", () => {
160
+ for (const [, appInfo] of appCache) {
161
+ killGradioApp(appInfo.process);
162
+ }
163
+ process.exit(0);
164
+ });
165
+
166
+ export const test = test_normal;
167
+
168
+ export async function wait_for_event(
169
+ component: SvelteComponent,
170
+ event: string
171
+ ): Promise<SpyFn> {
172
+ const mock = spy();
173
+ return new Promise((res) => {
174
+ component.$on(event, () => {
175
+ mock();
176
+ res(mock);
177
+ });
178
+ });
179
+ }
180
+
181
+ export interface ActionReturn<
182
+ Parameter = never,
183
+ Attributes extends Record<string, any> = Record<never, any>
184
+ > {
185
+ update?: [Parameter] extends [never] ? never : (parameter: Parameter) => void;
186
+ destroy?: () => void;
187
+ /**
188
+ * ### DO NOT USE THIS
189
+ * This exists solely for type-checking and has no effect at runtime.
190
+ * Set this through the `Attributes` generic instead.
191
+ */
192
+ $$_attributes?: Attributes;
193
+ }
194
+
195
+ export { expect } from "@playwright/test";
196
+
197
+ export const drag_and_drop_file = async (
198
+ page: Page,
199
+ selector: string | Locator,
200
+ filePath: string,
201
+ fileName: string,
202
+ fileType = "",
203
+ count = 1
204
+ ): Promise<void> => {
205
+ const buffer = (await fsPromises.readFile(filePath)).toString("base64");
206
+
207
+ const dataTransfer = await page.evaluateHandle(
208
+ async ({ bufferData, localFileName, localFileType, count }) => {
209
+ const dt = new DataTransfer();
210
+
211
+ const blobData = await fetch(bufferData).then((res) => res.blob());
212
+
213
+ const file = new File([blobData], localFileName, {
214
+ type: localFileType
215
+ });
216
+
217
+ for (let i = 0; i < count; i++) {
218
+ dt.items.add(file);
219
+ }
220
+ return dt;
221
+ },
222
+ {
223
+ bufferData: `data:application/octet-stream;base64,${buffer}`,
224
+ localFileName: fileName,
225
+ localFileType: fileType,
226
+ count
227
+ }
228
+ );
229
+
230
+ if (typeof selector === "string") {
231
+ await page.dispatchEvent(selector, "drop", { dataTransfer });
232
+ } else {
233
+ await selector.dispatchEvent("drop", { dataTransfer });
234
+ }
235
+ };
236
+
237
+ export async function go_to_testcase(
238
+ page: Page,
239
+ _test_case: string
240
+ ): Promise<void> {
241
+ // With the new setup, each testcase launches its own Gradio app.
242
+ // The fixture detects the testcase from the test title and launches
243
+ // the correct app, so this function is now a no-op.
244
+ // The page is already at the correct testcase app.
245
+ }
6.14.1/tootils/src/render.ts ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ getQueriesForElement,
3
+ prettyDOM,
4
+ fireEvent as dtlFireEvent
5
+ } from "@testing-library/dom";
6
+ import { tick, mount, unmount } from "svelte";
7
+ import type { SvelteComponent, Component } from "svelte";
8
+
9
+ import type {
10
+ queries,
11
+ Queries,
12
+ BoundFunction,
13
+ EventType
14
+ } from "@testing-library/dom";
15
+ import { vi, type Mock } from "vitest";
16
+ import { GRADIO_ROOT, allowed_shared_props } from "@gradio/utils";
17
+ import type { LoadingStatus, ILoadingStatus } from "@gradio/statustracker";
18
+ import { _ } from "svelte-i18n";
19
+
20
+ const containerCache = new Map();
21
+ const componentCache = new Set();
22
+
23
+ type ComponentType<T extends SvelteComponent, Props> = Component<Props>;
24
+
25
+ export type RenderResult<
26
+ C extends SvelteComponent,
27
+ Q extends Queries = typeof queries
28
+ > = {
29
+ container: HTMLElement;
30
+ component: C;
31
+ debug: (el?: HTMLElement | DocumentFragment) => void;
32
+ unmount: () => void;
33
+ } & { [P in keyof Q]: BoundFunction<Q[P]> };
34
+ export interface ILoadingStatus {
35
+ eta: number | null;
36
+ status: "pending" | "error" | "complete" | "generating" | "streaming";
37
+ queue: boolean;
38
+ queue_position: number | null;
39
+ queue_size?: number;
40
+ fn_index: number;
41
+ message?: string | null;
42
+ scroll_to_output?: boolean;
43
+ show_progress?: "full" | "minimal" | "hidden";
44
+ time_limit?: number | null | undefined;
45
+ progress?: {
46
+ progress: number | null;
47
+ index: number | null;
48
+ length: number | null;
49
+ unit: string | null;
50
+ desc: string | null;
51
+ }[];
52
+ validation_error?: string | null;
53
+ type: "input" | "output";
54
+ stream_state: "open" | "closed" | "waiting" | null;
55
+ }
56
+
57
+ const loading_status: ILoadingStatus = {
58
+ eta: 0,
59
+ queue_position: 1,
60
+ queue_size: 1,
61
+ queue: true,
62
+ message: null,
63
+ time_limit: null,
64
+ progress: [],
65
+ validation_error: null,
66
+ type: "output",
67
+ stream_state: null,
68
+ status: "complete" as ILoadingStatus["status"],
69
+ scroll_to_output: false,
70
+ fn_index: 0,
71
+ show_progress: "full" as ILoadingStatus["show_progress"]
72
+ };
73
+
74
+ export interface RenderOptions<Q extends Queries = typeof queries> {
75
+ container?: HTMLElement;
76
+ queries?: Q;
77
+ }
78
+
79
+ export async function render<
80
+ Events extends Record<string, any>,
81
+ Props extends Record<string, any>,
82
+ T extends SvelteComponent<Props, Events>,
83
+ X extends Record<string, any>
84
+ >(
85
+ Component: ComponentType<T, Props> | { default: ComponentType<T, Props> },
86
+ props?: Omit<Props, "gradio" | "loading_status"> & {
87
+ loading_status?: LoadingStatus;
88
+ },
89
+ options?: {
90
+ container?: HTMLElement;
91
+ }
92
+ ): Promise<
93
+ RenderResult<T> & {
94
+ listen: (event_name: string, opts?: { retrospective?: boolean }) => Mock;
95
+ set_data: (data: Record<string, any>) => Promise<void>;
96
+ get_data: () => Promise<Record<string, any>>;
97
+ }
98
+ > {
99
+ let container: HTMLElement;
100
+ if (!options?.container) {
101
+ container = document.body;
102
+ } else {
103
+ container = options.container;
104
+ }
105
+
106
+ const target = container.appendChild(document.createElement("div"));
107
+
108
+ const ComponentConstructor: ComponentType<T, Props> =
109
+ //@ts-ignore
110
+ Component.default || Component;
111
+
112
+ const id = Math.floor(Math.random() * 1000000);
113
+
114
+ let component_set_data: (data: Record<string, any>) => void;
115
+ let component_get_data: () => Promise<Record<string, any>>;
116
+
117
+ const mock_register = (
118
+ _id: number,
119
+ set_data: (data: Record<string, any>) => void,
120
+ get_data: () => Promise<Record<string, any>>
121
+ ): void => {
122
+ component_set_data = set_data;
123
+ component_get_data = get_data;
124
+ };
125
+
126
+ const event_listeners = new Map<string, Set<(data: any) => void>>();
127
+ const event_buffer: Array<{ event: string; data: any }> = [];
128
+
129
+ function notify_listeners(event: string, data: any): void {
130
+ const listeners = event_listeners.get(event);
131
+ if (listeners) {
132
+ for (const listener of listeners) {
133
+ listener(data);
134
+ }
135
+ }
136
+ }
137
+
138
+ const dispatcher = (_id: number, event: string, data: any): void => {
139
+ event_buffer.push({ event, data });
140
+ notify_listeners(event, data);
141
+ };
142
+
143
+ function listen(
144
+ event_name: string,
145
+ opts?: { retrospective?: boolean }
146
+ ): Mock {
147
+ const fn = vi.fn();
148
+ if (!event_listeners.has(event_name)) {
149
+ event_listeners.set(event_name, new Set());
150
+ }
151
+ event_listeners.get(event_name)!.add(fn);
152
+
153
+ if (opts?.retrospective) {
154
+ for (const entry of event_buffer) {
155
+ if (entry.event === event_name) {
156
+ fn(entry.data);
157
+ }
158
+ }
159
+ }
160
+
161
+ return fn;
162
+ }
163
+
164
+ const i18nFormatter = (s: string | null | undefined): string => s ?? "";
165
+
166
+ const shared_props_obj: Record<string, any> = {
167
+ id,
168
+ target,
169
+ theme_mode: "light" as const,
170
+ version: "2.0.0",
171
+ formatter: i18nFormatter,
172
+ client: {} as any,
173
+ load_component: () => Promise.resolve({ default: {} as any }),
174
+ show_progress: true,
175
+ api_prefix: "",
176
+ server: {} as any,
177
+ show_label: true,
178
+ register_component: mock_register,
179
+ dispatcher
180
+ };
181
+
182
+ const component_props_obj: Record<string, any> = {
183
+ i18n: i18nFormatter
184
+ };
185
+
186
+ if (props) {
187
+ for (const key in props) {
188
+ const value = (props as any)[key];
189
+ if (allowed_shared_props.includes(key as any)) {
190
+ shared_props_obj[key] = value;
191
+ } else {
192
+ component_props_obj[key] = value;
193
+ }
194
+ }
195
+ }
196
+
197
+ shared_props_obj.loading_status = props?.loading_status
198
+ ? props.loading_status
199
+ : loading_status;
200
+
201
+ const componentProps = {
202
+ shared_props: shared_props_obj,
203
+ props: {
204
+ ...component_props_obj
205
+ },
206
+ ...shared_props_obj
207
+ };
208
+
209
+ const component = mount(ComponentConstructor, {
210
+ target,
211
+ props: componentProps
212
+ }) as T;
213
+
214
+ containerCache.set(container, { target, component });
215
+ componentCache.add(component);
216
+
217
+ await tick();
218
+
219
+ return {
220
+ container,
221
+ component,
222
+ listen,
223
+ set_data: async (data: Record<string, any>) => {
224
+ const r = component_set_data(data);
225
+ // we double tick here because the event may trigger state update inside the component
226
+ // the event may _only_ be fired in response to these state updates.
227
+ // so we want everything to settle before returning and continuing with the test.
228
+ await tick();
229
+ await tick();
230
+ return r;
231
+ },
232
+ get_data: () => component_get_data(),
233
+ //@ts-ignore
234
+ debug: (el = container): void => console.warn(prettyDOM(el)),
235
+ unmount: (): void => {
236
+ if (componentCache.has(component)) {
237
+ unmount(component);
238
+ }
239
+ },
240
+ ...getQueriesForElement(container)
241
+ };
242
+ }
243
+
244
+ const cleanupAtContainer = (container: HTMLElement): void => {
245
+ const { target, component } = containerCache.get(container);
246
+
247
+ if (componentCache.has(component)) {
248
+ unmount(component);
249
+ }
250
+
251
+ if (target.parentNode === document.body) {
252
+ document.body.removeChild(target);
253
+ }
254
+
255
+ containerCache.delete(container);
256
+ };
257
+
258
+ export function cleanup(): void {
259
+ Array.from(containerCache.keys()).forEach(cleanupAtContainer);
260
+ document.body.innerHTML = "";
261
+ }
262
+
263
+ type AsyncFireObject = {
264
+ [K in EventType]: (
265
+ element: Document | Element | Window | Node,
266
+ options?: object
267
+ ) => Promise<boolean>;
268
+ };
269
+
270
+ export const fireEvent = Object.keys(dtlFireEvent).reduce((acc, key) => {
271
+ const _key = key as EventType;
272
+ return {
273
+ ...acc,
274
+ [_key]: async (
275
+ element: Document | Element | Window,
276
+ options: object = {}
277
+ ): Promise<boolean> => {
278
+ const event = dtlFireEvent[_key](element, options);
279
+ // we double tick here because the event may trigger state update inside the component
280
+ // the event may _only_ be fired in response to these state updates.
281
+ // so we want everything to settle before returning and continuing with the test.
282
+ await tick();
283
+ await tick();
284
+ return event;
285
+ }
286
+ };
287
+ }, {} as AsyncFireObject);
288
+
289
+ export type FireFunction = (
290
+ element: Document | Element | Window,
291
+ event: Event
292
+ ) => Promise<boolean>;
293
+
294
+ export { download_file, upload_file, drop_file } from "./download.js";
295
+
296
+ /**
297
+ * Creates a mock client suitable for components that use file uploads.
298
+ * The upload mock echoes back the input FileData unchanged.
299
+ */
300
+ export function mock_client(): Record<string, any> {
301
+ return {
302
+ upload: async (file_data: any[]) => file_data,
303
+ stream: async () => ({ onmessage: null, close: () => {} })
304
+ };
305
+ }
306
+ export {
307
+ TEST_TXT,
308
+ TEST_JPG,
309
+ TEST_PNG,
310
+ TEST_MP4,
311
+ TEST_WAV,
312
+ TEST_PDF,
313
+ TEST_GLTF,
314
+ TEST_PLY,
315
+ TEST_SPLAT
316
+ } from "./fixtures.js";
317
+ export * from "@testing-library/dom";
6.14.1/tootils/src/shared-prop-tests.ts ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, test, expect, afterEach } from "vitest";
2
+ import { render, cleanup } from "./render";
3
+
4
+ const loading_status = {
5
+ status: "complete",
6
+ queue_position: null,
7
+ queue_size: null,
8
+ eta: null,
9
+ message: null
10
+ };
11
+
12
+ export interface SharedPropTestConfig {
13
+ /** The Svelte component to test */
14
+ component: any;
15
+ /** Minimum props required to render the component without errors */
16
+ base_props: Record<string, any>;
17
+ /** Display name for test output */
18
+ name: string;
19
+ /**
20
+ * Some components don't render labels (e.g. HTML, Markdown).
21
+ * Set to false to skip label-related tests.
22
+ * @default true
23
+ */
24
+ has_label?: boolean;
25
+ /**
26
+ * Whether the component renders validation_error text.
27
+ * Not all components support this. Set to false to skip.
28
+ * @default true
29
+ */
30
+ has_validation_error?: boolean;
31
+ /**
32
+ * Some components (e.g. Accordion) map visible=false to "hidden"
33
+ * instead of removing from the DOM. Set to true to expect hidden
34
+ * behaviour rather than removal.
35
+ * @default false
36
+ */
37
+ visible_false_hides?: boolean;
38
+ /**
39
+ * Whether the component is wrapped in a Block (which renders a `.block`
40
+ * element). Components like Button render a bare element instead.
41
+ * Set to false to skip `.block` selector checks.
42
+ * @default true
43
+ */
44
+ has_block_wrapper?: boolean;
45
+ }
46
+
47
+ export function run_shared_prop_tests(config: SharedPropTestConfig): void {
48
+ const {
49
+ component,
50
+ base_props,
51
+ name,
52
+ has_label = true,
53
+ has_validation_error = true,
54
+ visible_false_hides = false,
55
+ has_block_wrapper = true
56
+ } = config;
57
+
58
+ const label = "Test Label";
59
+
60
+ function make_props(
61
+ overrides: Record<string, any> = {}
62
+ ): Record<string, any> {
63
+ return {
64
+ ...base_props,
65
+ loading_status: { ...loading_status, ...overrides },
66
+ label,
67
+ ...overrides
68
+ };
69
+ }
70
+
71
+ describe(`${name}: shared props`, () => {
72
+ afterEach(() => cleanup());
73
+
74
+ test("elem_id is applied to the wrapper", async () => {
75
+ const { container } = await render(
76
+ component,
77
+ make_props({ elem_id: "my-test-id" })
78
+ );
79
+ const el = container.querySelector("#my-test-id");
80
+ expect(el).not.toBeNull();
81
+ });
82
+
83
+ test("elem_classes are applied to the wrapper", async () => {
84
+ const { container } = await render(
85
+ component,
86
+ make_props({ elem_classes: ["my-test-class"] })
87
+ );
88
+ const el = container.querySelector(".my-test-class");
89
+ expect(el).not.toBeNull();
90
+ });
91
+
92
+ test("visible: true renders the component", async () => {
93
+ const { container } = await render(
94
+ component,
95
+ make_props({ visible: true, elem_id: "visible-test" })
96
+ );
97
+ const el = has_block_wrapper
98
+ ? container.querySelector(".block")
99
+ : container.querySelector("#visible-test");
100
+ expect(el).not.toBeNull();
101
+ });
102
+
103
+ test("visible: 'hidden' hides the component but keeps it in the DOM", async () => {
104
+ const result = await render(
105
+ component,
106
+ make_props({ visible: "hidden", elem_id: "hidden-test" })
107
+ );
108
+
109
+ const el = result.container.querySelector("#hidden-test");
110
+ expect(el).not.toBeNull();
111
+ expect(el).not.toBeVisible();
112
+ });
113
+
114
+ if (visible_false_hides) {
115
+ test("visible: false hides the component but keeps it in the DOM", async () => {
116
+ const result = await render(
117
+ component,
118
+ make_props({ visible: false, elem_id: "gone-test" })
119
+ );
120
+
121
+ const el = result.container.querySelector("#gone-test");
122
+ expect(el).not.toBeNull();
123
+ expect(el).not.toBeVisible();
124
+ });
125
+ } else {
126
+ test("visible: false removes the component from the DOM", async () => {
127
+ const result = await render(
128
+ component,
129
+ make_props({ visible: false, elem_id: "gone-test" })
130
+ );
131
+
132
+ const el = result.container.querySelector("#gone-test");
133
+ expect(el).toBeNull();
134
+ });
135
+ }
136
+
137
+ if (has_label) {
138
+ test("label text is rendered", async () => {
139
+ const result = await render(
140
+ component,
141
+ make_props({ label: "My Custom Label", show_label: true })
142
+ );
143
+ const el = result.getByText("My Custom Label");
144
+ expect(el).toBeTruthy();
145
+ });
146
+
147
+ test("show_label: true makes the label visible", async () => {
148
+ const result = await render(
149
+ component,
150
+ make_props({ label: "Visible Label", show_label: true })
151
+ );
152
+ const el = result.getByText("Visible Label");
153
+ expect(el).toBeVisible();
154
+ });
155
+
156
+ test("show_label: false hides the label visually but keeps it in the DOM", async () => {
157
+ const result = await render(
158
+ component,
159
+ make_props({ label: "Hidden Label", show_label: false })
160
+ );
161
+ const el = result.getByText("Hidden Label");
162
+ // The label remains in the DOM for screen readers via sr-only.
163
+ // sr-only uses clip/1px dimensions rather than display:none,
164
+ // so toBeVisible() won't catch it. We check the class directly.
165
+ expect(el.closest("[data-testid='block-info']")).toHaveClass("sr-only");
166
+ });
167
+ }
168
+
169
+ if (has_validation_error) {
170
+ test("validation_error displays error text visibly", async () => {
171
+ const result = await render(
172
+ component,
173
+ make_props({
174
+ validation_error: "This field is required",
175
+ show_validation_error: true
176
+ })
177
+ );
178
+ const el = result.getByText("This field is required");
179
+ expect(el).toBeVisible();
180
+ });
181
+ }
182
+ });
183
+ }