Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

golangCompletion.test.ts 24 KB

You have to be logged in to leave a comment. Sign In
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
  1. import { exec } from 'child_process';
  2. import fs from 'fs';
  3. import path from 'path';
  4. import { getCache, isCacheEnabled } from '../../src/cache';
  5. import { GolangProvider } from '../../src/providers/golangCompletion';
  6. jest.mock('child_process');
  7. jest.mock('../../src/cache');
  8. jest.mock('fs');
  9. jest.mock('path');
  10. jest.mock('../../src/util', () => {
  11. const actual = jest.requireActual('../../src/util');
  12. return {
  13. ...actual,
  14. parsePathOrGlob: jest.fn(() => ({
  15. extension: 'go',
  16. functionName: undefined,
  17. isPathPattern: false,
  18. filePath: '/absolute/path/to/script.go',
  19. })),
  20. };
  21. });
  22. describe('GolangProvider', () => {
  23. const mockExec = jest.mocked(exec);
  24. const mockGetCache = jest.mocked(getCache);
  25. const mockIsCacheEnabled = jest.mocked(isCacheEnabled);
  26. const mockReadFileSync = jest.mocked(fs.readFileSync);
  27. const mockResolve = jest.mocked(path.resolve);
  28. const mockMkdtempSync = jest.mocked(fs.mkdtempSync);
  29. const mockExistsSync = jest.mocked(fs.existsSync);
  30. const mockRmSync = jest.mocked(fs.rmSync);
  31. const mockReaddirSync = jest.mocked(fs.readdirSync);
  32. const mockCopyFileSync = jest.mocked(fs.copyFileSync);
  33. const mockMkdirSync = jest.mocked(fs.mkdirSync);
  34. beforeEach(() => {
  35. jest.clearAllMocks();
  36. mockGetCache.mockResolvedValue({
  37. get: jest.fn(),
  38. set: jest.fn(),
  39. } as never);
  40. mockIsCacheEnabled.mockReturnValue(false);
  41. mockReadFileSync.mockReturnValue('mock file content');
  42. const mockParsePathOrGlob = jest.requireMock('../../src/util').parsePathOrGlob;
  43. mockParsePathOrGlob.mockImplementation((basePath: string, runPath: string) => {
  44. if (!basePath && runPath === 'script.go') {
  45. return {
  46. filePath: 'script.go',
  47. functionName: undefined,
  48. isPathPattern: false,
  49. extension: 'go',
  50. };
  51. }
  52. return {
  53. filePath: runPath.replace(/^(file:\/\/|golang:)/, '').split(':')[0],
  54. functionName: runPath.includes(':') ? runPath.split(':')[1] : undefined,
  55. isPathPattern: false,
  56. extension: 'go',
  57. };
  58. });
  59. mockResolve.mockImplementation((p: string) => {
  60. if (!p) {
  61. return '/absolute/path/undefined';
  62. }
  63. if (p === 'script.go') {
  64. return 'script.go';
  65. }
  66. return typeof p === 'string' && p.includes('script.go') ? '/absolute/path/to/script.go' : p;
  67. });
  68. const mockRelative = jest.mocked(path.relative);
  69. mockRelative.mockImplementation((from: string, to: string) => {
  70. if (!from && to === 'script.go') {
  71. return 'script.go';
  72. }
  73. return to;
  74. });
  75. const mockDirname = jest.mocked(path.dirname);
  76. mockDirname.mockImplementation((p: string) => {
  77. const paths: Record<string, string> = {
  78. '/absolute/path/to/script.go': '/absolute/path/to',
  79. '/absolute/path/to': '/absolute/path',
  80. '/absolute/path': '/absolute',
  81. '/absolute': '/',
  82. };
  83. return paths[p] || p;
  84. });
  85. const mockJoin = jest.mocked(path.join);
  86. mockJoin.mockImplementation((...paths: string[]) => {
  87. const validPaths = paths.filter((p) => p !== undefined);
  88. if (
  89. validPaths.length === 2 &&
  90. validPaths[1] === 'go.mod' &&
  91. validPaths[0] === '/absolute/path/to'
  92. ) {
  93. return '/absolute/path/to/go.mod';
  94. }
  95. return validPaths.join('/').replace(/\/+/g, '/');
  96. });
  97. mockMkdtempSync.mockReturnValue('/tmp/golang-provider-xyz');
  98. mockExistsSync.mockImplementation(
  99. (p: fs.PathLike) => p.toString() === '/absolute/path/to/go.mod' || true,
  100. );
  101. mockReaddirSync.mockReturnValue([
  102. { name: 'test.go', isDirectory: () => false },
  103. ] as unknown as fs.Dirent[]);
  104. mockMkdirSync.mockImplementation(() => undefined);
  105. mockExec.mockImplementation(((cmd: string, callback: any) => {
  106. if (!callback) {
  107. return {} as any;
  108. }
  109. process.nextTick(() => {
  110. if (cmd.includes('cd') && cmd.includes('go build')) {
  111. callback(null, { stdout: '', stderr: '' }, '');
  112. } else if (cmd.includes('golang_wrapper')) {
  113. callback(null, { stdout: '{"output":"test output"}', stderr: '' }, '');
  114. } else {
  115. callback(new Error('test error'), { stdout: '', stderr: '' }, '');
  116. }
  117. });
  118. return {} as any;
  119. }) as any);
  120. });
  121. describe('constructor', () => {
  122. it('should initialize with correct properties', () => {
  123. const provider = new GolangProvider('script.go', {
  124. id: 'testId',
  125. config: { basePath: '/absolute/path/to' },
  126. });
  127. expect(provider.id()).toBe('testId');
  128. });
  129. it('should initialize with golang: syntax', () => {
  130. const provider = new GolangProvider('golang:script.go', {
  131. id: 'testId',
  132. config: { basePath: '/base' },
  133. });
  134. expect(provider.id()).toBe('testId');
  135. });
  136. it('should initialize with file:// prefix', () => {
  137. const provider = new GolangProvider('file://script.go', {
  138. id: 'testId',
  139. config: { basePath: '/base' },
  140. });
  141. expect(provider.id()).toBe('testId');
  142. });
  143. it('should initialize with file:// prefix and function name', () => {
  144. const provider = new GolangProvider('file://script.go:function_name', {
  145. id: 'testId',
  146. config: { basePath: '/base' },
  147. });
  148. expect(provider.id()).toBe('testId');
  149. });
  150. it('should handle undefined basePath and use default id', () => {
  151. const provider = new GolangProvider('script.go');
  152. expect(provider.id()).toBe('golang:script.go:default');
  153. expect(provider.config).toEqual({});
  154. });
  155. it('should use class id() method when no id is provided in options', () => {
  156. const provider = new GolangProvider('script.go:custom_function');
  157. expect(provider.id()).toBe('golang:script.go:custom_function');
  158. });
  159. it('should allow id() override and later retrieval', () => {
  160. const provider = new GolangProvider('script.go');
  161. expect(provider.id()).toBe('golang:script.go:default');
  162. const originalId = provider.id;
  163. provider.id = () => 'overridden-id';
  164. expect(provider.id()).toBe('overridden-id');
  165. provider.id = originalId;
  166. expect(provider.id()).toBe('golang:script.go:default');
  167. });
  168. });
  169. describe('caching', () => {
  170. it('should use cached result when available', async () => {
  171. const provider = new GolangProvider('script.go', {
  172. config: { basePath: '/absolute/path/to' },
  173. });
  174. mockIsCacheEnabled.mockReturnValue(true);
  175. const mockCache = {
  176. get: jest.fn().mockResolvedValue(JSON.stringify({ output: 'cached result' })),
  177. set: jest.fn(),
  178. };
  179. mockGetCache.mockResolvedValue(mockCache as never);
  180. const result = await provider.callApi('test prompt');
  181. expect(mockCache.get).toHaveBeenCalledWith(expect.stringContaining('golang:'));
  182. expect(mockExec).not.toHaveBeenCalled();
  183. expect(result).toEqual({ output: 'cached result' });
  184. });
  185. it('should handle cache errors', async () => {
  186. const provider = new GolangProvider('script.go', {
  187. config: { basePath: '/absolute/path/to' },
  188. });
  189. mockIsCacheEnabled.mockReturnValue(true);
  190. const mockCache = {
  191. get: jest.fn().mockRejectedValue(new Error('Cache error')),
  192. set: jest.fn(),
  193. };
  194. mockGetCache.mockResolvedValue(mockCache as never);
  195. await expect(provider.callApi('test prompt')).rejects.toThrow('Cache error');
  196. });
  197. it('should handle cache set errors', async () => {
  198. const provider = new GolangProvider('script.go', {
  199. config: { basePath: '/absolute/path/to' },
  200. });
  201. mockIsCacheEnabled.mockReturnValue(true);
  202. const mockCache = {
  203. get: jest.fn().mockResolvedValue(null),
  204. set: jest.fn().mockRejectedValue(new Error('Cache set error')),
  205. };
  206. mockGetCache.mockResolvedValue(mockCache as never);
  207. await expect(provider.callApi('test prompt')).rejects.toThrow('Cache set error');
  208. });
  209. it('should not cache results that contain errors', async () => {
  210. const provider = new GolangProvider('script.go', {
  211. config: { basePath: '/absolute/path/to' },
  212. });
  213. mockIsCacheEnabled.mockReturnValue(true);
  214. const mockCache = {
  215. get: jest.fn().mockResolvedValue(null),
  216. set: jest.fn(),
  217. };
  218. mockGetCache.mockResolvedValue(mockCache as never);
  219. mockExec.mockImplementation(((cmd: string, callback: any) => {
  220. if (!callback) {
  221. return {} as any;
  222. }
  223. process.nextTick(() => {
  224. if (cmd.includes('golang_wrapper')) {
  225. callback(null, { stdout: '{"error":"test error in result"}', stderr: '' }, '');
  226. } else {
  227. callback(null, { stdout: '', stderr: '' }, '');
  228. }
  229. });
  230. return {} as any;
  231. }) as any);
  232. const result = await provider.callApi('test prompt');
  233. expect(result).toEqual({ error: 'test error in result' });
  234. expect(mockCache.set).not.toHaveBeenCalled();
  235. });
  236. it('should handle circular references in vars when cache is disabled', async () => {
  237. const provider = new GolangProvider('script.go', {
  238. config: { basePath: '/absolute/path/to' },
  239. });
  240. mockIsCacheEnabled.mockReturnValue(false);
  241. const circularObj: any = { name: 'circular' };
  242. circularObj.self = circularObj;
  243. const spy = jest
  244. .spyOn(provider as any, 'executeGolangScript')
  245. .mockImplementation(() => Promise.resolve({ output: 'mocked result' }));
  246. const result = await provider.callApi('test prompt', {
  247. prompt: {
  248. raw: 'test prompt',
  249. label: 'test',
  250. },
  251. vars: { circular: circularObj },
  252. });
  253. expect(result).toEqual({ output: 'mocked result' });
  254. expect(spy).toHaveBeenCalledWith(
  255. 'test prompt',
  256. expect.objectContaining({
  257. vars: expect.objectContaining({ circular: expect.anything() }),
  258. }),
  259. 'call_api',
  260. );
  261. spy.mockRestore();
  262. });
  263. it('should execute script directly when cache is not enabled', async () => {
  264. const provider = new GolangProvider('script.go', {
  265. config: { basePath: '/absolute/path/to' },
  266. });
  267. mockIsCacheEnabled.mockReturnValue(false);
  268. mockGetCache.mockResolvedValue({
  269. get: jest.fn().mockResolvedValue(null),
  270. set: jest.fn(),
  271. } as never);
  272. mockExec.mockImplementation(((cmd: string, callback: any) => {
  273. if (!callback) {
  274. return {} as any;
  275. }
  276. process.nextTick(() =>
  277. callback(null, { stdout: '{"output":"direct execution result"}', stderr: '' }, ''),
  278. );
  279. return {} as any;
  280. }) as any);
  281. const result = await provider.callApi('test prompt');
  282. expect(result).toEqual({ output: 'direct execution result' });
  283. const mockCache = await mockGetCache.mock.results[0].value;
  284. expect(mockCache.set).not.toHaveBeenCalled();
  285. });
  286. });
  287. describe('cleanup', () => {
  288. it('should clean up on error', async () => {
  289. const provider = new GolangProvider('script.go', {
  290. config: { basePath: '/absolute/path/to' },
  291. });
  292. mockExec.mockImplementation(((cmd: string, callback: any) => {
  293. if (!callback) {
  294. return {} as any;
  295. }
  296. process.nextTick(() => {
  297. callback(new Error('test error'), { stdout: '', stderr: '' }, '');
  298. });
  299. return {} as any;
  300. }) as any);
  301. await expect(provider.callApi('test prompt')).rejects.toThrow(
  302. 'Error running Golang script: test error',
  303. );
  304. expect(mockRmSync).toHaveBeenCalledWith(
  305. expect.stringContaining('golang-provider'),
  306. expect.objectContaining({ recursive: true, force: true }),
  307. );
  308. });
  309. });
  310. describe('API methods', () => {
  311. it('should call callEmbeddingApi successfully', async () => {
  312. const provider = new GolangProvider('script.go', {
  313. config: { basePath: '/absolute/path/to' },
  314. });
  315. mockExec.mockImplementation(((cmd: string, callback: any) => {
  316. if (!callback) {
  317. return {} as any;
  318. }
  319. process.nextTick(() => {
  320. callback(
  321. null,
  322. {
  323. stdout: cmd.includes('golang_wrapper') ? '{"embedding":[0.1,0.2,0.3]}' : '',
  324. stderr: '',
  325. },
  326. '',
  327. );
  328. });
  329. return {} as any;
  330. }) as any);
  331. const result = await provider.callEmbeddingApi('test prompt');
  332. expect(result).toEqual({ embedding: [0.1, 0.2, 0.3] });
  333. });
  334. it('should call callClassificationApi successfully', async () => {
  335. const provider = new GolangProvider('script.go', {
  336. config: { basePath: '/absolute/path/to' },
  337. });
  338. mockExec.mockImplementation(((cmd: string, callback: any) => {
  339. if (!callback) {
  340. return {} as any;
  341. }
  342. process.nextTick(() => {
  343. callback(
  344. null,
  345. {
  346. stdout: cmd.includes('golang_wrapper') ? '{"classification":"test_class"}' : '',
  347. stderr: '',
  348. },
  349. '',
  350. );
  351. });
  352. return {} as any;
  353. }) as any);
  354. const result = await provider.callClassificationApi('test prompt');
  355. expect(result).toEqual({ classification: 'test_class' });
  356. });
  357. it('should handle stderr output without failing', async () => {
  358. const provider = new GolangProvider('script.go', {
  359. config: { basePath: '/absolute/path/to' },
  360. });
  361. mockExec.mockImplementation(((cmd: string, callback: any) => {
  362. if (!callback) {
  363. return {} as any;
  364. }
  365. process.nextTick(() => {
  366. callback(
  367. null,
  368. {
  369. stdout: cmd.includes('golang_wrapper') ? '{"output":"test"}' : '',
  370. stderr: 'warning: some go warning',
  371. },
  372. '',
  373. );
  374. });
  375. return {} as any;
  376. }) as any);
  377. const result = await provider.callApi('test prompt');
  378. expect(result).toEqual({ output: 'test' });
  379. });
  380. });
  381. describe('findModuleRoot', () => {
  382. it('should throw error when go.mod is not found', async () => {
  383. mockExistsSync.mockImplementation(() => false);
  384. const provider = new GolangProvider('script.go', {
  385. config: { basePath: '/absolute/path/to' },
  386. });
  387. await expect(provider.callApi('test prompt')).rejects.toThrow(
  388. 'Could not find go.mod file in any parent directory',
  389. );
  390. });
  391. it('should find go.mod in parent directory', async () => {
  392. const checkedPaths: string[] = [];
  393. mockExistsSync.mockImplementation((p: fs.PathLike) => {
  394. const pathStr = p.toString();
  395. checkedPaths.push(pathStr);
  396. return pathStr.endsWith('/absolute/path/to/go.mod');
  397. });
  398. const mockDirname = jest.mocked(path.dirname);
  399. mockDirname.mockImplementation((p: string) => p.split('/').slice(0, -1).join('/'));
  400. const mockResolve = jest.mocked(path.resolve);
  401. mockResolve.mockImplementation((p: string) =>
  402. p.startsWith('/') ? p : `/absolute/path/to/${p}`,
  403. );
  404. const mockJoin = jest.mocked(path.join);
  405. mockJoin.mockImplementation((...paths: string[]) => paths.join('/').replace(/\/+/g, '/'));
  406. const provider = new GolangProvider('script.go', {
  407. config: { basePath: '/absolute/path/to/subdir' },
  408. });
  409. mockExec.mockImplementation(((cmd: string, callback: any) => {
  410. if (!callback) {
  411. return {} as any;
  412. }
  413. process.nextTick(() => callback(null, { stdout: '{"output":"test"}', stderr: '' }, ''));
  414. return {} as any;
  415. }) as any);
  416. const result = await provider.callApi('test prompt');
  417. expect(result).toEqual({ output: 'test' });
  418. expect(checkedPaths).toContain('/absolute/path/to/go.mod');
  419. expect(mockExistsSync).toHaveBeenCalledWith(
  420. expect.stringContaining('/absolute/path/to/go.mod'),
  421. );
  422. });
  423. });
  424. describe('script execution', () => {
  425. it('should handle JSON parsing errors', async () => {
  426. const provider = new GolangProvider('script.go', {
  427. config: { basePath: '/absolute/path/to' },
  428. });
  429. mockExec.mockImplementation(((cmd: string, callback: any) => {
  430. if (!callback) {
  431. return {} as any;
  432. }
  433. process.nextTick(() => {
  434. callback(
  435. null,
  436. {
  437. stdout: cmd.includes('golang_wrapper') ? 'invalid json' : '',
  438. stderr: '',
  439. },
  440. '',
  441. );
  442. });
  443. return {} as any;
  444. }) as any);
  445. await expect(provider.callApi('test prompt')).rejects.toThrow('Error running Golang script');
  446. });
  447. it('should use custom function name when specified', async () => {
  448. const mockParsePathOrGlob = jest.requireMock('../../src/util').parsePathOrGlob;
  449. mockParsePathOrGlob.mockReturnValueOnce({
  450. filePath: '/absolute/path/to/script.go',
  451. functionName: 'custom_function',
  452. isPathPattern: false,
  453. extension: 'go',
  454. });
  455. const provider = new GolangProvider('script.go:custom_function', {
  456. config: { basePath: '/absolute/path/to' },
  457. });
  458. let executedCommand = '';
  459. mockExec.mockImplementation(((cmd: string, callback: any) => {
  460. if (!callback) {
  461. return {} as any;
  462. }
  463. if (cmd.includes('golang_wrapper')) {
  464. executedCommand = cmd;
  465. }
  466. process.nextTick(() => callback(null, { stdout: '{"output":"test"}', stderr: '' }, ''));
  467. return {} as any;
  468. }) as any);
  469. await provider.callApi('test prompt');
  470. expect(executedCommand).toContain('custom_function');
  471. expect(executedCommand.split(' ')[2]).toBe('custom_function');
  472. });
  473. it('should use custom go executable when specified', async () => {
  474. const provider = new GolangProvider('script.go', {
  475. config: {
  476. basePath: '/absolute/path/to',
  477. goExecutable: '/custom/go',
  478. },
  479. });
  480. let buildCommand = '';
  481. mockExec.mockImplementation(((cmd: string, callback: any) => {
  482. if (!callback) {
  483. return {} as any;
  484. }
  485. if (cmd.includes('go build')) {
  486. buildCommand = cmd;
  487. }
  488. process.nextTick(() => callback(null, { stdout: '{"output":"test"}', stderr: '' }, ''));
  489. return {} as any;
  490. }) as any);
  491. await provider.callApi('test prompt');
  492. expect(buildCommand).toContain('/custom/go build');
  493. });
  494. it('should handle circular references in args', async () => {
  495. const provider = new GolangProvider('script.go', {
  496. config: { basePath: '/absolute/path/to' },
  497. });
  498. // Create circular reference
  499. const circularObj: any = { name: 'circular' };
  500. circularObj.self = circularObj;
  501. // We need to access a private method, so we'll create a spy using any type assertions
  502. const spy = jest
  503. .spyOn(provider as any, 'executeGolangScript')
  504. .mockImplementation(() => Promise.resolve({ output: 'mocked result' }));
  505. // This should not throw even with circular references
  506. const result = await provider.callApi('test prompt', {
  507. prompt: {
  508. raw: 'test prompt',
  509. label: 'test',
  510. },
  511. vars: { circular: circularObj },
  512. });
  513. // Verify the result and that executeGolangScript was called
  514. expect(result).toEqual({ output: 'mocked result' });
  515. expect(spy).toHaveBeenCalledWith(
  516. 'test prompt',
  517. expect.objectContaining({
  518. vars: expect.objectContaining({ circular: expect.anything() }),
  519. }),
  520. 'call_api',
  521. );
  522. // Restore the original implementation
  523. spy.mockRestore();
  524. });
  525. });
  526. describe('file operations', () => {
  527. it('should handle directory copy errors', async () => {
  528. const provider = new GolangProvider('script.go', {
  529. config: { basePath: '/absolute/path/to' },
  530. });
  531. mockReaddirSync.mockImplementation(() => {
  532. throw new Error('Directory read error');
  533. });
  534. await expect(provider.callApi('test prompt')).rejects.toThrow('Directory read error');
  535. });
  536. it('should handle file copy errors', async () => {
  537. const provider = new GolangProvider('script.go', {
  538. config: { basePath: '/absolute/path/to' },
  539. });
  540. mockCopyFileSync.mockImplementation(() => {
  541. throw new Error('File copy error');
  542. });
  543. await expect(provider.callApi('test prompt')).rejects.toThrow('File copy error');
  544. });
  545. it('should copy main.go files without transformation', async () => {
  546. const provider = new GolangProvider('script.go', {
  547. config: { basePath: '/absolute/path/to' },
  548. });
  549. const mainGoContent = `
  550. package main
  551. // CallApi declaration
  552. var CallApi = func(prompt string) string {
  553. return "test"
  554. }
  555. func main() {
  556. // Some code
  557. }`;
  558. mockReaddirSync.mockReturnValue([
  559. { name: 'main.go', isDirectory: () => false },
  560. ] as unknown as fs.Dirent[]);
  561. mockReadFileSync.mockImplementation((p: fs.PathOrFileDescriptor) => {
  562. if (p.toString().endsWith('main.go')) {
  563. return mainGoContent;
  564. }
  565. return 'other content';
  566. });
  567. const copiedFiles: { src: string; dest: string }[] = [];
  568. mockCopyFileSync.mockImplementation((src: fs.PathLike, dest: fs.PathLike) => {
  569. copiedFiles.push({ src: src.toString(), dest: dest.toString() });
  570. return undefined;
  571. });
  572. mockExec.mockImplementation(((cmd: string, callback: any) => {
  573. if (!callback) {
  574. return {} as any;
  575. }
  576. process.nextTick(() => callback(null, { stdout: '{"output":"test"}', stderr: '' }, ''));
  577. return {} as any;
  578. }) as any);
  579. await provider.callApi('test prompt');
  580. // Verify that main.go was copied, not transformed
  581. expect(copiedFiles).toEqual(
  582. expect.arrayContaining([
  583. expect.objectContaining({
  584. src: expect.stringContaining('main.go'),
  585. dest: expect.stringContaining('main.go'),
  586. }),
  587. ]),
  588. );
  589. });
  590. it('should correctly handle nested directories in copyDir', async () => {
  591. const provider = new GolangProvider('script.go', {
  592. config: { basePath: '/absolute/path/to' },
  593. });
  594. // Mock a nested directory structure
  595. mockReaddirSync.mockImplementation((p: fs.PathOrFileDescriptor) => {
  596. if (p.toString().includes('nested')) {
  597. return [{ name: 'nested-file.go', isDirectory: () => false }] as unknown as fs.Dirent[];
  598. }
  599. return [
  600. { name: 'test.go', isDirectory: () => false },
  601. { name: 'nested', isDirectory: () => true },
  602. ] as unknown as fs.Dirent[];
  603. });
  604. // Track created directories and copied files
  605. const createdDirs: string[] = [];
  606. const copiedFiles: { src: string; dest: string }[] = [];
  607. mockMkdirSync.mockImplementation((p: fs.PathLike) => {
  608. createdDirs.push(p.toString());
  609. return undefined;
  610. });
  611. mockCopyFileSync.mockImplementation((src: fs.PathLike, dest: fs.PathLike) => {
  612. copiedFiles.push({ src: src.toString(), dest: dest.toString() });
  613. return undefined;
  614. });
  615. mockExec.mockImplementation(((cmd: string, callback: any) => {
  616. if (!callback) {
  617. return {} as any;
  618. }
  619. process.nextTick(() => callback(null, { stdout: '{"output":"test"}', stderr: '' }, ''));
  620. return {} as any;
  621. }) as any);
  622. await provider.callApi('test prompt');
  623. // Check that nested directories were created
  624. expect(createdDirs).toEqual(expect.arrayContaining(['/tmp/golang-provider-xyz']));
  625. // Check that nested files were copied
  626. expect(copiedFiles).toEqual(
  627. expect.arrayContaining([
  628. expect.objectContaining({
  629. dest: expect.stringContaining('nested-file.go'),
  630. }),
  631. ]),
  632. );
  633. });
  634. it('should handle copyFileSync errors', async () => {
  635. const provider = new GolangProvider('script.go', {
  636. config: { basePath: '/absolute/path/to' },
  637. });
  638. mockReaddirSync.mockReturnValue([
  639. { name: 'main.go', isDirectory: () => false },
  640. ] as unknown as fs.Dirent[]);
  641. mockCopyFileSync.mockImplementation(() => {
  642. throw new Error('Failed to copy file');
  643. });
  644. await expect(provider.callApi('test prompt')).rejects.toThrow('Failed to copy file');
  645. });
  646. });
  647. });
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...