import { describe, it, expect, beforeEach, afterEach } from 'vitest'; import Database from 'better-sqlite3'; import { runMigrations } from '../src/database/client.js'; import { RedditUsersRepository } from '../src/database/repositories.js'; describe('RedditUsersRepository', () => { let db: Database.Database; let repo: RedditUsersRepository; beforeEach(() => { db = new Database(':memory:'); db.pragma('foreign_keys = ON'); runMigrations(db); repo = new RedditUsersRepository(db); }); afterEach(() => { db.close(); }); it('upserts a new user and reads it back', () => { repo.upsert({ t2Id: 't2_abc', username: 'alice' }); const got = repo.getByT2('t2_abc'); expect(got?.username).toBe('alice'); expect(got?.t2Id).toBe('t2_abc'); }); it('normalizes a bare t2 id when looking up or writing', () => { repo.upsert({ t2Id: 'abc', username: 'alice' }); expect(repo.getByT2('abc')?.username).toBe('alice'); expect(repo.getByT2('t2_abc')?.username).toBe('alice'); }); it('updates the username when the same t2 is upserted twice', () => { repo.upsert({ t2Id: 't2_abc', username: 'old_name' }); repo.upsert({ t2Id: 't2_abc', username: 'new_name' }); expect(repo.getByT2('t2_abc')?.username).toBe('new_name'); }); it('refuses to store t2_-prefixed pseudo-usernames', () => { repo.upsert({ t2Id: 't2_abc', username: 't2_abc' }); expect(repo.getByT2('t2_abc')).toBeNull(); }); it('refuses to store MXID-shaped pseudo-usernames', () => { repo.upsert({ t2Id: 't2_abc', username: '@t2_abc:reddit.com' }); expect(repo.getByT2('t2_abc')).toBeNull(); }); it('looks up by username case-insensitively', () => { repo.upsert({ t2Id: 't2_abc', username: 'Alice' }); expect(repo.getByUsername('alice')?.t2Id).toBe('t2_abc'); expect(repo.getByUsername('ALICE')?.t2Id).toBe('t2_abc'); }); it('preserves an existing mxid when a later upsert passes null', () => { repo.upsert({ t2Id: 't2_abc', username: 'alice', mxid: '@t2_abc:reddit.com' }); repo.upsert({ t2Id: 't2_abc', username: 'alice' }); expect(repo.getByT2('t2_abc')?.mxid).toBe('@t2_abc:reddit.com'); }); it('bulk-inserts via upsertMany', () => { repo.upsertMany([ { t2Id: 't2_a', username: 'alice' }, { t2Id: 't2_b', username: 'bob' }, ]); const all = repo.getAll(); expect(all.map((u) => u.username).sort()).toEqual(['alice', 'bob']); }); });