prompt_test.go

  1package prompt
  2
  3import (
  4	"os"
  5	"path/filepath"
  6	"strings"
  7	"testing"
  8)
  9
 10func TestExpandPath(t *testing.T) {
 11	tests := []struct {
 12		name     string
 13		input    string
 14		expected func() string
 15	}{
 16		{
 17			name:  "regular path unchanged",
 18			input: "/absolute/path",
 19			expected: func() string {
 20				return "/absolute/path"
 21			},
 22		},
 23		{
 24			name:  "tilde expansion",
 25			input: "~/documents",
 26			expected: func() string {
 27				home, _ := os.UserHomeDir()
 28				return filepath.Join(home, "documents")
 29			},
 30		},
 31		{
 32			name:  "tilde only",
 33			input: "~",
 34			expected: func() string {
 35				home, _ := os.UserHomeDir()
 36				return home
 37			},
 38		},
 39		{
 40			name:  "environment variable expansion",
 41			input: "$HOME",
 42			expected: func() string {
 43				return os.Getenv("HOME")
 44			},
 45		},
 46		{
 47			name:  "relative path unchanged",
 48			input: "relative/path",
 49			expected: func() string {
 50				return "relative/path"
 51			},
 52		},
 53	}
 54
 55	for _, tt := range tests {
 56		t.Run(tt.name, func(t *testing.T) {
 57			result := expandPath(tt.input)
 58			expected := tt.expected()
 59
 60			// Skip test if environment variable is not set
 61			if strings.HasPrefix(tt.input, "$") && expected == "" {
 62				t.Skip("Environment variable not set")
 63			}
 64
 65			if result != expected {
 66				t.Errorf("expandPath(%q) = %q, want %q", tt.input, result, expected)
 67			}
 68		})
 69	}
 70}
 71
 72func TestProcessContextPaths(t *testing.T) {
 73	// Create a temporary directory and file for testing
 74	tmpDir := t.TempDir()
 75	testFile := filepath.Join(tmpDir, "test.txt")
 76	testContent := "test content"
 77
 78	err := os.WriteFile(testFile, []byte(testContent), 0o644)
 79	if err != nil {
 80		t.Fatalf("Failed to create test file: %v", err)
 81	}
 82
 83	// Test with absolute path
 84	result := processContextPaths("", []string{testFile})
 85	expected := "# From:" + testFile + "\n" + testContent
 86
 87	if result != expected {
 88		t.Errorf("processContextPaths with absolute path failed.\nGot: %q\nWant: %q", result, expected)
 89	}
 90
 91	// Test with tilde expansion (if we can create a file in home directory)
 92	home, err := os.UserHomeDir()
 93	if err == nil {
 94		homeTestFile := filepath.Join(home, "crush_test_file.txt")
 95		err = os.WriteFile(homeTestFile, []byte(testContent), 0o644)
 96		if err == nil {
 97			defer os.Remove(homeTestFile) // Clean up
 98
 99			tildeFile := "~/crush_test_file.txt"
100			result = processContextPaths("", []string{tildeFile})
101			expected = "# From:" + homeTestFile + "\n" + testContent
102
103			if result != expected {
104				t.Errorf("processContextPaths with tilde expansion failed.\nGot: %q\nWant: %q", result, expected)
105			}
106		}
107	}
108}