Files
RedditBot/tests/reddit-users-repo.test.ts
jjbruntonandClaude Opus 4.7 1b6dfd67e3 Persist t2→username mappings in reddit_users table
Adds a durable mapping so the UI never has to show raw t2_xxx IDs or
MXIDs just because the in-memory cache is cold after a restart.
ChatService seeds from the table on construction and writes through
every resolution path; cached chats whose username is still t2_xxx
get upgraded from the DB on loadCache.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-22 20:34:06 +01:00

71 lines
2.4 KiB
TypeScript

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']);
});
});