base64.test.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import { fromBase64, toBase64 } from '@opencode-ai/sdk/internal/utils/base64';
  2. describe.each(['Buffer', 'atob'])('with %s', (mode) => {
  3. let originalBuffer: BufferConstructor;
  4. beforeAll(() => {
  5. if (mode === 'atob') {
  6. originalBuffer = globalThis.Buffer;
  7. // @ts-expect-error Can't assign undefined to BufferConstructor
  8. delete globalThis.Buffer;
  9. }
  10. });
  11. afterAll(() => {
  12. if (mode === 'atob') {
  13. globalThis.Buffer = originalBuffer;
  14. }
  15. });
  16. test('toBase64', () => {
  17. const testCases = [
  18. {
  19. input: 'hello world',
  20. expected: 'aGVsbG8gd29ybGQ=',
  21. },
  22. {
  23. input: new Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]),
  24. expected: 'aGVsbG8gd29ybGQ=',
  25. },
  26. {
  27. input: undefined,
  28. expected: '',
  29. },
  30. {
  31. input: new Uint8Array([
  32. 229, 102, 215, 230, 65, 22, 46, 87, 243, 176, 99, 99, 31, 174, 8, 242, 83, 142, 169, 64, 122, 123,
  33. 193, 71,
  34. ]),
  35. expected: '5WbX5kEWLlfzsGNjH64I8lOOqUB6e8FH',
  36. },
  37. {
  38. input: '✓',
  39. expected: '4pyT',
  40. },
  41. {
  42. input: new Uint8Array([226, 156, 147]),
  43. expected: '4pyT',
  44. },
  45. ];
  46. testCases.forEach(({ input, expected }) => {
  47. expect(toBase64(input)).toBe(expected);
  48. });
  49. });
  50. test('fromBase64', () => {
  51. const testCases = [
  52. {
  53. input: 'aGVsbG8gd29ybGQ=',
  54. expected: new Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]),
  55. },
  56. {
  57. input: '',
  58. expected: new Uint8Array([]),
  59. },
  60. {
  61. input: '5WbX5kEWLlfzsGNjH64I8lOOqUB6e8FH',
  62. expected: new Uint8Array([
  63. 229, 102, 215, 230, 65, 22, 46, 87, 243, 176, 99, 99, 31, 174, 8, 242, 83, 142, 169, 64, 122, 123,
  64. 193, 71,
  65. ]),
  66. },
  67. {
  68. input: '4pyT',
  69. expected: new Uint8Array([226, 156, 147]),
  70. },
  71. ];
  72. testCases.forEach(({ input, expected }) => {
  73. expect(fromBase64(input)).toEqual(expected);
  74. });
  75. });
  76. });