readysite / pkg / database / engines / engines_test.go
2.2 KB
engines_test.go
package engines

import (
	"os"
	"path/filepath"
	"testing"
	"time"
)

func TestMemory(t *testing.T) {
	db := NewMemory()
	defer db.Close()

	// Should be able to execute queries
	_, err := db.Exec("CREATE TABLE test (id TEXT, name TEXT)")
	if err != nil {
		t.Fatalf("CREATE TABLE failed: %v", err)
	}

	_, err = db.Exec("INSERT INTO test (id, name) VALUES (?, ?)", "1", "Alice")
	if err != nil {
		t.Fatalf("INSERT failed: %v", err)
	}

	var name string
	err = db.QueryRow("SELECT name FROM test WHERE id = ?", "1").Scan(&name)
	if err != nil {
		t.Fatalf("SELECT failed: %v", err)
	}
	if name != "Alice" {
		t.Errorf("expected 'Alice', got '%s'", name)
	}
}

func TestMemory_NoSync(t *testing.T) {
	db := NewMemory()
	defer db.Close()

	// Memory database should not have a syncer
	if db.Sync != nil {
		t.Error("expected Sync to be nil for memory database")
	}
}

func TestLocal(t *testing.T) {
	tmpDir, err := os.MkdirTemp("", "local_test")
	if err != nil {
		t.Fatalf("failed to create temp dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)

	dbPath := filepath.Join(tmpDir, "test.db")
	db := NewLocal(dbPath)
	defer db.Close()

	// Should be able to execute queries
	_, err = db.Exec("CREATE TABLE test (id TEXT, name TEXT)")
	if err != nil {
		t.Fatalf("CREATE TABLE failed: %v", err)
	}

	_, err = db.Exec("INSERT INTO test (id, name) VALUES (?, ?)", "1", "Bob")
	if err != nil {
		t.Fatalf("INSERT failed: %v", err)
	}

	// Verify file was created
	if _, err := os.Stat(dbPath); os.IsNotExist(err) {
		t.Error("expected database file to exist")
	}
}

func TestLocal_NoSync(t *testing.T) {
	tmpDir, err := os.MkdirTemp("", "local_test")
	if err != nil {
		t.Fatalf("failed to create temp dir: %v", err)
	}
	defer os.RemoveAll(tmpDir)

	dbPath := filepath.Join(tmpDir, "test.db")
	db := NewLocal(dbPath)
	defer db.Close()

	// Local database should not have a syncer
	if db.Sync != nil {
		t.Error("expected Sync to be nil for local database")
	}
}

func TestRemote_WithSyncInterval(t *testing.T) {
	// Just test that the option works (can't test actual connection without a server)
	opt := WithSyncInterval(time.Minute)
	cfg := &remoteConfig{}
	opt(cfg)

	if cfg.syncInterval != time.Minute {
		t.Errorf("expected sync interval 1m, got %v", cfg.syncInterval)
	}
}
← Back