← back to Handbag Auth Nextjs

auction-viewer/tests/fixtures/test-database.js

130 lines

/**
 * Test Database Utilities
 */

const Database = require('better-sqlite3');
const path = require('path');
const fs = require('fs');

class TestDatabase {
  constructor(dbPath = null) {
    this.dbPath = dbPath || path.join(__dirname, 'test-auctions.db');
    this.db = null;
  }

  /**
   * Initialize test database with schema
   */
  initialize() {
    // Remove existing test database
    if (fs.existsSync(this.dbPath)) {
      fs.unlinkSync(this.dbPath);
    }

    this.db = new Database(this.dbPath);

    // Create auctions table
    this.db.exec(`
      CREATE TABLE IF NOT EXISTS auctions (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        auction_id TEXT UNIQUE,
        title TEXT,
        auction_house TEXT,
        current_price REAL,
        estimate_low REAL,
        estimate_high REAL,
        end_date TEXT,
        lot_number TEXT,
        url TEXT,
        search_term TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      )
    `);

    return this;
  }

  /**
   * Seed database with test data
   */
  seed(auctions) {
    const insert = this.db.prepare(`
      INSERT INTO auctions
      (auction_id, title, auction_house, current_price, estimate_low,
       estimate_high, end_date, lot_number, url, search_term)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
    `);

    const insertMany = this.db.transaction((items) => {
      for (const auction of items) {
        insert.run(
          auction.auction_id,
          auction.title,
          auction.auction_house,
          auction.current_price,
          auction.estimate_low,
          auction.estimate_high,
          auction.end_date,
          auction.lot_number,
          auction.url,
          auction.search_term
        );
      }
    });

    insertMany(auctions);
    return this;
  }

  /**
   * Get all auctions
   */
  getAllAuctions() {
    return this.db.prepare('SELECT * FROM auctions ORDER BY created_at DESC').all();
  }

  /**
   * Get auction count
   */
  getCount() {
    return this.db.prepare('SELECT COUNT(*) as count FROM auctions').get().count;
  }

  /**
   * Clear all data
   */
  clear() {
    this.db.exec('DELETE FROM auctions');
    return this;
  }

  /**
   * Close database connection
   */
  close() {
    if (this.db) {
      this.db.close();
      this.db = null;
    }
  }

  /**
   * Cleanup - remove database file
   */
  cleanup() {
    this.close();
    if (fs.existsSync(this.dbPath)) {
      fs.unlinkSync(this.dbPath);
    }
  }

  /**
   * Get database path
   */
  getPath() {
    return this.dbPath;
  }
}

module.exports = { TestDatabase };