session.test.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { describe, expect, mock, test } from 'bun:test';
  2. import {
  3. abortSessionWithTimeout,
  4. OperationTimeoutError,
  5. promptWithTimeout,
  6. withTimeout,
  7. } from './session';
  8. function never<T>(): Promise<T> {
  9. return new Promise<T>(() => {});
  10. }
  11. describe('session utilities', () => {
  12. test('withTimeout resolves without waiting for the timeout', async () => {
  13. const result = await withTimeout(Promise.resolve('ok'), 50, 'too slow');
  14. expect(result).toBe('ok');
  15. });
  16. test('withTimeout rejects with OperationTimeoutError when operation hangs', async () => {
  17. await expect(withTimeout(never(), 5, 'too slow')).rejects.toThrow(
  18. OperationTimeoutError,
  19. );
  20. });
  21. test('promptWithTimeout aborts a timed-out prompt before rejecting', async () => {
  22. const abort = mock(async () => ({}));
  23. const prompt = mock(() => never());
  24. const client = {
  25. session: {
  26. abort,
  27. prompt,
  28. },
  29. } as any;
  30. await expect(
  31. promptWithTimeout(
  32. client,
  33. { path: { id: 's1' }, body: { parts: [] } },
  34. 5,
  35. ),
  36. ).rejects.toThrow('Prompt timed out after 5ms');
  37. expect(abort).toHaveBeenCalledWith({ path: { id: 's1' } });
  38. });
  39. test('promptWithTimeout preserves timeout error when abort fails', async () => {
  40. const abort = mock(async () => {
  41. throw new Error('abort failed');
  42. });
  43. const prompt = mock(() => never());
  44. const client = {
  45. session: {
  46. abort,
  47. prompt,
  48. },
  49. } as any;
  50. await expect(
  51. promptWithTimeout(
  52. client,
  53. { path: { id: 's1' }, body: { parts: [] } },
  54. 5,
  55. ),
  56. ).rejects.toThrow('Prompt timed out after 5ms');
  57. });
  58. test('abortSessionWithTimeout rejects if abort hangs', async () => {
  59. const client = {
  60. session: {
  61. abort: mock(() => never()),
  62. },
  63. } as any;
  64. await expect(abortSessionWithTimeout(client, 's1', 5)).rejects.toThrow(
  65. 'Session abort timed out after 5ms',
  66. );
  67. });
  68. });