routes_test.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. package server
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "net/http/httptest"
  11. "os"
  12. "sort"
  13. "strings"
  14. "testing"
  15. "github.com/stretchr/testify/assert"
  16. "github.com/ollama/ollama/api"
  17. "github.com/ollama/ollama/parser"
  18. "github.com/ollama/ollama/version"
  19. )
  20. func createTestFile(t *testing.T, name string) string {
  21. t.Helper()
  22. f, err := os.CreateTemp(t.TempDir(), name)
  23. assert.Nil(t, err)
  24. defer f.Close()
  25. err = binary.Write(f, binary.LittleEndian, []byte("GGUF"))
  26. assert.Nil(t, err)
  27. err = binary.Write(f, binary.LittleEndian, uint32(3))
  28. assert.Nil(t, err)
  29. err = binary.Write(f, binary.LittleEndian, uint64(0))
  30. assert.Nil(t, err)
  31. err = binary.Write(f, binary.LittleEndian, uint64(0))
  32. assert.Nil(t, err)
  33. return f.Name()
  34. }
  35. func Test_Routes(t *testing.T) {
  36. type testCase struct {
  37. Name string
  38. Method string
  39. Path string
  40. Setup func(t *testing.T, req *http.Request)
  41. Expected func(t *testing.T, resp *http.Response)
  42. }
  43. createTestModel := func(t *testing.T, name string) {
  44. fname := createTestFile(t, "ollama-model")
  45. r := strings.NewReader(fmt.Sprintf("FROM %s\nPARAMETER seed 42\nPARAMETER top_p 0.9\nPARAMETER stop foo\nPARAMETER stop bar", fname))
  46. modelfile, err := parser.ParseFile(r)
  47. assert.Nil(t, err)
  48. fn := func(resp api.ProgressResponse) {
  49. t.Logf("Status: %s", resp.Status)
  50. }
  51. err = CreateModel(context.TODO(), name, "", "", modelfile, fn)
  52. assert.Nil(t, err)
  53. }
  54. testCases := []testCase{
  55. {
  56. Name: "Version Handler",
  57. Method: http.MethodGet,
  58. Path: "/api/version",
  59. Setup: func(t *testing.T, req *http.Request) {
  60. },
  61. Expected: func(t *testing.T, resp *http.Response) {
  62. contentType := resp.Header.Get("Content-Type")
  63. assert.Equal(t, contentType, "application/json; charset=utf-8")
  64. body, err := io.ReadAll(resp.Body)
  65. assert.Nil(t, err)
  66. assert.Equal(t, fmt.Sprintf(`{"version":"%s"}`, version.Version), string(body))
  67. },
  68. },
  69. {
  70. Name: "Tags Handler (no tags)",
  71. Method: http.MethodGet,
  72. Path: "/api/tags",
  73. Expected: func(t *testing.T, resp *http.Response) {
  74. contentType := resp.Header.Get("Content-Type")
  75. assert.Equal(t, contentType, "application/json; charset=utf-8")
  76. body, err := io.ReadAll(resp.Body)
  77. assert.Nil(t, err)
  78. var modelList api.ListResponse
  79. err = json.Unmarshal(body, &modelList)
  80. assert.Nil(t, err)
  81. assert.NotNil(t, modelList.Models)
  82. assert.Equal(t, 0, len(modelList.Models))
  83. },
  84. },
  85. {
  86. Name: "Tags Handler (yes tags)",
  87. Method: http.MethodGet,
  88. Path: "/api/tags",
  89. Setup: func(t *testing.T, req *http.Request) {
  90. createTestModel(t, "test-model")
  91. },
  92. Expected: func(t *testing.T, resp *http.Response) {
  93. contentType := resp.Header.Get("Content-Type")
  94. assert.Equal(t, contentType, "application/json; charset=utf-8")
  95. body, err := io.ReadAll(resp.Body)
  96. assert.Nil(t, err)
  97. var modelList api.ListResponse
  98. err = json.Unmarshal(body, &modelList)
  99. assert.Nil(t, err)
  100. assert.Equal(t, 1, len(modelList.Models))
  101. assert.Equal(t, modelList.Models[0].Name, "test-model:latest")
  102. },
  103. },
  104. {
  105. Name: "Create Model Handler",
  106. Method: http.MethodPost,
  107. Path: "/api/create",
  108. Setup: func(t *testing.T, req *http.Request) {
  109. fname := createTestFile(t, "ollama-model")
  110. stream := false
  111. createReq := api.CreateRequest{
  112. Name: "t-bone",
  113. Modelfile: fmt.Sprintf("FROM %s", fname),
  114. Stream: &stream,
  115. }
  116. jsonData, err := json.Marshal(createReq)
  117. assert.Nil(t, err)
  118. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  119. },
  120. Expected: func(t *testing.T, resp *http.Response) {
  121. contentType := resp.Header.Get("Content-Type")
  122. assert.Equal(t, "application/json", contentType)
  123. _, err := io.ReadAll(resp.Body)
  124. assert.Nil(t, err)
  125. assert.Equal(t, resp.StatusCode, 200)
  126. model, err := GetModel("t-bone")
  127. assert.Nil(t, err)
  128. assert.Equal(t, "t-bone:latest", model.ShortName)
  129. },
  130. },
  131. {
  132. Name: "Copy Model Handler",
  133. Method: http.MethodPost,
  134. Path: "/api/copy",
  135. Setup: func(t *testing.T, req *http.Request) {
  136. createTestModel(t, "hamshank")
  137. copyReq := api.CopyRequest{
  138. Source: "hamshank",
  139. Destination: "beefsteak",
  140. }
  141. jsonData, err := json.Marshal(copyReq)
  142. assert.Nil(t, err)
  143. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  144. },
  145. Expected: func(t *testing.T, resp *http.Response) {
  146. model, err := GetModel("beefsteak")
  147. assert.Nil(t, err)
  148. assert.Equal(t, "beefsteak:latest", model.ShortName)
  149. },
  150. },
  151. {
  152. Name: "Show Model Handler",
  153. Method: http.MethodPost,
  154. Path: "/api/show",
  155. Setup: func(t *testing.T, req *http.Request) {
  156. createTestModel(t, "show-model")
  157. showReq := api.ShowRequest{Model: "show-model"}
  158. jsonData, err := json.Marshal(showReq)
  159. assert.Nil(t, err)
  160. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  161. },
  162. Expected: func(t *testing.T, resp *http.Response) {
  163. contentType := resp.Header.Get("Content-Type")
  164. assert.Equal(t, contentType, "application/json; charset=utf-8")
  165. body, err := io.ReadAll(resp.Body)
  166. assert.Nil(t, err)
  167. var showResp api.ShowResponse
  168. err = json.Unmarshal(body, &showResp)
  169. assert.Nil(t, err)
  170. var params []string
  171. paramsSplit := strings.Split(showResp.Parameters, "\n")
  172. for _, p := range paramsSplit {
  173. params = append(params, strings.Join(strings.Fields(p), " "))
  174. }
  175. sort.Strings(params)
  176. expectedParams := []string{
  177. "seed 42",
  178. "stop \"bar\"",
  179. "stop \"foo\"",
  180. "top_p 0.9",
  181. }
  182. assert.Equal(t, expectedParams, params)
  183. },
  184. },
  185. }
  186. t.Setenv("OLLAMA_MODELS", t.TempDir())
  187. s := &Server{}
  188. router := s.GenerateRoutes()
  189. httpSrv := httptest.NewServer(router)
  190. t.Cleanup(httpSrv.Close)
  191. for _, tc := range testCases {
  192. t.Run(tc.Name, func(t *testing.T) {
  193. u := httpSrv.URL + tc.Path
  194. req, err := http.NewRequestWithContext(context.TODO(), tc.Method, u, nil)
  195. assert.Nil(t, err)
  196. if tc.Setup != nil {
  197. tc.Setup(t, req)
  198. }
  199. resp, err := httpSrv.Client().Do(req)
  200. assert.Nil(t, err)
  201. defer resp.Body.Close()
  202. if tc.Expected != nil {
  203. tc.Expected(t, resp)
  204. }
  205. })
  206. }
  207. }
  208. func TestCase(t *testing.T) {
  209. t.Setenv("OLLAMA_MODELS", t.TempDir())
  210. cases := []string{
  211. "mistral",
  212. "llama3:latest",
  213. "library/phi3:q4_0",
  214. "registry.ollama.ai/library/gemma:q5_K_M",
  215. // TODO: host:port currently fails on windows (#4107)
  216. // "localhost:5000/alice/bob:latest",
  217. }
  218. var s Server
  219. for _, tt := range cases {
  220. t.Run(tt, func(t *testing.T) {
  221. w := createRequest(t, s.CreateModelHandler, api.CreateRequest{
  222. Name: tt,
  223. Modelfile: fmt.Sprintf("FROM %s", createBinFile(t)),
  224. Stream: &stream,
  225. })
  226. if w.Code != http.StatusOK {
  227. t.Fatalf("expected status 200 got %d", w.Code)
  228. }
  229. expect, err := json.Marshal(map[string]string{"error": "a model with that name already exists"})
  230. if err != nil {
  231. t.Fatal(err)
  232. }
  233. t.Run("create", func(t *testing.T) {
  234. w = createRequest(t, s.CreateModelHandler, api.CreateRequest{
  235. Name: strings.ToUpper(tt),
  236. Modelfile: fmt.Sprintf("FROM %s", createBinFile(t)),
  237. Stream: &stream,
  238. })
  239. if w.Code != http.StatusBadRequest {
  240. t.Fatalf("expected status 500 got %d", w.Code)
  241. }
  242. if !bytes.Equal(w.Body.Bytes(), expect) {
  243. t.Fatalf("expected error %s got %s", expect, w.Body.String())
  244. }
  245. })
  246. t.Run("pull", func(t *testing.T) {
  247. w := createRequest(t, s.PullModelHandler, api.PullRequest{
  248. Name: strings.ToUpper(tt),
  249. Stream: &stream,
  250. })
  251. if w.Code != http.StatusBadRequest {
  252. t.Fatalf("expected status 500 got %d", w.Code)
  253. }
  254. if !bytes.Equal(w.Body.Bytes(), expect) {
  255. t.Fatalf("expected error %s got %s", expect, w.Body.String())
  256. }
  257. })
  258. t.Run("copy", func(t *testing.T) {
  259. w := createRequest(t, s.CopyModelHandler, api.CopyRequest{
  260. Source: tt,
  261. Destination: strings.ToUpper(tt),
  262. })
  263. if w.Code != http.StatusBadRequest {
  264. t.Fatalf("expected status 500 got %d", w.Code)
  265. }
  266. if !bytes.Equal(w.Body.Bytes(), expect) {
  267. t.Fatalf("expected error %s got %s", expect, w.Body.String())
  268. }
  269. })
  270. })
  271. }
  272. }