OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-note / test / unit / media-store.test.js

108 lines · javascript ref:
import test from 'brittle'
import fs from 'bare-fs'
import path from 'bare-path'
import os from 'bare-os'
import Corestore from 'corestore'
import { MediaStore } from '../../lib/media-store.js'

function tmpSetup () {
  const dir = path.join(os.tmpdir(), 'hn-ms-' + Date.now() + '-' + Math.random().toString(36).slice(2))
  fs.mkdirSync(dir, { recursive: true })
  const store = new Corestore(dir)
  return { store, dir }
}

function rmrf (dir) {
  try {
    for (const f of fs.readdirSync(dir)) {
      const fp = path.join(dir, f)
      const stat = fs.statSync(fp)
      if (stat.isDirectory()) rmrf(fp)
      else fs.unlinkSync(fp)
    }
    fs.rmdirSync(dir)
  } catch {}
}

test('MediaStore - put stores blob and returns sha256 hash', async (t) => {
  const { store, dir } = tmpSetup()
  const media = new MediaStore(store)
  await media.ready()

  const buf = Buffer.from('hello world')
  const hash = await media.put(buf, 'text/plain')

  t.is(typeof hash, 'string')
  t.is(hash.length, 64)

  await store.close()
  rmrf(dir)
})

test('MediaStore - get retrieves stored blob by hash', async (t) => {
  const { store, dir } = tmpSetup()
  const media = new MediaStore(store)
  await media.ready()

  const buf = Buffer.from('test data for retrieval')
  const hash = await media.put(buf, 'application/octet-stream')
  const retrieved = await media.get(hash)

  t.alike(retrieved, buf)

  await store.close()
  rmrf(dir)
})

test('MediaStore - has returns true for existing hash', async (t) => {
  const { store, dir } = tmpSetup()
  const media = new MediaStore(store)
  await media.ready()

  const buf = Buffer.from('existence check')
  const hash = await media.put(buf, 'text/plain')

  t.is(await media.has(hash), true)
  t.is(await media.has('0'.repeat(64)), false)

  await store.close()
  rmrf(dir)
})

test('MediaStore - dedup: same content returns same hash, stored once', async (t) => {
  const { store, dir } = tmpSetup()
  const media = new MediaStore(store)
  await media.ready()

  const buf = Buffer.from('duplicate content')
  const hash1 = await media.put(buf, 'text/plain')
  const hash2 = await media.put(buf, 'text/plain')

  t.is(hash1, hash2)

  const info = await media.getInfo(hash1)
  t.ok(info)
  t.is(info.size, buf.length)

  await store.close()
  rmrf(dir)
})

test('MediaStore - getInfo returns metadata', async (t) => {
  const { store, dir } = tmpSetup()
  const media = new MediaStore(store)
  await media.ready()

  const buf = Buffer.from('metadata test')
  const hash = await media.put(buf, 'image/jpeg')
  const info = await media.getInfo(hash)

  t.is(info.size, buf.length)
  t.is(info.mimeType, 'image/jpeg')
  t.ok(info.createdAt)
  t.ok(info.blobId)

  await store.close()
  rmrf(dir)
})