gradio-pr-bot commited on
Commit
b60356b
·
verified ·
1 Parent(s): 2123a1b

Upload folder using huggingface_hub

Browse files
6.14.0/tootils/package.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@self/tootils",
3
+ "version": "0.13.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.0/tootils/src/app-launcher.ts ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { spawn, 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
+ export async function findFreePort(
26
+ startPort: number,
27
+ endPort: number
28
+ ): Promise<number> {
29
+ for (let port = startPort; port < endPort; port++) {
30
+ if (await isPortFree(port)) {
31
+ return port;
32
+ }
33
+ }
34
+ throw new Error(`Could not find free port in range ${startPort}-${endPort}`);
35
+ }
36
+
37
+ function isPortFree(port: number): Promise<boolean> {
38
+ return new Promise((resolve, reject) => {
39
+ const sock = net.createConnection(port, "127.0.0.1");
40
+ sock.once("connect", () => {
41
+ sock.end();
42
+ resolve(false);
43
+ });
44
+ sock.once("error", (e: NodeJS.ErrnoException) => {
45
+ sock.destroy();
46
+ if (e.code === "ECONNREFUSED") {
47
+ resolve(true);
48
+ } else {
49
+ reject(e);
50
+ }
51
+ });
52
+ });
53
+ }
54
+
55
+ /**
56
+ * Poll the server with HTTP GET requests until it returns a response.
57
+ * Gradio prints "Running on local URL:" before the server is fully ready,
58
+ * so we need to verify it actually responds to HTTP requests.
59
+ */
60
+ async function waitForServerReady(
61
+ port: number,
62
+ timeoutMs: number = 15000
63
+ ): Promise<void> {
64
+ const start = Date.now();
65
+ const pollInterval = 200;
66
+
67
+ while (Date.now() - start < timeoutMs) {
68
+ try {
69
+ await new Promise<void>((resolve, reject) => {
70
+ // Use HEAD on /gradio_api/info to avoid triggering SSR rendering on
71
+ // the root URL, which could block Gradio's own startup health check.
72
+ const req = http.request(
73
+ `http://127.0.0.1:${port}/gradio_api/info`,
74
+ { method: "HEAD", timeout: 2000 },
75
+ (res) => {
76
+ res.resume(); // drain the response
77
+ resolve();
78
+ }
79
+ );
80
+ req.on("error", reject);
81
+ req.on("timeout", () => {
82
+ req.destroy();
83
+ reject(new Error("request timeout"));
84
+ });
85
+ req.end();
86
+ });
87
+ return; // Server responded successfully
88
+ } catch {
89
+ // Server not ready yet, wait and retry
90
+ await new Promise((r) => setTimeout(r, pollInterval));
91
+ }
92
+ }
93
+ throw new Error(
94
+ `Server on port ${port} did not become ready within ${timeoutMs}ms`
95
+ );
96
+ }
97
+
98
+ export function getTestcases(demoName: string): string[] {
99
+ const demoDir = path.join(ROOT_DIR, "demo", demoName);
100
+ if (!fs.existsSync(demoDir)) {
101
+ return [];
102
+ }
103
+
104
+ return fs
105
+ .readdirSync(demoDir)
106
+ .filter((f) => f.endsWith("_testcase.py"))
107
+ .map((f) => path.basename(f, ".py"));
108
+ }
109
+
110
+ // Check if a testcase file exists for this demo
111
+ export function hasTestcase(demoName: string, testcaseName: string): boolean {
112
+ const testcaseFile = path.join(
113
+ ROOT_DIR,
114
+ "demo",
115
+ demoName,
116
+ `${testcaseName}_testcase.py`
117
+ );
118
+ return fs.existsSync(testcaseFile);
119
+ }
120
+
121
+ // Get the path to a demo's Python file
122
+ function getDemoFilePath(demoName: string, testcaseName?: string): string {
123
+ if (testcaseName) {
124
+ return path.join(ROOT_DIR, "demo", demoName, `${testcaseName}_testcase.py`);
125
+ }
126
+ return path.join(ROOT_DIR, "demo", demoName, "run.py");
127
+ }
128
+
129
+ export async function launchGradioApp(
130
+ demoName: string,
131
+ workerIndex: number = 0,
132
+ timeout: number = 60000,
133
+ testcaseName?: string
134
+ ): Promise<GradioApp> {
135
+ // Partition ports by worker index to avoid collisions
136
+ const basePort = 7860 + workerIndex * 100;
137
+ const port = await findFreePort(basePort, basePort + 99);
138
+
139
+ // Get the path to the demo file
140
+ const demoFilePath = getDemoFilePath(demoName, testcaseName);
141
+
142
+ // Create unique directories for this instance to avoid cache conflicts
143
+ const instanceId = testcaseName
144
+ ? `${demoName}_${testcaseName}_${port}`
145
+ : `${demoName}_${port}`;
146
+ const instanceDir = path.join(os.tmpdir(), `gradio_test_${instanceId}`);
147
+ const cacheDir = path.join(instanceDir, "cached_examples");
148
+ const tempDir = path.join(instanceDir, "temp");
149
+
150
+ if (!fs.existsSync(instanceDir)) {
151
+ fs.mkdirSync(instanceDir, { recursive: true });
152
+ }
153
+
154
+ // Run the demo file directly - the demo's own if __name__ == "__main__" block
155
+ // has the correct launch parameters (show_error, etc.)
156
+ const childProcess = spawn("python", [demoFilePath], {
157
+ stdio: "pipe",
158
+ cwd: ROOT_DIR,
159
+ env: {
160
+ ...process.env,
161
+ PYTHONUNBUFFERED: "true",
162
+ GRADIO_ANALYTICS_ENABLED: "False",
163
+ GRADIO_IS_E2E_TEST: "1",
164
+ GRADIO_RESET_EXAMPLES_CACHE: "True",
165
+ // Control the port via environment variable
166
+ GRADIO_SERVER_PORT: port.toString(),
167
+ // Use unique directories per instance to avoid conflicts
168
+ GRADIO_EXAMPLES_CACHE: cacheDir,
169
+ GRADIO_TEMP_DIR: tempDir
170
+ }
171
+ });
172
+
173
+ childProcess.stdout?.setEncoding("utf8");
174
+ childProcess.stderr?.setEncoding("utf8");
175
+
176
+ // Wait for app to be ready
177
+ return new Promise<GradioApp>((resolve, reject) => {
178
+ const timeoutId = setTimeout(() => {
179
+ killGradioApp(childProcess);
180
+ reject(
181
+ new Error(`Gradio app ${demoName} failed to start within ${timeout}ms`)
182
+ );
183
+ }, timeout);
184
+
185
+ let output = "";
186
+ let startupDetected = false;
187
+
188
+ function handleOutput(data: string): void {
189
+ output += data;
190
+ // Check for Gradio's startup message
191
+ if (
192
+ !startupDetected &&
193
+ (data.includes("Running on local URL:") ||
194
+ data.includes(`Uvicorn running on`))
195
+ ) {
196
+ startupDetected = true;
197
+ clearTimeout(timeoutId);
198
+ // The startup message is printed before the server is fully ready.
199
+ // Poll with HTTP requests to ensure it actually responds.
200
+ waitForServerReady(port)
201
+ .then(() => resolve({ port, process: childProcess }))
202
+ .catch(reject);
203
+ }
204
+ }
205
+
206
+ childProcess.stdout?.on("data", handleOutput);
207
+ childProcess.stderr?.on("data", handleOutput);
208
+
209
+ childProcess.on("error", (err) => {
210
+ clearTimeout(timeoutId);
211
+ reject(err);
212
+ });
213
+
214
+ childProcess.on("exit", (code) => {
215
+ if (code !== 0 && code !== null) {
216
+ clearTimeout(timeoutId);
217
+ reject(
218
+ new Error(
219
+ `Gradio app ${demoName} exited with code ${code}.\nOutput: ${output}`
220
+ )
221
+ );
222
+ }
223
+ });
224
+ });
225
+ }
6.14.0/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.0/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.0/tootils/src/fixtures.ts ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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);
6.14.0/tootils/src/index.ts ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ // Test fixture that launches Gradio app per test
57
+ const test_normal = base.extend<{ setup: void }>({
58
+ setup: [
59
+ async ({ page }, use, testInfo): Promise<void> => {
60
+ const { file, title } = testInfo;
61
+ const demoName = path.basename(file, ".spec.ts");
62
+
63
+ // Check if this is a reload test (they manage their own apps)
64
+ if (demoName.endsWith(".reload")) {
65
+ // For reload tests, don't launch an app - they handle it themselves
66
+ await use();
67
+ return;
68
+ }
69
+
70
+ // Check if this test is for a specific testcase
71
+ const testcaseName = extractTestcaseFromTitle(title, demoName);
72
+
73
+ // Cache key includes testcase if present
74
+ const cacheKey = testcaseName ? `${demoName}_${testcaseName}` : demoName;
75
+
76
+ let appInfo = appCache.get(cacheKey);
77
+
78
+ if (!appInfo) {
79
+ // Launch the app for this test
80
+ const workerIndex = testInfo.workerIndex;
81
+ try {
82
+ const { port, process } = await launchGradioApp(
83
+ demoName,
84
+ workerIndex,
85
+ 60000,
86
+ testcaseName
87
+ );
88
+ appInfo = { port, process, refCount: 0 };
89
+ appCache.set(cacheKey, appInfo);
90
+ } catch (error) {
91
+ console.error(`Failed to launch app for ${cacheKey}:`, error);
92
+ throw error;
93
+ }
94
+ }
95
+
96
+ appInfo.refCount++;
97
+
98
+ // Navigate to the app
99
+ await page.goto(`http://localhost:${appInfo.port}`);
100
+
101
+ if (
102
+ process.env?.GRADIO_SSR_MODE?.toLowerCase() === "true" &&
103
+ !(
104
+ demoName.includes("multipage") ||
105
+ demoName.includes("chatinterface_deep_link")
106
+ )
107
+ ) {
108
+ await page.waitForSelector("#svelte-announcer");
109
+ }
110
+ await page.waitForLoadState("load");
111
+
112
+ await use();
113
+
114
+ // Decrement ref count
115
+ appInfo.refCount--;
116
+
117
+ // Note: We don't kill the app here because other tests might
118
+ // still need it. The app will be killed when the process exits.
119
+ },
120
+ { auto: true }
121
+ ]
122
+ });
123
+
124
+ // Cleanup apps when the process exits
125
+ process.on("exit", () => {
126
+ for (const [, appInfo] of appCache) {
127
+ killGradioApp(appInfo.process);
128
+ }
129
+ });
130
+
131
+ process.on("SIGINT", () => {
132
+ for (const [, appInfo] of appCache) {
133
+ killGradioApp(appInfo.process);
134
+ }
135
+ process.exit(0);
136
+ });
137
+
138
+ process.on("SIGTERM", () => {
139
+ for (const [, appInfo] of appCache) {
140
+ killGradioApp(appInfo.process);
141
+ }
142
+ process.exit(0);
143
+ });
144
+
145
+ export const test = test_normal;
146
+
147
+ export async function wait_for_event(
148
+ component: SvelteComponent,
149
+ event: string
150
+ ): Promise<SpyFn> {
151
+ const mock = spy();
152
+ return new Promise((res) => {
153
+ component.$on(event, () => {
154
+ mock();
155
+ res(mock);
156
+ });
157
+ });
158
+ }
159
+
160
+ export interface ActionReturn<
161
+ Parameter = never,
162
+ Attributes extends Record<string, any> = Record<never, any>
163
+ > {
164
+ update?: [Parameter] extends [never] ? never : (parameter: Parameter) => void;
165
+ destroy?: () => void;
166
+ /**
167
+ * ### DO NOT USE THIS
168
+ * This exists solely for type-checking and has no effect at runtime.
169
+ * Set this through the `Attributes` generic instead.
170
+ */
171
+ $$_attributes?: Attributes;
172
+ }
173
+
174
+ export { expect } from "@playwright/test";
175
+
176
+ export const drag_and_drop_file = async (
177
+ page: Page,
178
+ selector: string | Locator,
179
+ filePath: string,
180
+ fileName: string,
181
+ fileType = "",
182
+ count = 1
183
+ ): Promise<void> => {
184
+ const buffer = (await fsPromises.readFile(filePath)).toString("base64");
185
+
186
+ const dataTransfer = await page.evaluateHandle(
187
+ async ({ bufferData, localFileName, localFileType, count }) => {
188
+ const dt = new DataTransfer();
189
+
190
+ const blobData = await fetch(bufferData).then((res) => res.blob());
191
+
192
+ const file = new File([blobData], localFileName, {
193
+ type: localFileType
194
+ });
195
+
196
+ for (let i = 0; i < count; i++) {
197
+ dt.items.add(file);
198
+ }
199
+ return dt;
200
+ },
201
+ {
202
+ bufferData: `data:application/octet-stream;base64,${buffer}`,
203
+ localFileName: fileName,
204
+ localFileType: fileType,
205
+ count
206
+ }
207
+ );
208
+
209
+ if (typeof selector === "string") {
210
+ await page.dispatchEvent(selector, "drop", { dataTransfer });
211
+ } else {
212
+ await selector.dispatchEvent("drop", { dataTransfer });
213
+ }
214
+ };
215
+
216
+ export async function go_to_testcase(
217
+ page: Page,
218
+ _test_case: string
219
+ ): Promise<void> {
220
+ // With the new setup, each testcase launches its own Gradio app.
221
+ // The fixture detects the testcase from the test title and launches
222
+ // the correct app, so this function is now a no-op.
223
+ // The page is already at the correct testcase app.
224
+ }
6.14.0/tootils/src/render.ts ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ } from "./fixtures.js";
314
+ export * from "@testing-library/dom";
6.14.0/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
+ }