Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

composerFiles.test.ts

386 lines11.5 KB

1import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
2​
3const mocks = vi.hoisted(() => ({
4 documentUri: "file:///documents",
5 pickFile: vi.fn(),
6 copy: vi.fn(),
7 delete: vi.fn(),
8 open: vi.fn(),
9 size: vi.fn(),
10}));
11​
12vi.mock("expo-file-system", () => {
13 class Directory {
14 readonly uri: string;
15​
16 constructor(root: string | { readonly uri: string }, name: string) {
17 this.uri = `${typeof root === "string" ? root : root.uri}/${name}`;
18 }
19​
20 create(): void {}
21 }
22​
23 class File {
24 static pickFileAsync = mocks.pickFile;
25​
26 readonly uri: string;
27​
28 constructor(source: string | Directory, name?: string) {
29 this.uri = source instanceof Directory ? `${source.uri}/${name}` : source;
30 }
31​
32 get exists(): boolean {
33 return true;
34 }
35​
36 get size(): number | null {
37 return mocks.size(this.uri) ?? null;
38 }
39​
40 create(): void {}
41​
42 open(mode: string) {
43 return mocks.open(this.uri, mode);
44 }
45​
46 async copy(destination: File): Promise<void> {
47 mocks.copy(this.uri, destination.uri);
48 }
49​
50 delete(): void {
51 mocks.delete(this.uri);
52 }
53 }
54​
55 return {
56 Directory,
57 File,
58 FileMode: { ReadOnly: "r", WriteOnly: "w" },
59 Paths: {
60 get document() {
61 return { uri: mocks.documentUri };
62 },
63 },
64 };
65});
66​
67vi.mock("./uuid", () => ({ uuidv4: () => "attachment-id" }));
68​
69import {
70 persistComposerAttachmentFile,
71 pickComposerFiles,
72 removePersistedComposerAttachmentFile,
73} from "./composerImages";
74​
75describe("pickComposerFiles", () => {
76 beforeEach(() => {
77 mocks.documentUri = "file:///documents";
78 mocks.pickFile.mockReset();
79 mocks.copy.mockReset();
80 mocks.delete.mockReset();
81 mocks.open.mockReset();
82 mocks.size.mockReset();
83 mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? null : 42));
84 });
85​
86 it("copies picked files into app-owned storage without loading their contents", async () => {
87 mocks.pickFile.mockResolvedValue({
88 canceled: false,
89 result: [
90 {
91 uri: "file:///downloads/report.pdf",
92 name: "report.pdf",
93 type: "application/pdf",
94 size: 42,
95 },
96 ],
97 });
98​
99 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
100 files: [
101 {
102 id: "attachment-id",
103 type: "file",
104 name: "report.pdf",
105 mimeType: "application/pdf",
106 sizeBytes: 42,
107 fileUri: "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
108 },
109 ],
110 error: null,
111 });
112 expect(mocks.copy).toHaveBeenCalledWith(
113 "file:///downloads/report.pdf",
114 "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
115 );
116 });
117​
118 it("falls back to a usable name when the picker reports a blank one", async () => {
119 mocks.pickFile.mockResolvedValue({
120 canceled: false,
121 result: [
122 {
123 uri: "file:///downloads/unnamed",
124 name: " ",
125 type: "application/pdf",
126 size: 42,
127 },
128 ],
129 });
130​
131 const result = await pickComposerFiles({ existingCount: 0 });
132 expect(result.error).toBeNull();
133 expect(result.files).toHaveLength(1);
134 expect(result.files[0]?.name).toBe("file");
135 });
136​
137 it("rejects files that exceed the environment's advertised upload limit", async () => {
138 mocks.pickFile.mockResolvedValue({
139 canceled: false,
140 result: [
141 {
142 uri: "file:///downloads/archive.zip",
143 name: "archive.zip",
144 type: "application/zip",
145 size: 2 * 1024 * 1024,
146 },
147 ],
148 });
149​
150 await expect(pickComposerFiles({ existingCount: 0, maxBytes: 1024 * 1024 })).resolves.toEqual({
151 files: [],
152 error: "'archive.zip' exceeds the 1 MB attachment limit.",
153 });
154 expect(mocks.copy).not.toHaveBeenCalled();
155 });
156​
157 it("never accepts files above the 50 MB contract limit", async () => {
158 mocks.pickFile.mockResolvedValue({
159 canceled: false,
160 result: [
161 {
162 uri: "file:///downloads/archive.zip",
163 name: "archive.zip",
164 type: "application/zip",
165 size: 51 * 1024 * 1024,
166 },
167 ],
168 });
169​
170 await expect(
171 pickComposerFiles({ existingCount: 0, maxBytes: 80 * 1024 * 1024 }),
172 ).resolves.toEqual({
173 files: [],
174 error: "'archive.zip' exceeds the 50 MB attachment limit.",
175 });
176 });
177​
178 it("rejects a file that grew after the picker reported its size", async () => {
179 mocks.pickFile.mockResolvedValue({
180 canceled: false,
181 result: [
182 {
183 uri: "file:///downloads/archive.zip",
184 name: "archive.zip",
185 type: "application/zip",
186 size: 42,
187 },
188 ],
189 });
190 mocks.size.mockReturnValue(2 * 1024 * 1024);
191​
192 await expect(pickComposerFiles({ existingCount: 0, maxBytes: 1024 * 1024 })).resolves.toEqual({
193 files: [],
194 error: "'archive.zip' exceeds the 1 MB attachment limit.",
195 });
196 expect(mocks.copy).not.toHaveBeenCalled();
197 });
198​
199 it("stops copying an unknown-size content URI when it exceeds the attachment limit", async () => {
200 const maxBytes = 1024 * 1024;
201 let remainingBytes = maxBytes + 1;
202 const source = {
203 readBytes: vi.fn((length: number) => {
204 const size = Math.min(length, remainingBytes);
205 remainingBytes -= size;
206 return new Uint8Array(size);
207 }),
208 close: vi.fn(),
209 };
210 const destination = { writeBytes: vi.fn(), close: vi.fn() };
211 mocks.open.mockImplementation((uri: string) =>
212 uri.startsWith("content:") ? source : destination,
213 );
214​
215 await expect(
216 persistComposerAttachmentFile("content://shared/large", "large.bin", maxBytes),
217 ).rejects.toThrow("'large.bin' exceeds the 1 MB attachment limit.");
218​
219 expect(source.close).toHaveBeenCalledOnce();
220 expect(destination.close).toHaveBeenCalledOnce();
221 expect(mocks.delete).toHaveBeenCalledWith(
222 "file:///documents/t3-composer-attachments/attachment-id-large.bin",
223 );
224 expect(mocks.copy).not.toHaveBeenCalled();
225 });
226​
227 it("rejects a copy that delivered more bytes than the source reported", async () => {
228 const maxBytes = 1024 * 1024;
229 // An Android content: stream can report a small size and still deliver
230 // more bytes; the persisted copy is what must satisfy the limit.
231 mocks.size.mockImplementation((uri: string) =>
232 uri.startsWith("content:") ? 42 : 2 * 1024 * 1024,
233 );
234​
235 await expect(
236 persistComposerAttachmentFile("content://shared/liar", "liar.bin", maxBytes),
237 ).rejects.toThrow("'liar.bin' exceeds the 1 MB attachment limit.");
238​
239 expect(mocks.copy).toHaveBeenCalledOnce();
240 expect(mocks.delete).toHaveBeenCalledWith(
241 "file:///documents/t3-composer-attachments/attachment-id-liar.bin",
242 );
243 });
244​
245 it("reports an empty file without calling it oversized", async () => {
246 mocks.size.mockReturnValue(0);
247 mocks.pickFile.mockResolvedValue({
248 canceled: false,
249 result: [
250 {
251 uri: "file:///downloads/empty.txt",
252 name: "empty.txt",
253 type: "text/plain",
254 size: 0,
255 },
256 ],
257 });
258​
259 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
260 files: [],
261 error: "'empty.txt' is empty or could not be read.",
262 });
263 });
264​
265 it("copies an Android SAF file when the picker reports an unknown zero size", async () => {
266 const reader = {
267 readBytes: vi
268 .fn()
269 .mockReturnValueOnce(new Uint8Array(42))
270 .mockReturnValueOnce(new Uint8Array()),
271 close: vi.fn(),
272 };
273 const writer = { writeBytes: vi.fn(), close: vi.fn() };
274 mocks.size.mockImplementation((uri: string) => (uri.startsWith("content:") ? 0 : 42));
275 mocks.open.mockImplementation((uri: string) => (uri.startsWith("content:") ? reader : writer));
276 mocks.pickFile.mockResolvedValue({
277 canceled: false,
278 result: [
279 {
280 uri: "content://shared/report",
281 name: "report.pdf",
282 type: "application/pdf",
283 size: 0,
284 },
285 ],
286 });
287​
288 await expect(pickComposerFiles({ existingCount: 0 })).resolves.toEqual({
289 files: [
290 {
291 id: "attachment-id",
292 type: "file",
293 name: "report.pdf",
294 mimeType: "application/pdf",
295 sizeBytes: 42,
296 fileUri: "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
297 },
298 ],
299 error: null,
300 });
301 });
302​
303 it("uses the remaining slot for the first valid file after an oversized selection", async () => {
304 mocks.pickFile.mockResolvedValue({
305 canceled: false,
306 result: [
307 {
308 uri: "file:///downloads/huge.zip",
309 name: "huge.zip",
310 type: "application/zip",
311 size: 2 * 1024 * 1024,
312 },
313 {
314 uri: "file:///downloads/report.pdf",
315 name: "report.pdf",
316 type: "application/pdf",
317 size: 42,
318 },
319 ],
320 });
321​
322 const result = await pickComposerFiles({ existingCount: 7, maxBytes: 1024 * 1024 });
323​
324 expect(result.files.map((file) => file.name)).toEqual(["report.pdf"]);
325 });
326​
327 it("removes the partial destination file when a copy fails midway", async () => {
328 mocks.copy.mockImplementation(() => {
329 throw new Error("disk full");
330 });
331​
332 await expect(
333 persistComposerAttachmentFile("file:///downloads/report.pdf", "report.pdf"),
334 ).rejects.toThrow("disk full");
335​
336 expect(mocks.delete).toHaveBeenCalledWith(
337 "file:///documents/t3-composer-attachments/attachment-id-report.pdf",
338 );
339 });
340​
341 it("deletes app-owned attachments without touching user-owned files", async () => {
342 await removePersistedComposerAttachmentFile(
343 "file:///documents/t3-composer-attachments/report.pdf",
344 );
345 await removePersistedComposerAttachmentFile("file:///downloads/report.pdf");
346​
347 expect(mocks.delete).toHaveBeenCalledOnce();
348 expect(mocks.delete).toHaveBeenCalledWith(
349 "file:///documents/t3-composer-attachments/report.pdf",
350 );
351 });
352​
353 it("removes a restored attachment from the current iOS document container", async () => {
354 const fileName = "33333333-3333-4333-8333-333333333333-report%20%23.pdf";
355 const oldUri = `file:///private/var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/${fileName}`;
356 mocks.documentUri =
357 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
358​
359 await removePersistedComposerAttachmentFile(oldUri);
360 await removePersistedComposerAttachmentFile(
361 `file:///var/mobile/Containers/Shared/FileProvider/other/Documents/t3-composer-attachments/${fileName}`,
362 );
363 await removePersistedComposerAttachmentFile(
364 `${mocks.documentUri}/t3-composer-attachments/..%2F..%2Fsender.pdf`,
365 );
366​
367 expect(mocks.delete.mock.calls).toEqual([
368 [`${mocks.documentUri}/t3-composer-attachments/${fileName}`],
369 ]);
370 });
371​
372 it("copies an open-in-place source from its actual container without rebasing it", async () => {
373 const sourceUri =
374 "file:///var/mobile/Containers/Data/Application/11111111-1111-4111-8111-111111111111/Documents/t3-composer-attachments/33333333-3333-4333-8333-333333333333-report.pdf";
375 mocks.documentUri =
376 "file:///var/mobile/Containers/Data/Application/22222222-2222-4222-8222-222222222222/Documents";
377​
378 await persistComposerAttachmentFile(sourceUri, "report.pdf");
379​
380 expect(mocks.copy).toHaveBeenCalledWith(
381 sourceUri,
382 `${mocks.documentUri}/t3-composer-attachments/attachment-id-report.pdf`,
383 );
384 expect(mocks.delete).not.toHaveBeenCalled();
385 });
386});