-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathstorage-object.test.ts
More file actions
991 lines (803 loc) · 34.1 KB
/
Copy pathstorage-object.test.ts
File metadata and controls
991 lines (803 loc) · 34.1 KB
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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
import { StorageObject } from '../../src/sdk/storage-object';
import type { ObjectView, ObjectDownloadURLView } from '../../src/resources/objects';
// Mock the Runloop client
jest.mock('../../src/index');
// Mock fetch globally
(global as any).fetch = jest.fn();
// Mock fs and path modules
jest.mock('node:fs/promises', () => ({
stat: jest.fn(),
readFile: jest.fn(),
}));
jest.mock('node:path', () => ({
basename: jest.fn((path) => path.split('/').pop()),
extname: jest.fn((path) => {
const ext = path.split('.').pop();
return ext ? `.${ext}` : '';
}),
join: jest.fn((...paths) => paths.join('/')),
}));
// Mock tar module
jest.mock('tar', () => ({
create: jest.fn(),
}));
describe('StorageObject (New API)', () => {
let mockClient: any;
let mockObjectData: ObjectView;
let mockFs: any;
let mockPath: any;
beforeEach(() => {
// Get mocked modules
mockFs = require('node:fs/promises');
mockPath = require('node:path');
// Create mock client instance with proper structure
mockClient = {
objects: {
create: jest.fn(),
retrieve: jest.fn(),
list: jest.fn(),
complete: jest.fn(),
download: jest.fn(),
delete: jest.fn(),
},
devboxes: {
createAndAwaitRunning: jest.fn(),
retrieve: jest.fn(),
execute: jest.fn(),
executeAsync: jest.fn(),
readFileContents: jest.fn(),
writeFileContents: jest.fn(),
downloadFile: jest.fn(),
uploadFile: jest.fn(),
shutdown: jest.fn(),
suspend: jest.fn(),
resume: jest.fn(),
keepAlive: jest.fn(),
snapshotDisk: jest.fn(),
createSSHKey: jest.fn(),
createTunnel: jest.fn(),
removeTunnel: jest.fn(),
listDiskSnapshots: jest.fn(),
},
blueprints: {
createAndAwaitBuildCompleted: jest.fn(),
retrieve: jest.fn(),
preview: jest.fn(),
logs: jest.fn(),
delete: jest.fn(),
},
diskSnapshots: {
queryStatus: jest.fn(),
update: jest.fn(),
delete: jest.fn(),
},
} as any;
// Mock object data
mockObjectData = {
id: 'object-123',
content_type: 'text',
name: 'test-file.txt',
state: 'UPLOADING',
size_bytes: null,
upload_url: 'https://s3.example.com/upload/test-file.txt?signature=...',
create_time_ms: Date.now(),
};
// Reset fetch mock
((global as any).fetch as jest.Mock).mockReset();
});
describe('create', () => {
it('should create a storage object and return a StorageObject instance', async () => {
mockClient.objects.create.mockResolvedValue(mockObjectData);
const obj = await StorageObject.create(mockClient, {
name: 'test-file.txt',
content_type: 'text',
metadata: { project: 'demo' },
});
expect(mockClient.objects.create).toHaveBeenCalledWith(
{
name: 'test-file.txt',
content_type: 'text',
metadata: { project: 'demo' },
},
undefined,
);
expect(obj).toBeInstanceOf(StorageObject);
expect(obj.id).toBe('object-123');
});
it('should support different content types', async () => {
const binaryObjectData = { ...mockObjectData, content_type: 'binary' as const };
mockClient.objects.create.mockResolvedValue(binaryObjectData);
const obj = await StorageObject.create(mockClient, {
name: 'data.bin',
content_type: 'binary',
});
expect(obj.id).toBe('object-123');
});
});
describe('fromId', () => {
it('should create a StorageObject instance by ID without API call', () => {
const obj = StorageObject.fromId(mockClient, 'object-123');
expect(obj).toBeInstanceOf(StorageObject);
expect(obj.id).toBe('object-123');
});
});
describe('list', () => {
it('should list all storage objects', async () => {
const obj1: ObjectView = {
id: 'object-1',
content_type: 'text',
name: 'file1.txt',
state: 'READ_ONLY',
create_time_ms: Date.now(),
};
const obj2: ObjectView = {
id: 'object-2',
content_type: 'binary',
name: 'file2.bin',
state: 'READ_ONLY',
create_time_ms: Date.now(),
};
const mockPage = {
[Symbol.asyncIterator]: async function* () {
yield obj1;
yield obj2;
},
};
mockClient.objects.list.mockResolvedValue(mockPage as any);
const objects = await StorageObject.list(mockClient, undefined, {});
expect(mockClient.objects.list).toHaveBeenCalledWith(undefined, {});
expect(objects).toHaveLength(2);
expect(objects[0]!.id).toBe('object-1');
expect(objects[1]!.id).toBe('object-2');
});
it('should support filtering', async () => {
const mockPage = {
[Symbol.asyncIterator]: async function* () {
yield mockObjectData;
},
};
mockClient.objects.list.mockResolvedValue(mockPage as any);
await StorageObject.list(mockClient, {
content_type: 'text',
search: 'test',
});
expect(mockClient.objects.list).toHaveBeenCalledWith(
{
content_type: 'text',
search: 'test',
},
undefined,
);
});
});
describe('instance methods', () => {
let storageObject: StorageObject;
beforeEach(async () => {
mockClient.objects.create.mockResolvedValue(mockObjectData);
storageObject = await StorageObject.create(mockClient, {
name: 'test-file.txt',
content_type: 'text',
});
});
describe('getInfo', () => {
it('should get object information from API', async () => {
const updatedData = { ...mockObjectData, state: 'READ_ONLY' as const };
mockClient.objects.retrieve.mockResolvedValue(updatedData);
const info = await storageObject.getInfo();
expect(mockClient.objects.retrieve).toHaveBeenCalledWith('object-123', undefined);
expect(info.state).toBe('READ_ONLY');
expect(info.id).toBe('object-123');
});
});
describe('uploadContent', () => {
it('should upload string content', async () => {
// Mock getInfo to return object data with upload_url
mockClient.objects.retrieve.mockResolvedValue(mockObjectData);
const mockFetchResponse = {
ok: true,
status: 200,
statusText: 'OK',
};
((global as any).fetch as jest.Mock).mockResolvedValue(mockFetchResponse);
await storageObject.uploadContent('Hello, World!');
expect((global as any).fetch).toHaveBeenCalledWith(mockObjectData.upload_url, {
method: 'PUT',
body: Buffer.from('Hello, World!', 'utf-8'),
});
});
it('should upload buffer content', async () => {
// Mock getInfo to return object data with upload_url
mockClient.objects.retrieve.mockResolvedValue(mockObjectData);
const mockFetchResponse = {
ok: true,
status: 200,
statusText: 'OK',
};
((global as any).fetch as jest.Mock).mockResolvedValue(mockFetchResponse);
const buffer = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
await storageObject.uploadContent(buffer);
expect((global as any).fetch).toHaveBeenCalledWith(mockObjectData.upload_url, {
method: 'PUT',
body: buffer,
});
});
it('should throw error when upload URL is not available', async () => {
const completedData = { ...mockObjectData, upload_url: null };
mockClient.objects.retrieve.mockResolvedValue(completedData);
const completedObj = StorageObject.fromId(mockClient, 'object-123');
await expect(completedObj.uploadContent('test')).rejects.toThrow('No upload URL available');
});
it('should throw error when upload fails', async () => {
// Mock getInfo to return object data with upload_url
mockClient.objects.retrieve.mockResolvedValue(mockObjectData);
const mockFetchResponse = {
ok: false,
status: 403,
statusText: 'Forbidden',
text: jest.fn().mockResolvedValue('Forbidden'),
};
((global as any).fetch as jest.Mock).mockResolvedValue(mockFetchResponse);
await expect(storageObject.uploadContent('test')).rejects.toThrow('Upload failed: 403');
});
});
describe('complete', () => {
it('should mark upload as complete', async () => {
const completedData = {
...mockObjectData,
state: 'READ_ONLY',
size_bytes: 13,
upload_url: null,
};
mockClient.objects.complete.mockResolvedValue(completedData);
await storageObject.complete();
expect(mockClient.objects.complete).toHaveBeenCalledWith('object-123', {}, undefined);
});
});
describe('getDownloadUrl', () => {
it('should generate a download URL', async () => {
const mockDownloadUrl: ObjectDownloadURLView = {
download_url: 'https://s3.example.com/download/test-file.txt?signature=...',
};
mockClient.objects.download.mockResolvedValue(mockDownloadUrl);
const result = await storageObject.getDownloadUrl(3600);
expect(mockClient.objects.download).toHaveBeenCalledWith(
'object-123',
{ duration_seconds: 3600 },
undefined,
);
expect(result.download_url).toBeTruthy();
});
it('should use default duration when not specified', async () => {
const mockDownloadUrl: ObjectDownloadURLView = {
download_url: 'https://s3.example.com/download/test-file.txt',
};
mockClient.objects.download.mockResolvedValue(mockDownloadUrl);
await storageObject.getDownloadUrl();
expect(mockClient.objects.download).toHaveBeenCalledWith(
'object-123',
{ duration_seconds: undefined },
undefined,
);
});
});
describe('downloadAsText', () => {
it('should download content as text', async () => {
const mockDownloadUrl: ObjectDownloadURLView = {
download_url: 'https://s3.example.com/download/test-file.txt',
};
mockClient.objects.download.mockResolvedValue(mockDownloadUrl);
const mockFetchResponse = {
ok: true,
text: jest.fn().mockResolvedValue('File contents'),
};
((global as any).fetch as jest.Mock).mockResolvedValue(mockFetchResponse);
const content = await storageObject.downloadAsText();
expect((global as any).fetch).toHaveBeenCalledWith(mockDownloadUrl.download_url);
expect(content).toBe('File contents');
});
it('should throw error when download fails', async () => {
const mockDownloadUrl: ObjectDownloadURLView = {
download_url: 'https://s3.example.com/download/test-file.txt',
};
mockClient.objects.download.mockResolvedValue(mockDownloadUrl);
const mockFetchResponse = {
ok: false,
status: 404,
statusText: 'Not Found',
};
((global as any).fetch as jest.Mock).mockResolvedValue(mockFetchResponse);
await expect(storageObject.downloadAsText()).rejects.toThrow('Download failed: 404 Not Found');
});
});
describe('downloadAsBuffer', () => {
it('should download content as buffer', async () => {
const mockDownloadUrl: ObjectDownloadURLView = {
download_url: 'https://s3.example.com/download/data.bin',
};
mockClient.objects.download.mockResolvedValue(mockDownloadUrl);
const mockArrayBuffer = new Uint8Array([0x89, 0x50, 0x4e, 0x47]).buffer;
const mockFetchResponse = {
ok: true,
arrayBuffer: jest.fn().mockResolvedValue(mockArrayBuffer),
};
((global as any).fetch as jest.Mock).mockResolvedValue(mockFetchResponse);
const buffer = await storageObject.downloadAsBuffer();
expect((global as any).fetch).toHaveBeenCalledWith(mockDownloadUrl.download_url);
expect(Buffer.isBuffer(buffer)).toBe(true);
expect(buffer.length).toBe(4);
});
});
describe('delete', () => {
it('should delete the storage object', async () => {
const deletedData = { ...mockObjectData, state: 'DELETED' };
mockClient.objects.delete.mockResolvedValue(deletedData);
await storageObject.delete();
expect(mockClient.objects.delete).toHaveBeenCalledWith('object-123', {}, undefined);
});
});
describe('id property', () => {
it('should expose object ID', () => {
expect(storageObject.id).toBe('object-123');
});
});
});
describe('complete workflow', () => {
it('should create, upload, complete, and download an object', async () => {
// Create
mockClient.objects.create.mockResolvedValue(mockObjectData);
const obj = await StorageObject.create(mockClient, {
name: 'workflow-test.txt',
content_type: 'text',
});
// Upload - mock getInfo for uploadContent
mockClient.objects.retrieve.mockResolvedValue(mockObjectData);
((global as any).fetch as jest.Mock).mockResolvedValue({ ok: true });
await obj.uploadContent('Test content');
// Complete
const completedData = { ...mockObjectData, state: 'READ_ONLY', size_bytes: 12 };
mockClient.objects.complete.mockResolvedValue(completedData);
await obj.complete();
// Download
const mockDownloadUrl: ObjectDownloadURLView = {
download_url: 'https://s3.example.com/download/workflow-test.txt',
};
mockClient.objects.download.mockResolvedValue(mockDownloadUrl);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
text: jest.fn().mockResolvedValue('Test content'),
});
const content = await obj.downloadAsText();
expect(content).toBe('Test content');
});
});
describe('uploadFromFile', () => {
beforeEach(() => {
// Clear all mocks
jest.clearAllMocks();
// Reset global fetch mock
((global as any).fetch as jest.Mock).mockClear();
});
it('should upload a text file with auto-detected content-type', async () => {
const mockFileBuffer = Buffer.from('test content');
mockFs.stat.mockResolvedValue({ isFile: () => true });
mockFs.readFile.mockResolvedValue(mockFileBuffer);
const mockObjectData = { id: 'file-123', upload_url: 'https://upload.example.com/file' };
const mockObjectInfo = { ...mockObjectData, name: 'test.txt', state: 'UPLOADING' };
const mockCompletedData = { ...mockObjectInfo, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromFile(mockClient, './test.txt', 'test.txt');
expect(mockClient.objects.create).toHaveBeenCalledWith(
{ name: 'test.txt', content_type: 'text', metadata: null },
undefined,
);
expect(mockFs.readFile).toHaveBeenCalledWith('./test.txt');
expect(result).toBeInstanceOf(StorageObject);
expect(result.id).toBe('file-123');
});
it('should upload a file with explicit content-type and custom name', async () => {
const mockFileBuffer = Buffer.from('binary content');
mockFs.stat.mockResolvedValue({ isFile: () => true });
mockFs.readFile.mockResolvedValue(mockFileBuffer);
const mockObjectData = { id: 'file-456', upload_url: 'https://upload.example.com/file' };
const mockObjectInfo = { ...mockObjectData, name: 'custom.bin', state: 'UPLOADING' };
const mockCompletedData = { ...mockObjectInfo, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromFile(mockClient, './data.bin', 'custom.bin', {
contentType: 'binary',
metadata: { source: 'test' },
});
expect(mockClient.objects.create).toHaveBeenCalledWith(
{ name: 'custom.bin', content_type: 'binary', metadata: { source: 'test' } },
{ contentType: 'binary', metadata: { source: 'test' } },
);
expect(result.id).toBe('file-456');
});
it('should throw error in browser environment', async () => {
// Mock browser environment
const originalProcess = global.process;
delete (global as any).process;
await expect(StorageObject.uploadFromFile(mockClient, './test.txt', 'test.txt')).rejects.toThrow(
'File upload methods are only available in Node.js environment',
);
// Restore process
global.process = originalProcess;
});
it('should handle file read errors gracefully', async () => {
mockFs.stat.mockRejectedValue(new Error('File not found'));
await expect(
StorageObject.uploadFromFile(mockClient, './nonexistent.txt', 'nonexistent.txt', {}),
).rejects.toThrow('Failed to access file ./nonexistent.txt: File not found');
});
it('should handle upload failures gracefully', async () => {
const mockFileBuffer = Buffer.from('test content');
mockFs.stat.mockResolvedValue({ isFile: () => true });
mockFs.readFile.mockResolvedValue(mockFileBuffer);
const mockObjectData = { id: 'file-789', upload_url: 'https://upload.example.com/file' };
const mockObjectInfo = { ...mockObjectData, name: 'test.txt', state: 'UPLOADING' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: false,
status: 500,
statusText: 'Internal Server Error',
});
await expect(StorageObject.uploadFromFile(mockClient, './test.txt', 'test.txt', {})).rejects.toThrow(
'Failed to upload file: Upload failed: 500 Internal Server Error',
);
});
it('should upload an archive file with auto-detected content-type', async () => {
const mockArchiveBuffer = Buffer.from('compressed archive content');
mockFs.stat.mockResolvedValue({ isFile: () => true });
mockFs.readFile.mockResolvedValue(mockArchiveBuffer);
const mockObjectData = { id: 'archive-123', upload_url: 'https://upload.example.com/archive' };
const mockObjectInfo = { ...mockObjectData, name: 'project.tar.gz', state: 'UPLOADING' };
const mockCompletedData = { ...mockObjectInfo, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromFile(
mockClient,
'./files/test-archive.tar.gz',
'test-archive.tar.gz',
);
expect(mockClient.objects.create).toHaveBeenCalledWith(
{ name: 'test-archive.tar.gz', content_type: 'tgz', metadata: null },
undefined,
);
expect(mockFs.readFile).toHaveBeenCalledWith('./files/test-archive.tar.gz');
expect(result).toBeInstanceOf(StorageObject);
expect(result.id).toBe('archive-123');
});
});
describe('uploadFromText', () => {
beforeEach(() => {
// Clear all mocks
jest.clearAllMocks();
// Reset global fetch mock
((global as any).fetch as jest.Mock).mockClear();
});
it('should upload text content with text content-type', async () => {
const textContent = 'Hello, World!';
const mockObjectData = { id: 'text-123', upload_url: 'https://upload.example.com/text' };
const mockObjectInfo = { ...mockObjectData, name: 'hello.txt', state: 'UPLOADING' };
const mockCompletedData = { ...mockObjectInfo, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromText(mockClient, textContent, 'hello.txt');
expect(mockClient.objects.create).toHaveBeenCalledWith(
{ name: 'hello.txt', content_type: 'text', metadata: null },
undefined,
);
// uploadFromText uses Blob for fetch body
const fetchCalls = ((global as any).fetch as jest.Mock).mock.calls;
expect(fetchCalls[0][0]).toBe('https://upload.example.com/text');
expect(fetchCalls[0][1].method).toBe('PUT');
expect(fetchCalls[0][1].body).toBeInstanceOf(Blob);
expect(result).toBeInstanceOf(StorageObject);
expect(result.id).toBe('text-123');
});
it('should upload text content with custom metadata', async () => {
const textContent = '{"key": "value"}';
const mockObjectData = { id: 'json-123', upload_url: 'https://upload.example.com/json' };
const mockObjectInfo = { ...mockObjectData, name: 'data.json', state: 'UPLOADING' };
const mockCompletedData = { ...mockObjectInfo, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromText(mockClient, textContent, 'data.json', {
metadata: { format: 'json' },
});
expect(mockClient.objects.create).toHaveBeenCalledWith(
{ name: 'data.json', content_type: 'text', metadata: { format: 'json' } },
{ metadata: { format: 'json' } },
);
expect(result.id).toBe('json-123');
});
it('should handle upload failures gracefully', async () => {
const textContent = 'test content';
const mockObjectData = { id: 'text-456', upload_url: 'https://upload.example.com/text' };
const mockObjectInfo = { ...mockObjectData, name: 'test.txt', state: 'UPLOADING' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: false,
status: 403,
statusText: 'Forbidden',
});
await expect(StorageObject.uploadFromText(mockClient, textContent, 'test.txt')).rejects.toThrow(
'Failed to upload text: Upload failed: 403 Forbidden',
);
});
it('should complete full upload lifecycle', async () => {
const textContent = 'lifecycle test content';
const mockObjectData = { id: 'lifecycle-text-123', upload_url: 'https://upload.example.com/lifecycle' };
const mockObjectInfo = { ...mockObjectData, name: 'lifecycle.txt', state: 'UPLOADING' };
const mockCompletedData = { ...mockObjectInfo, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromText(mockClient, textContent, 'lifecycle.txt');
// Verify all three steps were called
expect(mockClient.objects.create).toHaveBeenCalledTimes(1);
expect((global as any).fetch).toHaveBeenCalledTimes(1);
expect(mockClient.objects.complete).toHaveBeenCalledTimes(1);
expect(result).toBeInstanceOf(StorageObject);
});
});
describe('uploadFromBuffer', () => {
beforeEach(() => {
// Clear all mocks
jest.clearAllMocks();
// Reset global fetch mock
((global as any).fetch as jest.Mock).mockClear();
});
it('should upload buffer with specified content-type and name', async () => {
const buffer = Buffer.from('buffer content');
const mockObjectData = { id: 'buffer-123', upload_url: 'https://upload.example.com/buffer' };
const mockObjectInfo = { ...mockObjectData, name: 'buffer.txt', state: 'UPLOADING' };
const mockCompletedData = { ...mockObjectInfo, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromBuffer(mockClient, buffer, 'buffer.txt', 'text', {
metadata: { source: 'buffer' },
});
expect(mockClient.objects.create).toHaveBeenCalledWith(
{ name: 'buffer.txt', content_type: 'text', metadata: { source: 'buffer' } },
{ metadata: { source: 'buffer' } },
);
// uploadFromBuffer uses Blob for fetch body
const fetchCalls = ((global as any).fetch as jest.Mock).mock.calls;
expect(fetchCalls[0][0]).toBe('https://upload.example.com/buffer');
expect(fetchCalls[0][1].method).toBe('PUT');
expect(fetchCalls[0][1].body).toBeInstanceOf(Blob);
expect(result).toBeInstanceOf(StorageObject);
expect(result.id).toBe('buffer-123');
});
it('should throw error in browser environment', async () => {
// Mock browser environment
const originalProcess = global.process;
delete (global as any).process;
const buffer = Buffer.from('test');
await expect(StorageObject.uploadFromBuffer(mockClient, buffer, 'test.txt', 'text')).rejects.toThrow(
'File upload methods are only available in Node.js environment',
);
// Restore process
global.process = originalProcess;
});
it('should handle upload failures gracefully', async () => {
const buffer = Buffer.from('test content');
const mockObjectData = { id: 'buffer-456', upload_url: 'https://upload.example.com/buffer' };
const mockObjectInfo = { ...mockObjectData, name: 'test.txt', state: 'UPLOADING' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: false,
status: 403,
statusText: 'Forbidden',
});
await expect(StorageObject.uploadFromBuffer(mockClient, buffer, 'test.txt', 'text')).rejects.toThrow(
'Failed to upload buffer: Upload failed: 403 Forbidden',
);
});
it('should complete full upload lifecycle', async () => {
const buffer = Buffer.from('lifecycle test');
const mockObjectData = { id: 'lifecycle-123', upload_url: 'https://upload.example.com/lifecycle' };
const mockObjectInfo = { ...mockObjectData, name: 'lifecycle.txt', state: 'UPLOADING' };
const mockCompletedData = { ...mockObjectInfo, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromBuffer(mockClient, buffer, 'lifecycle.txt', 'text');
// Verify all three steps were called
expect(mockClient.objects.create).toHaveBeenCalledTimes(1);
expect((global as any).fetch).toHaveBeenCalledTimes(1);
expect(mockClient.objects.complete).toHaveBeenCalledTimes(1);
expect(result).toBeInstanceOf(StorageObject);
});
});
describe('uploadFromDir', () => {
let mockTar: any;
beforeEach(() => {
// Clear all mocks
jest.clearAllMocks();
// Reset global fetch mock
((global as any).fetch as jest.Mock).mockClear();
// Get tar mock
mockTar = require('tar');
});
it('should upload a directory as gzipped tarball', async () => {
// Mock directory exists
mockFs.stat.mockResolvedValue({ isDirectory: () => true });
// Mock tar stream
const mockTarballBuffer = Buffer.from('compressed tarball content');
mockTar.create.mockReturnValue({
[Symbol.asyncIterator]: async function* () {
yield mockTarballBuffer;
},
});
const mockObjectData = { id: 'dir-123', upload_url: 'https://upload.example.com/dir' };
const mockObjectInfo = { ...mockObjectData, name: 'project.tar.gz', state: 'UPLOADING' };
const mockCompletedData = { ...mockObjectInfo, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.retrieve.mockResolvedValue(mockObjectInfo);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromDir(mockClient, './my-project', {
name: 'project.tar.gz',
});
expect(mockClient.objects.create).toHaveBeenCalledWith(
{ name: 'project.tar.gz', content_type: 'tgz' },
undefined,
);
expect(mockTar.create).toHaveBeenCalled();
expect(result).toBeInstanceOf(StorageObject);
expect(result.id).toBe('dir-123');
});
it('should upload directory with TTL and metadata', async () => {
// Mock directory exists
mockFs.stat.mockResolvedValue({ isDirectory: () => true });
// Mock tar stream
const mockTarballBuffer = Buffer.from('compressed tarball');
mockTar.create.mockReturnValue({
[Symbol.asyncIterator]: async function* () {
yield mockTarballBuffer;
},
});
const mockObjectData = { id: 'dir-456', upload_url: 'https://upload.example.com/dir' };
const mockCompletedData = { ...mockObjectData, state: 'READ_ONLY' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
mockClient.objects.complete.mockResolvedValue(mockCompletedData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: true,
status: 200,
statusText: 'OK',
});
const result = await StorageObject.uploadFromDir(mockClient, './my-project', {
name: 'project.tar.gz',
ttl_ms: 3600000,
metadata: { project: 'demo' },
});
expect(mockClient.objects.create).toHaveBeenCalledWith(
{ name: 'project.tar.gz', content_type: 'tgz', metadata: { project: 'demo' }, ttl_ms: 3600000 },
undefined,
);
expect(result.id).toBe('dir-456');
});
it('should throw error if path is not a directory', async () => {
mockFs.stat.mockResolvedValue({ isDirectory: () => false });
await expect(
StorageObject.uploadFromDir(mockClient, './file.txt', { name: 'archive.tar.gz' }),
).rejects.toThrow('Path is not a directory: ./file.txt');
});
it('should throw error if directory does not exist', async () => {
mockFs.stat.mockRejectedValue(new Error('ENOENT: no such file or directory'));
await expect(
StorageObject.uploadFromDir(mockClient, './nonexistent', { name: 'archive.tar.gz' }),
).rejects.toThrow('Failed to access directory ./nonexistent');
});
it('should throw error in browser environment', async () => {
const originalProcess = global.process;
delete (global as any).process;
await expect(
StorageObject.uploadFromDir(mockClient, './project', { name: 'project.tar.gz' }),
).rejects.toThrow('File upload methods are only available in Node.js environment');
global.process = originalProcess;
});
it('should handle upload failures gracefully', async () => {
mockFs.stat.mockResolvedValue({ isDirectory: () => true });
const mockTarballBuffer = Buffer.from('tarball');
mockTar.create.mockReturnValue({
[Symbol.asyncIterator]: async function* () {
yield mockTarballBuffer;
},
});
const mockObjectData = { id: 'dir-999', upload_url: 'https://upload.example.com/dir' };
mockClient.objects.create.mockResolvedValue(mockObjectData);
((global as any).fetch as jest.Mock).mockResolvedValue({
ok: false,
status: 500,
statusText: 'Internal Server Error',
});
await expect(
StorageObject.uploadFromDir(mockClient, './project', { name: 'project.tar.gz' }),
).rejects.toThrow('Failed to upload tarball: Upload failed: 500 Internal Server Error');
});
});
describe('error handling', () => {
it('should handle create errors', async () => {
const error = new Error('Create failed');
mockClient.objects.create.mockRejectedValue(error);
await expect(
StorageObject.create(
mockClient,
{
name: 'test.txt',
content_type: 'text',
},
{},
),
).rejects.toThrow('Create failed');
});
it('should handle retrieval errors in getInfo', async () => {
const error = new Error('Not found');
mockClient.objects.retrieve.mockRejectedValue(error);
const obj = StorageObject.fromId(mockClient, 'non-existent');
await expect(obj.getInfo()).rejects.toThrow('Not found');
});
it('should handle list errors', async () => {
const error = new Error('List failed');
mockClient.objects.list.mockRejectedValue(error);
await expect(StorageObject.list(mockClient, undefined, {})).rejects.toThrow('List failed');
});
});
});