π OpenHands: AI-Driven Development
test: cover core utilities and state stores (#17290)
aivong-openhands73cbe26137fa
diff --git a/__tests__/stores/initial-query-store.test.ts b/__tests__/stores/initial-query-store.test.tsnew file mode 100644index 0000000000..ebde634a66--- /dev/null+++ b/__tests__/stores/initial-query-store.test.ts@@ -0,0 +1,71 @@+import { beforeEach, describe, expect, it } from "vitest";+import { useInitialQueryStore } from "#/stores/initial-query-store";++const emptyState = {+ files: [],+ initialPrompt: null,+ selectedRepository: null,+ selectedRepositoryProvider: null,+ replayJson: null,+};++describe("useInitialQueryStore", () => {+ beforeEach(() => {+ useInitialQueryStore.getState().reset();+ });++ it("adds, removes, and clears files", () => {+ const store = useInitialQueryStore.getState();+ store.addFile("first");+ store.addFile("second");+ store.addFile("third");+ expect(useInitialQueryStore.getState().files).toEqual([+ "first",+ "second",+ "third",+ ]);++ useInitialQueryStore.getState().removeFile(1);+ expect(useInitialQueryStore.getState().files).toEqual(["first", "third"]);+ useInitialQueryStore.getState().removeFile(99);+ expect(useInitialQueryStore.getState().files).toEqual(["first", "third"]);+ useInitialQueryStore.getState().clearFiles();+ expect(useInitialQueryStore.getState().files).toEqual([]);+ });++ it("sets and clears prompt and repository selections", () => {+ const repository = {+ id: "repository-1",+ full_name: "owner/repository",+ git_provider: "github",+ is_public: true,+ } as const;+ const store = useInitialQueryStore.getState();+ store.setInitialPrompt("Build it");+ store.setSelectedRepository(repository);+ store.setSelectedRepositoryProvider("github");+ store.setReplayJson('{"event":"message"}');+ expect(useInitialQueryStore.getState()).toMatchObject({+ initialPrompt: "Build it",+ selectedRepository: repository,+ selectedRepositoryProvider: "github",+ replayJson: '{"event":"message"}',+ });++ useInitialQueryStore.getState().clearInitialPrompt();+ useInitialQueryStore.getState().clearSelectedRepository();+ useInitialQueryStore.getState().setSelectedRepositoryProvider(null);+ useInitialQueryStore.getState().setReplayJson(null);+ expect(useInitialQueryStore.getState()).toMatchObject(emptyState);+ });++ it("resets every field after populated state", () => {+ const store = useInitialQueryStore.getState();+ store.addFile("image");+ store.setInitialPrompt("Prompt");+ store.setSelectedRepositoryProvider("gitlab");+ store.setReplayJson("{}");+ useInitialQueryStore.getState().reset();+ expect(useInitialQueryStore.getState()).toMatchObject(emptyState);+ });+});diff --git a/__tests__/utils/file-processing.test.ts b/__tests__/utils/file-processing.test.tsnew file mode 100644index 0000000000..1d7b9bde75--- /dev/null+++ b/__tests__/utils/file-processing.test.ts@@ -0,0 +1,124 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { processFiles, processImages } from "#/utils/file-processing";++const reads = vi.hoisted(() => ({+ arrayBuffers: [] as string[],+ dataUrls: [] as string[],+}));++class ControlledFileReader {+ onload: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onabort: (() => void) | null = null;++ private finish(file: File) {+ queueMicrotask(() => {+ if (file.name.startsWith("error")) {+ this.onerror?.();+ } else if (file.name.startsWith("abort")) {+ this.onabort?.();+ } else {+ this.onload?.();+ }+ });+ }++ readAsArrayBuffer(file: File) {+ reads.arrayBuffers.push(file.name);+ this.finish(file);+ }++ readAsDataURL(file: File) {+ reads.dataUrls.push(file.name);+ this.finish(file);+ }+}++function file(name: string, type = "text/plain") {+ return new File(["content"], name, { type });+}++describe("file processing", () => {+ beforeEach(() => {+ reads.arrayBuffers = [];+ reads.dataUrls = [];+ vi.stubGlobal("FileReader", ControlledFileReader);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("returns successful files in input order while retaining read failures", async () => {+ const first = file("first.txt");+ const failed = file("error-report.txt");+ const last = file("last.txt");++ const result = await processFiles([first, failed, last]);++ expect(reads.arrayBuffers).toEqual([+ "first.txt",+ "error-report.txt",+ "last.txt",+ ]);+ expect(result.successful).toEqual([first, last]);+ expect(result.failed).toEqual([+ {+ file: failed,+ error: new Error("Failed to read file: error-report.txt"),+ },+ ]);+ });++ it("reports aborted regular-file reads", async () => {+ const aborted = file("abort-upload.txt");++ await expect(processFiles([aborted])).resolves.toEqual({+ successful: [],+ failed: [+ {+ file: aborted,+ error: new Error("File reading was aborted: abort-upload.txt"),+ },+ ],+ });+ });++ it("reads images as data URLs and isolates errors and aborts", async () => {+ const successful = file("photo.png", "image/png");+ const failed = file("error-photo.png", "image/png");+ const aborted = file("abort-photo.png", "image/png");++ const result = await processImages([successful, failed, aborted]);++ expect(reads.dataUrls).toEqual([+ "photo.png",+ "error-photo.png",+ "abort-photo.png",+ ]);+ expect(result.successful).toEqual([successful]);+ expect(result.failed).toEqual([+ {+ file: failed,+ error: new Error("Failed to read image: error-photo.png"),+ },+ {+ file: aborted,+ error: new Error("Image reading was aborted: abort-photo.png"),+ },+ ]);+ });++ it("handles empty file and image batches without creating readers", async () => {+ await expect(processFiles([])).resolves.toEqual({+ successful: [],+ failed: [],+ });+ await expect(processImages([])).resolves.toEqual({+ successful: [],+ failed: [],+ });+ expect(reads.arrayBuffers).toEqual([]);+ expect(reads.dataUrls).toEqual([]);+ });+});diff --git a/__tests__/utils/get-language-from-path.test.ts b/__tests__/utils/get-language-from-path.test.tsnew file mode 100644index 0000000000..1f4187ad9f--- /dev/null+++ b/__tests__/utils/get-language-from-path.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from "vitest";+import { getLanguageFromPath } from "#/utils/get-language-from-path";++describe("getLanguageFromPath", () => {+ it.each([+ ["index.js", "javascript"],+ ["component.JSX", "javascript"],+ ["types.ts", "typescript"],+ ["view.tsx", "typescript"],+ ["script.py", "python"],+ ["index.html", "html"],+ ["styles.css", "css"],+ ["package.json", "json"],+ ["README.md", "markdown"],+ ["workflow.yml", "yaml"],+ ["config.yaml", "yaml"],+ ["install.sh", "bash"],+ ["profile.bash", "bash"],+ ["container.dockerfile", "dockerfile"],+ ["main.rs", "rust"],+ ["main.go", "go"],+ ["Main.java", "java"],+ ["main.cpp", "cpp"],+ ["legacy.cc", "cpp"],+ ["native.cxx", "cpp"],+ ["native.c", "c"],+ ["task.rb", "ruby"],+ ["index.php", "php"],+ ["query.sql", "sql"],+ ["README", "text"],+ ["archive.unknown", "text"],+ ["", "text"],+ ])("maps %s to %s", (path, language) => {+ expect(getLanguageFromPath(path)).toBe(language);+ });+});diff --git a/__tests__/utils/send-message-with-attachments.test.ts b/__tests__/utils/send-message-with-attachments.test.tsnew file mode 100644index 0000000000..1f9b5e3d98--- /dev/null+++ b/__tests__/utils/send-message-with-attachments.test.ts@@ -0,0 +1,162 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import { sendMessageWithAttachments } from "#/utils/send-message-with-attachments";++const mocks = vi.hoisted(() => ({+ partition: vi.fn(),+ validate: vi.fn(),+ convert: vi.fn(),+ resolveRuntime: vi.fn(),+ upload: vi.fn(),+ sendMessage: vi.fn(),+ toast: vi.fn(),+}));++vi.mock("#/components/features/chat/utils/chat-input.utils", () => ({+ partitionImagesForUpload: mocks.partition,+}));++vi.mock("#/utils/file-validation", () => ({+ validateFiles: mocks.validate,+}));++vi.mock("#/utils/convert-image-to-base-64", () => ({+ convertImageToBase64: mocks.convert,+}));++vi.mock("#/api/conversation-file-upload.api", () => ({+ resolveConversationRuntime: mocks.resolveRuntime,+ uploadFilesToConversation: mocks.upload,+}));++vi.mock(+ "#/api/conversation-service/agent-server-conversation-service.api",+ () => ({+ default: { sendMessage: mocks.sendMessage },+ }),+);++vi.mock("#/utils/custom-toast-handlers", () => ({+ displayErrorToast: mocks.toast,+}));++const translate = vi.fn((key: string) => `translated:${key}`);+const image = new File(["image"], "image.png", { type: "image/png" });+const imageFile = new File(["large image"], "large.png", {+ type: "image/png",+});+const documentFile = new File(["notes"], "notes.txt", {+ type: "text/plain",+});++function options() {+ return {+ conversationId: "conversation-1",+ content: "Please inspect these files",+ images: [image, imageFile],+ files: [documentFile],+ imagesMarkedUploadAsFile: ["large.png"],+ t: translate as never,+ };+}++describe("sendMessageWithAttachments", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.partition.mockReturnValue({+ imagesToEmbed: [image],+ imagesAsFiles: [imageFile],+ });+ mocks.validate.mockReturnValue({ isValid: true });+ mocks.convert.mockResolvedValue("data:image/png;base64,aW1hZ2U=");+ mocks.resolveRuntime.mockResolvedValue({ kind: "remote" });+ mocks.upload.mockResolvedValue({+ skipped_files: [{ reason: "large.png was skipped" }],+ uploaded_files: [+ "/workspace/notes.txt",+ "/workspace/large.png",+ ],+ });+ mocks.sendMessage.mockResolvedValue(undefined);+ });++ it("uploads files, embeds images, reports skips, and sends the augmented prompt", async () => {+ const result = await sendMessageWithAttachments(options());++ expect(mocks.partition).toHaveBeenCalledWith(+ [image, imageFile],+ ["large.png"],+ );+ expect(mocks.validate).toHaveBeenCalledWith([+ image,+ documentFile,+ imageFile,+ ]);+ expect(mocks.upload).toHaveBeenCalledWith("conversation-1", [+ documentFile,+ imageFile,+ ]);+ expect(mocks.toast).toHaveBeenCalledWith("large.png was skipped");+ expect(mocks.sendMessage).toHaveBeenCalledWith(+ "conversation-1",+ {+ role: "user",+ content: [+ {+ type: "text",+ text: "Please inspect these files\n\ntranslated:CHAT_INTERFACE$AUGMENTED_PROMPT_FILES_TITLE: /workspace/notes.txt\n\n/workspace/large.png",+ },+ {+ type: "image",+ image_urls: ["data:image/png;base64,aW1hZ2U="],+ },+ ],+ },+ { kind: "remote" },+ );+ expect(result).toMatchObject({+ text: "Please inspect these files",+ content:+ "Please inspect these files\n\ntranslated:CHAT_INTERFACE$AUGMENTED_PROMPT_FILES_TITLE: /workspace/notes.txt\n\n/workspace/large.png",+ imageUrls: ["data:image/png;base64,aW1hZ2U="],+ fileUrls: ["/workspace/notes.txt", "/workspace/large.png"],+ });+ expect(Number.isNaN(Date.parse(result.timestamp))).toBe(false);+ });++ it("sends plain text without calling the upload or image converters", async () => {+ mocks.partition.mockReturnValue({ imagesToEmbed: [], imagesAsFiles: [] });+ const plain = options();+ plain.images = [];+ plain.files = [];+ plain.imagesMarkedUploadAsFile = [];++ const result = await sendMessageWithAttachments(plain);++ expect(mocks.upload).not.toHaveBeenCalled();+ expect(mocks.convert).not.toHaveBeenCalled();+ expect(mocks.toast).not.toHaveBeenCalled();+ expect(mocks.sendMessage.mock.calls[0][1]).toEqual({+ role: "user",+ content: [{ type: "text", text: plain.content }],+ });+ expect(result.content).toBe(plain.content);+ });++ it("throws the validator's attachment error before resolving a runtime", async () => {+ mocks.validate.mockReturnValue({+ isValid: false,+ errorMessage: "Attachment is too large",+ });+ await expect(sendMessageWithAttachments(options())).rejects.toThrow(+ "Attachment is too large",+ );+ expect(mocks.resolveRuntime).not.toHaveBeenCalled();+ });++ it("uses a fallback error for invalid attachments without a message", async () => {+ mocks.validate.mockReturnValue({ isValid: false });+ await expect(sendMessageWithAttachments(options())).rejects.toThrow(+ "Invalid attachments",+ );+ });+});