import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; import { rmSync, writeFileSync } from 'node:fs'; import { spawnSync } from 'node:child_process'; import { chromium } from 'playwright'; import type { Browser, BrowserContext } from 'playwright'; import { BASE, ADMIN_PASS, DATA_DIR, setupTestEnv, spawnServer, killServer, login, seedRepo, db, } from './helpers.ts'; let browser: Browser; let server: Awaited>; beforeAll(async () => { await setupTestEnv(); server = await spawnServer(); browser = await chromium.launch(); // Register alice const ctx = await browser.newContext(); const page = await ctx.newPage(); try { await page.goto(`${BASE}/register`); await page.fill('[name=username]', 'alice'); await page.fill('[name=password]', 'password123'); await page.fill('[name=password2]', 'password123'); await page.click('button[type=submit]'); await page.waitForURL(BASE + '/'); } finally { await ctx.close(); } }); afterAll(async () => { await browser.close(); await killServer(server); }); async function loggedInContext(username = 'admin', password = ADMIN_PASS) { const ctx = await browser.newContext(); const page = await ctx.newPage(); await login(page, username, password); await page.close(); return ctx; } // ─── Repos ──────────────────────────────────────────────────────────────────── describe('repos', () => { // Shared admin context — cookies persist across tests in this block. let adminCtx: BrowserContext; // Alice's context, created after alice is registered in auth tests. let aliceCtx: BrowserContext; // Set after 'commit log' test; used by all commit-detail tests below. let commitUrl: string; beforeAll(async () => { adminCtx = await loggedInContext(); aliceCtx = await loggedInContext('alice', 'password123'); }); afterAll(async () => { await adminCtx.close(); await aliceCtx.close(); }); test('non-admin gets 403 on /new', async () => { const page = await aliceCtx.newPage(); try { const resp = await page.request.get(`${BASE}/new`); expect(resp.status()).toBe(403); } finally { await page.close(); } }); test('create repository', async () => { const page = await adminCtx.newPage(); try { await page.goto(`${BASE}/new`); await page.fill('[name=name]', 'my-repo'); await page.fill('[name=description]', 'A test repo'); await page.click('form[action="/new"] button[type=submit]'); await page.waitForURL(`${BASE}/my-repo`); expect(await page.locator('.empty-state').isVisible()).toBe(true); } finally { await page.close(); } }); test('repository appears in list', async () => { const page = await adminCtx.newPage(); try { await page.goto(BASE); expect(await page.locator('.repo-name').allTextContents()).toContain('my-repo'); } finally { await page.close(); } }); test('search finds matching repo', async () => { const page = await adminCtx.newPage(); try { await page.goto(BASE); await page.fill('[name=q]', 'my-repo'); await page.click('.search-form button[type=submit]'); expect(await page.locator('.repo-name').allTextContents()).toContain('my-repo'); } finally { await page.close(); } }); test('search returns empty for unknown term', async () => { const page = await adminCtx.newPage(); try { await page.goto(BASE); await page.fill('[name=q]', 'zzz-nothing-here'); await page.click('.search-form button[type=submit]'); expect(await page.locator('.empty-state').isVisible()).toBe(true); } finally { await page.close(); } }); test('browse file tree after seeding content', async () => { await seedRepo('my-repo'); const page = await adminCtx.newPage(); try { await page.goto(`${BASE}/my-repo/tree/main`); const files = await page.locator('.file-name a').allTextContents(); expect(files).toContain('README.md'); expect(files).toContain('index.js'); } finally { await page.close(); } }); test('view file blob with syntax highlighting', async () => { const page = await adminCtx.newPage(); try { await page.goto(`${BASE}/my-repo/blob/main/index.js`); expect(await page.locator('.file-blob-name').textContent()).toBe('index.js'); expect(await page.locator('.file-blob-body').isVisible()).toBe(true); } finally { await page.close(); } }); test('raw file download responds 200', async () => { const page = await adminCtx.newPage(); try { const resp = await page.request.get(`${BASE}/my-repo/raw/main/README.md`); expect(resp.status()).toBe(200); expect(resp.headers()['content-disposition']).toContain('README.md'); } finally { await page.close(); } }); test('commit log shows initial commit', async () => { const page = await adminCtx.newPage(); try { await page.goto(`${BASE}/my-repo/commits/main`); const subjects = await page.locator('.commit-subject').allTextContents(); expect(subjects.some(s => s.includes('Initial commit'))).toBe(true); // Navigate to the commit page and capture the URL for subsequent tests await page.locator('.commit-hash').first().click(); await page.waitForURL(/\/my-repo\/commit\//); commitUrl = page.url(); } finally { await page.close(); } }); test('commit detail shows metadata card', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); expect(await page.locator('.commit-card').isVisible()).toBe(true); expect(await page.locator('.commit-card-subject').textContent()).toContain('Initial commit'); // Author, date and SHA rows are all present const metaText = await page.locator('.commit-card-meta').textContent(); expect(metaText).toContain('Test'); // author name set by seedRepo expect(metaText).toContain('Author'); // label (CSS uppercases visually) expect(metaText).toContain('Date'); expect(metaText).toContain('Commit'); } finally { await page.close(); } }); test('commit detail full SHA is shown', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); const sha = commitUrl.split('/commit/')[1] ?? null; expect(await page.locator('.commit-sha-full').textContent()).toBe(sha); } finally { await page.close(); } }); test('commit detail shows file nav sidebar', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); expect(await page.locator('.file-nav-details').isVisible()).toBe(true); const navItems = await page.locator('.file-nav-item').allTextContents(); // seedRepo adds README.md and index.js expect(navItems.some(t => t.includes('README.md'))).toBe(true); expect(navItems.some(t => t.includes('index.js'))).toBe(true); } finally { await page.close(); } }); test('commit detail file nav items are anchor links to diff sections', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); const hrefs = await page.locator('.file-nav-item').evaluateAll( els => els.map(el => el.getAttribute('href') ?? ''), ); expect(hrefs.every(h => h.startsWith('#'))).toBe(true); } finally { await page.close(); } }); test('commit detail shows diff table with added lines', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); // Initial commit only adds lines expect(await page.locator('.diff-table').first().isVisible()).toBe(true); expect(await page.locator('.diff-row-add').count()).toBeGreaterThan(0); expect(await page.locator('.diff-row-del').count()).toBe(0); } finally { await page.close(); } }); test('commit detail diff table has line numbers', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); // New-side line numbers (column 2) on add rows start at 1 const firstNewLn = await page.locator('.diff-row-add .diff-ln-new').first().textContent(); expect(firstNewLn?.trim()).toBe('1'); } finally { await page.close(); } }); test('commit detail shows added stats on file header', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); const addStats = await page.locator('.diff-stat-add').allTextContents(); expect(addStats.length).toBeGreaterThan(0); expect(addStats.every(s => s.startsWith('+'))).toBe(true); } finally { await page.close(); } }); test('commit detail view-at-sha button links to blob at that commit', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); const sha = commitUrl.split('/commit/')[1]; const btn = page.locator('.btn-xs').first(); const href = await btn.getAttribute('href'); expect(href).toContain(`/blob/${sha}/`); } finally { await page.close(); } }); test('commit detail view-at-branch button links to blob at default branch', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); const btns = await page.locator('.btn-xs').allTextContents(); expect(btns.some(t => t.includes('@ main'))).toBe(true); const branchBtns = await page.locator('.btn-xs').evaluateAll( els => els.filter(el => el.textContent?.includes('@ main')).map(el => el.getAttribute('href') ?? ''), ); expect(branchBtns.every(h => h.includes('/blob/main/'))).toBe(true); } finally { await page.close(); } }); test('commit detail file diff can be collapsed', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); // File body is visible when details is open const diffFile = page.locator('.diff-file').first(); expect(await diffFile.getAttribute('open')).not.toBeNull(); // Click the summary to collapse await diffFile.locator('.diff-file-header').click(); expect(await diffFile.getAttribute('open')).toBeNull(); } finally { await page.close(); } }); test('commit detail file nav sidebar can be collapsed', async () => { const page = await adminCtx.newPage(); try { await page.goto(commitUrl); const nav = page.locator('.file-nav-details'); expect(await nav.getAttribute('open')).not.toBeNull(); await nav.locator('.file-nav-toggle').click(); expect(await nav.getAttribute('open')).toBeNull(); } finally { await page.close(); } }); test('readme renders on repo home', async () => { const page = await adminCtx.newPage(); try { await page.goto(`${BASE}/my-repo`); expect(await page.locator('.readme-header').isVisible()).toBe(true); expect(await page.locator('.readme-section .markdown-body').innerHTML()).toContain('my-repo'); } finally { await page.close(); } }); test('private repo hidden from other users', async () => { // Make private const adminPage = await adminCtx.newPage(); try { await adminPage.goto(`${BASE}/my-repo/settings`); await adminPage.check('[name=is_private]'); await adminPage.click('form[action$="/settings"] button[type=submit]'); expect(await adminPage.locator('.form-success').isVisible()).toBe(true); } finally { await adminPage.close(); } // Alice should get 404 const alicePage = await aliceCtx.newPage(); try { const resp = await alicePage.request.get(`${BASE}/my-repo`); expect(resp.status()).toBe(404); await alicePage.goto(BASE); expect(await alicePage.locator('.repo-name').allTextContents()).not.toContain('my-repo'); } finally { await alicePage.close(); } // Restore to public const adminPage2 = await adminCtx.newPage(); try { await adminPage2.goto(`${BASE}/my-repo/settings`); await adminPage2.uncheck('[name=is_private]'); await adminPage2.click('form[action$="/settings"] button[type=submit]'); } finally { await adminPage2.close(); } }); test('settings tab visible for admin, hidden for others', async () => { const adminPage = await adminCtx.newPage(); try { await adminPage.goto(`${BASE}/my-repo`); expect(await adminPage.locator('.repo-tab[href$="/settings"]').isVisible()).toBe(true); } finally { await adminPage.close(); } const alicePage = await aliceCtx.newPage(); try { await alicePage.goto(`${BASE}/my-repo`); expect(await alicePage.locator('.repo-tab[href$="/settings"]').count()).toBe(0); } finally { await alicePage.close(); } }); test('create repository with invalid name shows error', async () => { const resp = await adminCtx.request.post(`${BASE}/new`, { form: { name: 'has spaces!', description: '', default_branch: 'main' }, maxRedirects: 0, }); expect(resp.status()).toBe(200); expect(await resp.text()).toContain('Invalid repository name'); }); test('auto-scanned repo is private by default', async () => { const name = 'auto-private-repo'; const dir = `${process.cwd()}/${DATA_DIR}/repos/${name}.git`; rmSync(dir, { recursive: true, force: true }); const tmp = `/tmp/hf-scan-${Date.now()}`; try { spawnSync('git', ['init', '--bare', dir], { stdio: 'ignore' }); spawnSync('git', ['clone', dir, tmp], { stdio: 'ignore' }); spawnSync('git', ['-C', tmp, 'commit', '--allow-empty', '-m', 'init'], { stdio: 'ignore' }); spawnSync('git', ['-C', tmp, 'push', 'origin', 'HEAD:main'], { stdio: 'ignore' }); } finally { rmSync(tmp, { recursive: true, force: true }); } // The Go server adopts repos found on disk at startup, not lazily per // request, so restart it and read the row it created. await killServer(server); server = await spawnServer(); const repo = await db .selectFrom('repositories') .select(['name', 'is_private']) .where('name', '=', name) .executeTakeFirst(); expect(repo!.is_private).toBe(1); await db.deleteFrom('repositories').where('name', '=', name).execute(); rmSync(dir, { recursive: true, force: true }); }); test('repo is registered even with a stale config.lock', async () => { const name = 'stale-lock-repo'; const dir = `${process.cwd()}/${DATA_DIR}/repos/${name}.git`; rmSync(dir, { recursive: true, force: true }); spawnSync('git', ['init', '--bare', dir], { stdio: 'ignore' }); // Drop core.bare so ensureBare has to attempt a write, then block it. spawnSync('git', ['config', '--file', `${dir}/config`, '--unset', 'core.bare'], { stdio: 'ignore', }); writeFileSync(`${dir}/config.lock`, ''); await killServer(server); server = await spawnServer(); const repo = await db .selectFrom('repositories') .select('name') .where('name', '=', name) .executeTakeFirst(); expect(repo!.name).toBe(name); await db.deleteFrom('repositories').where('name', '=', name).execute(); rmSync(dir, { recursive: true, force: true }); }); });