1package ollama
  2
  3import (
  4	"context"
  5	"testing"
  6	"time"
  7)
  8
  9func TestProcessManager(t *testing.T) {
 10	if !IsInstalled() {
 11		t.Skip("Ollama is not installed, skipping ProcessManager test")
 12	}
 13
 14	// Test that processManager is initialized
 15	if processManager == nil {
 16		t.Fatal("processManager is nil")
 17	}
 18
 19	if processManager.processes == nil {
 20		t.Fatal("processManager.processes is nil")
 21	}
 22
 23	t.Log("ProcessManager is properly initialized")
 24}
 25
 26func TestCleanupProcesses(t *testing.T) {
 27	if !IsInstalled() {
 28		t.Skip("Ollama is not installed, skipping cleanup test")
 29	}
 30
 31	ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
 32	defer cancel()
 33
 34	// Start Ollama service if not running
 35	wasRunning := IsRunning(ctx)
 36	if !wasRunning {
 37		t.Log("Starting Ollama service for cleanup test...")
 38		if err := StartOllamaService(ctx); err != nil {
 39			t.Fatalf("Failed to start Ollama service: %v", err)
 40		}
 41
 42		// Verify it started
 43		if !IsRunning(ctx) {
 44			t.Fatal("Failed to start Ollama service")
 45		}
 46
 47		// Test cleanup
 48		t.Log("Testing cleanup...")
 49		cleanupProcesses()
 50
 51		// Give some time for cleanup
 52		time.Sleep(3 * time.Second)
 53
 54		// Verify cleanup worked (service should be stopped)
 55		if IsRunning(ctx) {
 56			t.Error("Ollama service is still running after cleanup")
 57		} else {
 58			t.Log("Cleanup successfully stopped Ollama service")
 59		}
 60	} else {
 61		t.Log("Ollama was already running, skipping cleanup test to avoid disruption")
 62	}
 63}
 64
 65func TestSetupProcessCleanup(t *testing.T) {
 66	// Test that setupProcessCleanup can be called without panicking
 67	// Note: We can't easily test signal handling in unit tests
 68	defer func() {
 69		if r := recover(); r != nil {
 70			t.Fatalf("setupProcessCleanup panicked: %v", r)
 71		}
 72	}()
 73
 74	// This should not panic and should be safe to call multiple times
 75	setupProcessCleanup()
 76	setupProcessCleanup() // Should be safe due to sync.Once
 77
 78	t.Log("setupProcessCleanup completed without panic")
 79}
 80
 81func TestProcessManagerThreadSafety(t *testing.T) {
 82	if !IsInstalled() {
 83		t.Skip("Ollama is not installed, skipping thread safety test")
 84	}
 85
 86	// Test concurrent access to processManager
 87	done := make(chan bool)
 88
 89	// Start multiple goroutines that access processManager
 90	for i := 0; i < 10; i++ {
 91		go func() {
 92			processManager.mu.RLock()
 93			_ = len(processManager.processes)
 94			processManager.mu.RUnlock()
 95			done <- true
 96		}()
 97	}
 98
 99	// Wait for all goroutines to complete
100	for i := 0; i < 10; i++ {
101		select {
102		case <-done:
103			// Success
104		case <-time.After(1 * time.Second):
105			t.Fatal("Thread safety test timed out")
106		}
107	}
108
109	t.Log("ProcessManager thread safety test passed")
110}