| 1 | 'use strict'; |
| 2 | |
| 3 | const crypto = require('crypto'); |
| 4 | const fs = require('fs'); |
| 5 | const os = require('os'); |
| 6 | const path = require('path'); |
| 7 | |
| 8 | jest.mock('../server/db', () => |
| 9 | { |
| 10 | const { Database } = require('node-sqlite3-wasm'); |
| 11 | let db; |
| 12 | function getDb () |
| 13 | { |
| 14 | if (!db) |
| 15 | { |
| 16 | db = new Database(':memory:'); |
| 17 | db.exec(` |
| 18 | CREATE TABLE IF NOT EXISTS file_meta ( |
| 19 | file_path TEXT PRIMARY KEY, |
| 20 | uploader TEXT NOT NULL DEFAULT '', |
| 21 | downloaders TEXT NOT NULL DEFAULT '[]', |
| 22 | watched_by TEXT NOT NULL DEFAULT '{}', |
| 23 | uploaded_at TEXT, |
| 24 | sha256 TEXT |
| 25 | ); |
| 26 | `); |
| 27 | } |
| 28 | return db; |
| 29 | } |
| 30 | return { getDb, initDb: getDb }; |
| 31 | }); |
| 32 | |
| 33 | describe('file hash queue', () => |
| 34 | { |
| 35 | let tempDir; |
| 36 | |
| 37 | beforeEach(() => |
| 38 | { |
| 39 | tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-file-hash-')); |
| 40 | }); |
| 41 | |
| 42 | afterEach(() => |
| 43 | { |
| 44 | fs.rmSync(tempDir, { recursive: true, force: true }); |
| 45 | }); |
| 46 | |
| 47 | test('drainFileHashQueue persists sha256 for queued files', async () => |
| 48 | { |
| 49 | const filePath = path.join(tempDir, 'queued.txt'); |
| 50 | const content = 'background hash'; |
| 51 | fs.writeFileSync(filePath, content); |
| 52 | |
| 53 | const { getDb } = require('../server/db'); |
| 54 | getDb().prepare('INSERT INTO file_meta (file_path, uploader, downloaders) VALUES (?, ?, ?)') |
| 55 | .run([filePath, '', '[]']); |
| 56 | |
| 57 | const hashQueue = require('../server/file-hash-queue'); |
| 58 | hashQueue.enqueueFileHash(filePath); |
| 59 | await hashQueue.drainFileHashQueue(); |
| 60 | |
| 61 | const expected = crypto.createHash('sha256').update(content).digest('hex'); |
| 62 | const row = getDb().prepare('SELECT sha256 FROM file_meta WHERE file_path = ?').get([filePath]); |
| 63 | expect(row.sha256).toBe(expected); |
| 64 | }); |
| 65 | }); |