Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

2.4 KB
Raw Blame
import { expect, assert } from 'vitest'

import { FileNotFoundError, NotFoundError } from '../../../src'
import { sandboxTest } from '../../setup.js'

sandboxTest('read file', async ({ sandbox }) => {
  const filename = 'test_read.txt'
  const content = 'Hello, world!'

  await sandbox.files.write(filename, content)
  const readContent = await sandbox.files.read(filename)
  assert.equal(readContent, content)
})

sandboxTest('read non-existing file', async ({ sandbox }) => {
  const filename = 'non_existing_file.txt'

  await expect(sandbox.files.read(filename)).rejects.toThrowError(
    FileNotFoundError
  )
})

sandboxTest(
  'read non-existing file catches with deprecated NotFoundError',
  async ({ sandbox }) => {
    const filename = 'non_existing_file.txt'

    await expect(sandbox.files.read(filename)).rejects.toThrowError(
      NotFoundError
    )
  }
)

sandboxTest('read file as stream', async ({ sandbox }) => {
  const filename = 'test_read_stream.txt'
  const content = 'Streamed read content. '.repeat(10_000)

  await sandbox.files.write(filename, content)
  const stream = await sandbox.files.read(filename, { format: 'stream' })

  const decoder = new TextDecoder()
  let readContent = ''
  for await (const chunk of stream as unknown as AsyncIterable<Uint8Array>) {
    readContent += decoder.decode(chunk, { stream: true })
  }
  readContent += decoder.decode()
  assert.equal(readContent, content)
})

sandboxTest('read non-existing file as stream', async ({ sandbox }) => {
  const filename = 'non_existing_file.txt'

  await expect(
    sandbox.files.read(filename, { format: 'stream' })
  ).rejects.toThrowError(FileNotFoundError)
})

sandboxTest('read empty file in all formats', async ({ sandbox }) => {
  const filename = 'empty-file-formats.txt'
  await sandbox.commands.run(`touch ${filename}`)

  const text = await sandbox.files.read(filename, { format: 'text' })
  expect(text).toBe('')

  const bytes = await sandbox.files.read(filename, { format: 'bytes' })
  expect(bytes).toBeInstanceOf(Uint8Array)
  expect(bytes.length).toBe(0)

  const blob = await sandbox.files.read(filename, { format: 'blob' })
  expect(blob).toBeInstanceOf(Blob)
  expect(blob.size).toBe(0)

  const stream = await sandbox.files.read(filename, { format: 'stream' })
  expect(stream).toBeInstanceOf(ReadableStream)
  let bytesRead = 0
  for await (const chunk of stream as unknown as AsyncIterable<Uint8Array>) {
    bytesRead += chunk.length
  }
  expect(bytesRead).toBe(0)
})