|
| 1 | +//go:build integration |
| 2 | + |
| 3 | +package integration |
| 4 | + |
| 5 | +import ( |
| 6 | + "bytes" |
| 7 | + "context" |
| 8 | + "encoding/json" |
| 9 | + "fmt" |
| 10 | + "io" |
| 11 | + "log/slog" |
| 12 | + "math/rand" |
| 13 | + "net" |
| 14 | + "net/http" |
| 15 | + "os" |
| 16 | + "path/filepath" |
| 17 | + "runtime" |
| 18 | + "strconv" |
| 19 | + "strings" |
| 20 | + "sync" |
| 21 | + "testing" |
| 22 | + "time" |
| 23 | + |
| 24 | + "github.com/jmorganca/ollama/api" |
| 25 | + "github.com/jmorganca/ollama/app/lifecycle" |
| 26 | + "github.com/stretchr/testify/assert" |
| 27 | +) |
| 28 | + |
| 29 | +func FindPort() string { |
| 30 | + port := 0 |
| 31 | + if a, err := net.ResolveTCPAddr("tcp", "localhost:0"); err == nil { |
| 32 | + var l *net.TCPListener |
| 33 | + if l, err = net.ListenTCP("tcp", a); err == nil { |
| 34 | + port = l.Addr().(*net.TCPAddr).Port |
| 35 | + l.Close() |
| 36 | + } |
| 37 | + } |
| 38 | + if port == 0 { |
| 39 | + port = rand.Intn(65535-49152) + 49152 // get a random port in the ephemeral range |
| 40 | + } |
| 41 | + return strconv.Itoa(port) |
| 42 | +} |
| 43 | + |
| 44 | +func GetTestEndpoint() (string, string) { |
| 45 | + defaultPort := "11434" |
| 46 | + ollamaHost := os.Getenv("OLLAMA_HOST") |
| 47 | + |
| 48 | + scheme, hostport, ok := strings.Cut(ollamaHost, "://") |
| 49 | + if !ok { |
| 50 | + scheme, hostport = "http", ollamaHost |
| 51 | + } |
| 52 | + |
| 53 | + // trim trailing slashes |
| 54 | + hostport = strings.TrimRight(hostport, "/") |
| 55 | + |
| 56 | + host, port, err := net.SplitHostPort(hostport) |
| 57 | + if err != nil { |
| 58 | + host, port = "127.0.0.1", defaultPort |
| 59 | + if ip := net.ParseIP(strings.Trim(hostport, "[]")); ip != nil { |
| 60 | + host = ip.String() |
| 61 | + } else if hostport != "" { |
| 62 | + host = hostport |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + if os.Getenv("OLLAMA_TEST_EXISTING") == "" && port == defaultPort { |
| 67 | + port = FindPort() |
| 68 | + } |
| 69 | + |
| 70 | + url := fmt.Sprintf("%s:%s", host, port) |
| 71 | + slog.Info("server connection", "url", url) |
| 72 | + return scheme, url |
| 73 | +} |
| 74 | + |
| 75 | +// TODO make fanicier, grab logs, etc. |
| 76 | +var serverMutex sync.Mutex |
| 77 | +var serverReady bool |
| 78 | + |
| 79 | +func StartServer(ctx context.Context, ollamaHost string) error { |
| 80 | + // Make sure the server has been built |
| 81 | + CLIName, err := filepath.Abs("../ollama") |
| 82 | + if err != nil { |
| 83 | + return err |
| 84 | + } |
| 85 | + |
| 86 | + if runtime.GOOS == "windows" { |
| 87 | + CLIName += ".exe" |
| 88 | + } |
| 89 | + _, err = os.Stat(CLIName) |
| 90 | + if err != nil { |
| 91 | + return fmt.Errorf("CLI missing, did you forget to build first? %w", err) |
| 92 | + } |
| 93 | + serverMutex.Lock() |
| 94 | + defer serverMutex.Unlock() |
| 95 | + if serverReady { |
| 96 | + return nil |
| 97 | + } |
| 98 | + |
| 99 | + if tmp := os.Getenv("OLLAMA_HOST"); tmp != ollamaHost { |
| 100 | + slog.Info("setting env", "OLLAMA_HOST", ollamaHost) |
| 101 | + os.Setenv("OLLAMA_HOST", ollamaHost) |
| 102 | + } |
| 103 | + |
| 104 | + slog.Info("starting server", "url", ollamaHost) |
| 105 | + done, err := lifecycle.SpawnServer(ctx, "../ollama") |
| 106 | + if err != nil { |
| 107 | + return fmt.Errorf("failed to start server: %w", err) |
| 108 | + } |
| 109 | + |
| 110 | + go func() { |
| 111 | + <-ctx.Done() |
| 112 | + serverMutex.Lock() |
| 113 | + defer serverMutex.Unlock() |
| 114 | + exitCode := <-done |
| 115 | + if exitCode > 0 { |
| 116 | + slog.Warn("server failure", "exit", exitCode) |
| 117 | + } |
| 118 | + serverReady = false |
| 119 | + }() |
| 120 | + |
| 121 | + // TODO wait only long enough for the server to be responsive... |
| 122 | + time.Sleep(500 * time.Millisecond) |
| 123 | + |
| 124 | + serverReady = true |
| 125 | + return nil |
| 126 | +} |
| 127 | + |
| 128 | +func GenerateTestHelper(ctx context.Context, t *testing.T, client *http.Client, genReq api.GenerateRequest, anyResp []string) { |
| 129 | + requestJSON, err := json.Marshal(genReq) |
| 130 | + if err != nil { |
| 131 | + t.Fatalf("Error serializing request: %v", err) |
| 132 | + } |
| 133 | + defer func() { |
| 134 | + if t.Failed() && os.Getenv("OLLAMA_TEST_EXISTING") == "" { |
| 135 | + // TODO |
| 136 | + fp, err := os.Open(lifecycle.ServerLogFile) |
| 137 | + if err != nil { |
| 138 | + slog.Error("failed to open server log", "logfile", lifecycle.ServerLogFile, "error", err) |
| 139 | + return |
| 140 | + } |
| 141 | + data, err := io.ReadAll(fp) |
| 142 | + if err != nil { |
| 143 | + slog.Error("failed to read server log", "logfile", lifecycle.ServerLogFile, "error", err) |
| 144 | + return |
| 145 | + } |
| 146 | + slog.Warn("SERVER LOG FOLLOWS") |
| 147 | + os.Stderr.Write(data) |
| 148 | + slog.Warn("END OF SERVER") |
| 149 | + } |
| 150 | + err = os.Remove(lifecycle.ServerLogFile) |
| 151 | + if err != nil && !os.IsNotExist(err) { |
| 152 | + slog.Warn("failed to cleanup", "logfile", lifecycle.ServerLogFile, "error", err) |
| 153 | + } |
| 154 | + }() |
| 155 | + scheme, testEndpoint := GetTestEndpoint() |
| 156 | + |
| 157 | + if os.Getenv("OLLAMA_TEST_EXISTING") == "" { |
| 158 | + assert.NoError(t, StartServer(ctx, testEndpoint)) |
| 159 | + } |
| 160 | + |
| 161 | + // Make the request and get the response |
| 162 | + req, err := http.NewRequest("POST", scheme+"://"+testEndpoint+"/api/generate", bytes.NewReader(requestJSON)) |
| 163 | + if err != nil { |
| 164 | + t.Fatalf("Error creating request: %v", err) |
| 165 | + } |
| 166 | + |
| 167 | + // Set the content type for the request |
| 168 | + req.Header.Set("Content-Type", "application/json") |
| 169 | + |
| 170 | + // Make the request with the HTTP client |
| 171 | + response, err := client.Do(req.WithContext(ctx)) |
| 172 | + if err != nil { |
| 173 | + t.Fatalf("Error making request: %v", err) |
| 174 | + } |
| 175 | + body, err := io.ReadAll(response.Body) |
| 176 | + assert.NoError(t, err) |
| 177 | + assert.Equal(t, response.StatusCode, 200, string(body)) |
| 178 | + |
| 179 | + // Verify the response is valid JSON |
| 180 | + var payload api.GenerateResponse |
| 181 | + err = json.Unmarshal(body, &payload) |
| 182 | + if err != nil { |
| 183 | + assert.NoError(t, err, body) |
| 184 | + } |
| 185 | + |
| 186 | + // Verify the response contains the expected data |
| 187 | + for _, resp := range anyResp { |
| 188 | + assert.Contains(t, strings.ToLower(payload.Response), resp) |
| 189 | + } |
| 190 | +} |
0 commit comments