File size: 5,357 Bytes
3c3cdbd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";

const mockFetch = vi.fn();
vi.stubGlobal("fetch", mockFetch);

const hashQuery = (query: string) =>
  query
    .split("")
    .reduce((acc, char) => ((acc << 5) - acc + char.charCodeAt(0)) | 0, 0)
    .toString(36);

const mockFetchResponse = (results: string[][]) => {
  mockFetch.mockResolvedValue({
    ok: true,
    json: vi.fn().mockResolvedValue(results),
  });
};

vi.mock("./logEntries", () => ({
  addLogEntry: vi.fn(),
}));

vi.mock("./searchTokenHash", () => ({
  getSearchTokenHash: vi.fn().mockResolvedValue("mock-token-hash"),
}));

describe("Search Module", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  afterEach(() => {
    vi.restoreAllMocks();
  });

  describe("hashQuery", () => {
    it("should generate consistent hashes for the same query", () => {
      const hash1 = hashQuery("test query");
      const hash2 = hashQuery("test query");
      expect(hash1).toBe(hash2);
    });

    it("should generate different hashes for different queries", () => {
      const hash1 = hashQuery("test query");
      const hash2 = hashQuery("different query");
      expect(hash1).not.toBe(hash2);
    });

    it("should handle empty strings", () => {
      const hash = hashQuery("");
      expect(hash).toBe("0");
    });

    it("should handle special characters", () => {
      const hash1 = hashQuery("test@query#123");
      const hash2 = hashQuery("test@query#123");
      expect(hash1).toBe(hash2);
    });

    it("should handle unicode characters", () => {
      const hash1 = hashQuery("ζ—₯本θͺžγƒ†γ‚Ήγƒˆ");
      const hash2 = hashQuery("ζ—₯本θͺžγƒ†γ‚Ήγƒˆ");
      expect(hash1).toBe(hash2);
    });
  });

  describe("searchText API behavior", () => {
    it("should handle API errors gracefully and return empty array", async () => {
      mockFetch.mockRejectedValue(new Error("Network error"));

      expect(mockFetch).toBeDefined();
    });

    it("should handle non-OK HTTP responses", async () => {
      mockFetch.mockResolvedValue({
        ok: false,
        status: 500,
        statusText: "Internal Server Error",
      });

      const response = await mockFetch();
      expect(response.ok).toBe(false);
      expect(response.status).toBe(500);
    });

    it("should parse JSON response correctly", async () => {
      const mockResults = [["Title 1", "Snippet 1", "https://example.com/1"]];
      mockFetchResponse(mockResults);

      const response = await mockFetch();
      const data = await response.json();
      expect(data).toEqual(mockResults);
    });
  });

  describe("searchImages API behavior", () => {
    it("should handle image search API errors", async () => {
      mockFetch.mockRejectedValue(new Error("Image search failed"));

      await expect(mockFetch()).rejects.toThrow("Image search failed");
    });

    it("should parse image results correctly", async () => {
      const mockResults = [
        ["Image 1", "Alt text 1", "https://example.com/image1.jpg"],
        ["Image 2", "Alt text 2", "https://example.com/image2.jpg"],
      ];
      mockFetchResponse(mockResults);

      const response = await mockFetch();
      const data = await response.json();
      expect(data).toHaveLength(2);
      expect(data[0][0]).toBe("Image 1");
    });
  });

  describe("URL construction", () => {
    it("should construct correct search URL with query parameter", () => {
      const query = "test query";
      const searchUrl = new URL("/search/text", "http://localhost:3000");
      searchUrl.searchParams.set("q", query);
      searchUrl.searchParams.set("token", "mock-token-hash");

      expect(searchUrl.searchParams.get("q")).toBe("test query");
      expect(searchUrl.searchParams.get("token")).toBe("mock-token-hash");
    });

    it("should include limit parameter when provided", () => {
      const searchUrl = new URL("/search/text", "http://localhost:3000");
      searchUrl.searchParams.set("q", "test");
      searchUrl.searchParams.set("limit", "5");

      expect(searchUrl.searchParams.get("limit")).toBe("5");
    });

    it("should construct correct image search URL", () => {
      const searchUrl = new URL("/search/images", "http://localhost:3000");
      searchUrl.searchParams.set("q", "cat photos");

      expect(searchUrl.pathname).toBe("/search/images");
      expect(searchUrl.searchParams.get("q")).toBe("cat photos");
    });
  });

  describe("Cache configuration", () => {
    it("should have reasonable default TTL", () => {
      const defaultTTL = 15 * 60 * 1000;
      expect(defaultTTL).toBe(900000);
    });

    it("should have reasonable default max entries", () => {
      const defaultMaxEntries = 100;
      expect(defaultMaxEntries).toBe(100);
    });
  });

  describe("Error Handling patterns", () => {
    it("should handle network timeouts", async () => {
      mockFetch.mockRejectedValue(new Error("Network timeout"));

      await expect(mockFetch()).rejects.toThrow("Network timeout");
    });

    it("should handle malformed JSON responses", async () => {
      mockFetch.mockResolvedValue({
        ok: true,
        json: vi.fn().mockRejectedValue(new SyntaxError("Unexpected token")),
      });

      const response = await mockFetch();
      await expect(response.json()).rejects.toThrow("Unexpected token");
    });
  });
});