storage-upload/test/media/api.test.mjs

109 lines
3.3 KiB
JavaScript

import { Eltro as t, assert} from 'eltro'
import fs from 'fs/promises'
import { fileURLToPath } from 'url'
import path from 'path'
import { server, resetLog } from '../helper.server.mjs'
import Client from '../helper.client.mjs'
import config from '../../api/config.mjs'
import encode from '../../api/jwt/encode.mjs'
let __dirname = path.dirname(fileURLToPath(import.meta.url))
function resolve(file) {
return path.resolve(path.join(__dirname, file))
}
t.describe('Media (API)', () => {
const client = new Client()
const secret = 'asdf1234'
let testFile
t.after(function() {
if (testFile) {
return fs.unlink(resolve(`../../public/${testFile}`))
}
})
t.timeout(10000).describe('POST /media', function temp() {
t.test('should require authentication', async () => {
resetLog()
assert.strictEqual(server.log.error.callCount, 0)
assert.strictEqual(server.log.warn.callCount, 0)
let err = await assert.isRejected(
client.upload('/media',
resolve('test.png')
)
)
assert.strictEqual(err.status, 422)
assert.match(err.message, /[Tt]oken/)
assert.match(err.message, /[Mm]issing/)
await new Promise(function(res) {
setTimeout(res, 100)
})
console.log(server.log.warn.firstCall)
console.log(server.log.warn.secondCall)
assert.strictEqual(server.log.error.callCount, 0)
assert.strictEqual(server.log.warn.callCount, 2)
assert.strictEqual(typeof(server.log.warn.firstCall[0]), 'string')
assert.match(server.log.warn.firstCall[0], /[Tt]oken/)
assert.match(server.log.warn.firstCall[0], /[Mm]issing/)
})
t.test('should verify token correctly', async () => {
const assertToken = 'asdf.asdf.asdf'
resetLog()
assert.strictEqual(server.log.error.callCount, 0)
assert.strictEqual(server.log.warn.callCount, 0)
assert.strictEqual(server.log.info.callCount, 0)
let err = await assert.isRejected(
client.upload('/media?token=' + assertToken,
resolve('test.png')
)
)
assert.strictEqual(err.status, 422)
assert.match(err.message, /[Tt]oken/)
assert.match(err.message, /[Ii]nvalid/)
await new Promise(function(res) {
setTimeout(res, 100)
})
assert.strictEqual(server.log.error.callCount, 1)
assert.strictEqual(server.log.warn.callCount, 2)
assert.strictEqual(typeof(server.log.warn.firstCall[0]), 'string')
assert.match(server.log.warn.firstCall[0], /[Tt]oken/)
assert.match(server.log.warn.firstCall[0], /[Ii]nvalid/)
assert.ok(server.log.error.lastCall[0] instanceof Error)
assert.match(server.log.error.lastCall[1], new RegExp(assertToken))
})
t.test('should upload file and create file', async () => {
let token = encode(null, { iss: 'development' }, secret)
let data = await assert.isFulfilled(
client.upload(
`/media?token=${token}`,
resolve('test.png')
)
)
assert.ok(data)
assert.ok(data.filename)
assert.ok(data.path)
testFile = data.path
let stats = await Promise.all([
fs.stat(resolve('test.png')),
fs.stat(resolve(`../../public/${testFile}`)),
])
assert.strictEqual(stats[0].size, stats[1].size)
})
})
})