routes_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. package server
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/binary"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "io/fs"
  10. "math"
  11. "math/rand/v2"
  12. "net"
  13. "net/http"
  14. "net/http/httptest"
  15. "os"
  16. "path/filepath"
  17. "sort"
  18. "strings"
  19. "testing"
  20. "unicode"
  21. "github.com/ollama/ollama/api"
  22. "github.com/ollama/ollama/llm"
  23. "github.com/ollama/ollama/openai"
  24. "github.com/ollama/ollama/parser"
  25. "github.com/ollama/ollama/types/model"
  26. "github.com/ollama/ollama/version"
  27. )
  28. func createTestFile(t *testing.T, name string) string {
  29. t.Helper()
  30. f, err := os.CreateTemp(t.TempDir(), name)
  31. if err != nil {
  32. t.Fatalf("failed to create temp file: %v", err)
  33. }
  34. defer f.Close()
  35. err = binary.Write(f, binary.LittleEndian, []byte("GGUF"))
  36. if err != nil {
  37. t.Fatalf("failed to write to file: %v", err)
  38. }
  39. err = binary.Write(f, binary.LittleEndian, uint32(3))
  40. if err != nil {
  41. t.Fatalf("failed to write to file: %v", err)
  42. }
  43. err = binary.Write(f, binary.LittleEndian, uint64(0))
  44. if err != nil {
  45. t.Fatalf("failed to write to file: %v", err)
  46. }
  47. err = binary.Write(f, binary.LittleEndian, uint64(0))
  48. if err != nil {
  49. t.Fatalf("failed to write to file: %v", err)
  50. }
  51. return f.Name()
  52. }
  53. // equalStringSlices checks if two slices of strings are equal.
  54. func equalStringSlices(a, b []string) bool {
  55. if len(a) != len(b) {
  56. return false
  57. }
  58. for i := range a {
  59. if a[i] != b[i] {
  60. return false
  61. }
  62. }
  63. return true
  64. }
  65. func Test_Routes(t *testing.T) {
  66. type testCase struct {
  67. Name string
  68. Method string
  69. Path string
  70. Setup func(t *testing.T, req *http.Request)
  71. Expected func(t *testing.T, resp *http.Response)
  72. }
  73. createTestModel := func(t *testing.T, name string) {
  74. t.Helper()
  75. fname := createTestFile(t, "ollama-model")
  76. r := strings.NewReader(fmt.Sprintf("FROM %s\nPARAMETER seed 42\nPARAMETER top_p 0.9\nPARAMETER stop foo\nPARAMETER stop bar", fname))
  77. modelfile, err := parser.ParseFile(r)
  78. if err != nil {
  79. t.Fatalf("failed to parse file: %v", err)
  80. }
  81. fn := func(resp api.ProgressResponse) {
  82. t.Logf("Status: %s", resp.Status)
  83. }
  84. err = CreateModel(context.TODO(), model.ParseName(name), "", "", modelfile, fn)
  85. if err != nil {
  86. t.Fatalf("failed to create model: %v", err)
  87. }
  88. }
  89. testCases := []testCase{
  90. {
  91. Name: "Version Handler",
  92. Method: http.MethodGet,
  93. Path: "/api/version",
  94. Setup: func(t *testing.T, req *http.Request) {
  95. },
  96. Expected: func(t *testing.T, resp *http.Response) {
  97. contentType := resp.Header.Get("Content-Type")
  98. if contentType != "application/json; charset=utf-8" {
  99. t.Errorf("expected content type application/json; charset=utf-8, got %s", contentType)
  100. }
  101. body, err := io.ReadAll(resp.Body)
  102. if err != nil {
  103. t.Fatalf("failed to read response body: %v", err)
  104. }
  105. expectedBody := fmt.Sprintf(`{"version":"%s"}`, version.Version)
  106. if string(body) != expectedBody {
  107. t.Errorf("expected body %s, got %s", expectedBody, string(body))
  108. }
  109. },
  110. },
  111. {
  112. Name: "Tags Handler (no tags)",
  113. Method: http.MethodGet,
  114. Path: "/api/tags",
  115. Expected: func(t *testing.T, resp *http.Response) {
  116. contentType := resp.Header.Get("Content-Type")
  117. if contentType != "application/json; charset=utf-8" {
  118. t.Errorf("expected content type application/json; charset=utf-8, got %s", contentType)
  119. }
  120. body, err := io.ReadAll(resp.Body)
  121. if err != nil {
  122. t.Fatalf("failed to read response body: %v", err)
  123. }
  124. var modelList api.ListResponse
  125. err = json.Unmarshal(body, &modelList)
  126. if err != nil {
  127. t.Fatalf("failed to unmarshal response body: %v", err)
  128. }
  129. if modelList.Models == nil || len(modelList.Models) != 0 {
  130. t.Errorf("expected empty model list, got %v", modelList.Models)
  131. }
  132. },
  133. },
  134. {
  135. Name: "openai empty list",
  136. Method: http.MethodGet,
  137. Path: "/v1/models",
  138. Expected: func(t *testing.T, resp *http.Response) {
  139. contentType := resp.Header.Get("Content-Type")
  140. if contentType != "application/json" {
  141. t.Errorf("expected content type application/json, got %s", contentType)
  142. }
  143. body, err := io.ReadAll(resp.Body)
  144. if err != nil {
  145. t.Fatalf("failed to read response body: %v", err)
  146. }
  147. var modelList openai.ListCompletion
  148. err = json.Unmarshal(body, &modelList)
  149. if err != nil {
  150. t.Fatalf("failed to unmarshal response body: %v", err)
  151. }
  152. if modelList.Object != "list" || len(modelList.Data) != 0 {
  153. t.Errorf("expected empty model list, got %v", modelList.Data)
  154. }
  155. },
  156. },
  157. {
  158. Name: "Tags Handler (yes tags)",
  159. Method: http.MethodGet,
  160. Path: "/api/tags",
  161. Setup: func(t *testing.T, req *http.Request) {
  162. createTestModel(t, "test-model")
  163. },
  164. Expected: func(t *testing.T, resp *http.Response) {
  165. contentType := resp.Header.Get("Content-Type")
  166. if contentType != "application/json; charset=utf-8" {
  167. t.Errorf("expected content type application/json; charset=utf-8, got %s", contentType)
  168. }
  169. body, err := io.ReadAll(resp.Body)
  170. if err != nil {
  171. t.Fatalf("failed to read response body: %v", err)
  172. }
  173. if strings.Contains(string(body), "expires_at") {
  174. t.Errorf("response body should not contain 'expires_at'")
  175. }
  176. var modelList api.ListResponse
  177. err = json.Unmarshal(body, &modelList)
  178. if err != nil {
  179. t.Fatalf("failed to unmarshal response body: %v", err)
  180. }
  181. if len(modelList.Models) != 1 || modelList.Models[0].Name != "test-model:latest" {
  182. t.Errorf("expected model 'test-model:latest', got %v", modelList.Models)
  183. }
  184. },
  185. },
  186. {
  187. Name: "Delete Model Handler",
  188. Method: http.MethodDelete,
  189. Path: "/api/delete",
  190. Setup: func(t *testing.T, req *http.Request) {
  191. createTestModel(t, "model-to-delete")
  192. deleteReq := api.DeleteRequest{
  193. Name: "model-to-delete",
  194. }
  195. jsonData, err := json.Marshal(deleteReq)
  196. if err != nil {
  197. t.Fatalf("failed to marshal delete request: %v", err)
  198. }
  199. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  200. },
  201. Expected: func(t *testing.T, resp *http.Response) {
  202. if resp.StatusCode != http.StatusOK {
  203. t.Errorf("expected status code 200, got %d", resp.StatusCode)
  204. }
  205. // Verify the model was deleted
  206. _, err := GetModel("model-to-delete")
  207. if err == nil || !os.IsNotExist(err) {
  208. t.Errorf("expected model to be deleted, got error %v", err)
  209. }
  210. },
  211. },
  212. {
  213. Name: "Delete Non-existent Model",
  214. Method: http.MethodDelete,
  215. Path: "/api/delete",
  216. Setup: func(t *testing.T, req *http.Request) {
  217. deleteReq := api.DeleteRequest{
  218. Name: "non-existent-model",
  219. }
  220. jsonData, err := json.Marshal(deleteReq)
  221. if err != nil {
  222. t.Fatalf("failed to marshal delete request: %v", err)
  223. }
  224. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  225. },
  226. Expected: func(t *testing.T, resp *http.Response) {
  227. if resp.StatusCode != http.StatusNotFound {
  228. t.Errorf("expected status code 404, got %d", resp.StatusCode)
  229. }
  230. body, err := io.ReadAll(resp.Body)
  231. if err != nil {
  232. t.Fatalf("failed to read response body: %v", err)
  233. }
  234. var errorResp map[string]string
  235. err = json.Unmarshal(body, &errorResp)
  236. if err != nil {
  237. t.Fatalf("failed to unmarshal response body: %v", err)
  238. }
  239. if !strings.Contains(errorResp["error"], "not found") {
  240. t.Errorf("expected error message to contain 'not found', got %s", errorResp["error"])
  241. }
  242. },
  243. },
  244. {
  245. Name: "openai list models with tags",
  246. Method: http.MethodGet,
  247. Path: "/v1/models",
  248. Expected: func(t *testing.T, resp *http.Response) {
  249. contentType := resp.Header.Get("Content-Type")
  250. if contentType != "application/json" {
  251. t.Errorf("expected content type application/json, got %s", contentType)
  252. }
  253. body, err := io.ReadAll(resp.Body)
  254. if err != nil {
  255. t.Fatalf("failed to read response body: %v", err)
  256. }
  257. var modelList openai.ListCompletion
  258. err = json.Unmarshal(body, &modelList)
  259. if err != nil {
  260. t.Fatalf("failed to unmarshal response body: %v", err)
  261. }
  262. if len(modelList.Data) != 1 || modelList.Data[0].Id != "test-model:latest" || modelList.Data[0].OwnedBy != "library" {
  263. t.Errorf("expected model 'test-model:latest' owned by 'library', got %v", modelList.Data)
  264. }
  265. },
  266. },
  267. {
  268. Name: "Create Model Handler",
  269. Method: http.MethodPost,
  270. Path: "/api/create",
  271. Setup: func(t *testing.T, req *http.Request) {
  272. fname := createTestFile(t, "ollama-model")
  273. stream := false
  274. createReq := api.CreateRequest{
  275. Name: "t-bone",
  276. Modelfile: fmt.Sprintf("FROM %s", fname),
  277. Stream: &stream,
  278. }
  279. jsonData, err := json.Marshal(createReq)
  280. if err != nil {
  281. t.Fatalf("failed to marshal create request: %v", err)
  282. }
  283. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  284. },
  285. Expected: func(t *testing.T, resp *http.Response) {
  286. contentType := resp.Header.Get("Content-Type")
  287. if contentType != "application/json" {
  288. t.Errorf("expected content type application/json, got %s", contentType)
  289. }
  290. _, err := io.ReadAll(resp.Body)
  291. if err != nil {
  292. t.Fatalf("failed to read response body: %v", err)
  293. }
  294. if resp.StatusCode != http.StatusOK { // Updated line
  295. t.Errorf("expected status code 200, got %d", resp.StatusCode)
  296. }
  297. model, err := GetModel("t-bone")
  298. if err != nil {
  299. t.Fatalf("failed to get model: %v", err)
  300. }
  301. if model.ShortName != "t-bone:latest" {
  302. t.Errorf("expected model name 't-bone:latest', got %s", model.ShortName)
  303. }
  304. },
  305. },
  306. {
  307. Name: "Copy Model Handler",
  308. Method: http.MethodPost,
  309. Path: "/api/copy",
  310. Setup: func(t *testing.T, req *http.Request) {
  311. createTestModel(t, "hamshank")
  312. copyReq := api.CopyRequest{
  313. Source: "hamshank",
  314. Destination: "beefsteak",
  315. }
  316. jsonData, err := json.Marshal(copyReq)
  317. if err != nil {
  318. t.Fatalf("failed to marshal copy request: %v", err)
  319. }
  320. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  321. },
  322. Expected: func(t *testing.T, resp *http.Response) {
  323. model, err := GetModel("beefsteak")
  324. if err != nil {
  325. t.Fatalf("failed to get model: %v", err)
  326. }
  327. if model.ShortName != "beefsteak:latest" {
  328. t.Errorf("expected model name 'beefsteak:latest', got %s", model.ShortName)
  329. }
  330. },
  331. },
  332. {
  333. Name: "Show Model Handler",
  334. Method: http.MethodPost,
  335. Path: "/api/show",
  336. Setup: func(t *testing.T, req *http.Request) {
  337. createTestModel(t, "show-model")
  338. showReq := api.ShowRequest{Model: "show-model"}
  339. jsonData, err := json.Marshal(showReq)
  340. if err != nil {
  341. t.Fatalf("failed to marshal show request: %v", err)
  342. }
  343. req.Body = io.NopCloser(bytes.NewReader(jsonData))
  344. },
  345. Expected: func(t *testing.T, resp *http.Response) {
  346. contentType := resp.Header.Get("Content-Type")
  347. if contentType != "application/json; charset=utf-8" {
  348. t.Errorf("expected content type application/json; charset=utf-8, got %s", contentType)
  349. }
  350. body, err := io.ReadAll(resp.Body)
  351. if err != nil {
  352. t.Fatalf("failed to read response body: %v", err)
  353. }
  354. var showResp api.ShowResponse
  355. err = json.Unmarshal(body, &showResp)
  356. if err != nil {
  357. t.Fatalf("failed to unmarshal response body: %v", err)
  358. }
  359. var params []string
  360. paramsSplit := strings.Split(showResp.Parameters, "\n")
  361. for _, p := range paramsSplit {
  362. params = append(params, strings.Join(strings.Fields(p), " "))
  363. }
  364. sort.Strings(params)
  365. expectedParams := []string{
  366. "seed 42",
  367. "stop \"bar\"",
  368. "stop \"foo\"",
  369. "top_p 0.9",
  370. }
  371. if !equalStringSlices(params, expectedParams) {
  372. t.Errorf("expected parameters %v, got %v", expectedParams, params)
  373. }
  374. paramCount, ok := showResp.ModelInfo["general.parameter_count"].(float64)
  375. if !ok {
  376. t.Fatalf("expected parameter count to be a float64, got %T", showResp.ModelInfo["general.parameter_count"])
  377. }
  378. if math.Abs(paramCount) > 1e-9 {
  379. t.Errorf("expected parameter count to be 0, got %f", paramCount)
  380. }
  381. },
  382. },
  383. {
  384. Name: "openai retrieve model handler",
  385. Method: http.MethodGet,
  386. Path: "/v1/models/show-model",
  387. Expected: func(t *testing.T, resp *http.Response) {
  388. contentType := resp.Header.Get("Content-Type")
  389. if contentType != "application/json" {
  390. t.Errorf("expected content type application/json, got %s", contentType)
  391. }
  392. body, err := io.ReadAll(resp.Body)
  393. if err != nil {
  394. t.Fatalf("failed to read response body: %v", err)
  395. }
  396. var retrieveResp api.RetrieveModelResponse
  397. err = json.Unmarshal(body, &retrieveResp)
  398. if err != nil {
  399. t.Fatalf("failed to unmarshal response body: %v", err)
  400. }
  401. if retrieveResp.Id != "show-model" || retrieveResp.OwnedBy != "library" {
  402. t.Errorf("expected model 'show-model' owned by 'library', got %v", retrieveResp)
  403. }
  404. },
  405. },
  406. }
  407. t.Setenv("OLLAMA_MODELS", t.TempDir())
  408. s := &Server{}
  409. router := s.GenerateRoutes()
  410. httpSrv := httptest.NewServer(router)
  411. t.Cleanup(httpSrv.Close)
  412. for _, tc := range testCases {
  413. t.Run(tc.Name, func(t *testing.T) {
  414. u := httpSrv.URL + tc.Path
  415. req, err := http.NewRequestWithContext(context.TODO(), tc.Method, u, nil)
  416. if err != nil {
  417. t.Fatalf("failed to create request: %v", err)
  418. }
  419. if tc.Setup != nil {
  420. tc.Setup(t, req)
  421. }
  422. resp, err := httpSrv.Client().Do(req)
  423. if err != nil {
  424. t.Fatalf("failed to do request: %v", err)
  425. }
  426. defer resp.Body.Close()
  427. if tc.Expected != nil {
  428. tc.Expected(t, resp)
  429. }
  430. })
  431. }
  432. }
  433. func casingShuffle(s string) string {
  434. rr := []rune(s)
  435. for i := range rr {
  436. if rand.N(2) == 0 {
  437. rr[i] = unicode.ToUpper(rr[i])
  438. } else {
  439. rr[i] = unicode.ToLower(rr[i])
  440. }
  441. }
  442. return string(rr)
  443. }
  444. func TestManifestCaseSensitivity(t *testing.T) {
  445. t.Setenv("OLLAMA_MODELS", t.TempDir())
  446. r := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  447. w.WriteHeader(http.StatusOK)
  448. io.WriteString(w, `{}`) //nolint:errcheck
  449. }))
  450. defer r.Close()
  451. nameUsed := make(map[string]bool)
  452. name := func() string {
  453. const fqmn = "example/namespace/model:tag"
  454. for {
  455. v := casingShuffle(fqmn)
  456. if nameUsed[v] {
  457. continue
  458. }
  459. nameUsed[v] = true
  460. return v
  461. }
  462. }
  463. wantStableName := name()
  464. t.Logf("stable name: %s", wantStableName)
  465. // checkManifestList tests that there is strictly one manifest in the
  466. // models directory, and that the manifest is for the model under test.
  467. checkManifestList := func() {
  468. t.Helper()
  469. mandir := filepath.Join(os.Getenv("OLLAMA_MODELS"), "manifests/")
  470. var entries []string
  471. t.Logf("dir entries:")
  472. fsys := os.DirFS(mandir)
  473. err := fs.WalkDir(fsys, ".", func(path string, info fs.DirEntry, err error) error {
  474. if err != nil {
  475. return err
  476. }
  477. t.Logf(" %s", fs.FormatDirEntry(info))
  478. if info.IsDir() {
  479. return nil
  480. }
  481. path = strings.TrimPrefix(path, mandir)
  482. entries = append(entries, path)
  483. return nil
  484. })
  485. if err != nil {
  486. t.Fatalf("failed to walk directory: %v", err)
  487. }
  488. if len(entries) != 1 {
  489. t.Errorf("len(got) = %d, want 1", len(entries))
  490. return // do not use Fatal so following steps run
  491. }
  492. g := entries[0] // raw path
  493. g = filepath.ToSlash(g)
  494. w := model.ParseName(wantStableName).Filepath()
  495. w = filepath.ToSlash(w)
  496. if g != w {
  497. t.Errorf("\ngot: %s\nwant: %s", g, w)
  498. }
  499. }
  500. checkOK := func(w *httptest.ResponseRecorder) {
  501. t.Helper()
  502. if w.Code != http.StatusOK {
  503. t.Errorf("code = %d, want 200", w.Code)
  504. t.Logf("body: %s", w.Body.String())
  505. }
  506. }
  507. var s Server
  508. testMakeRequestDialContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
  509. var d net.Dialer
  510. return d.DialContext(ctx, "tcp", r.Listener.Addr().String())
  511. }
  512. t.Cleanup(func() { testMakeRequestDialContext = nil })
  513. t.Logf("creating")
  514. checkOK(createRequest(t, s.CreateHandler, api.CreateRequest{
  515. // Start with the stable name, and later use a case-shuffled
  516. // version.
  517. Name: wantStableName,
  518. Modelfile: fmt.Sprintf("FROM %s", createBinFile(t, nil, nil)),
  519. Stream: &stream,
  520. }))
  521. checkManifestList()
  522. t.Logf("creating (again)")
  523. checkOK(createRequest(t, s.CreateHandler, api.CreateRequest{
  524. Name: name(),
  525. Modelfile: fmt.Sprintf("FROM %s", createBinFile(t, nil, nil)),
  526. Stream: &stream,
  527. }))
  528. checkManifestList()
  529. t.Logf("pulling")
  530. checkOK(createRequest(t, s.PullHandler, api.PullRequest{
  531. Name: name(),
  532. Stream: &stream,
  533. Insecure: true,
  534. }))
  535. checkManifestList()
  536. t.Logf("copying")
  537. checkOK(createRequest(t, s.CopyHandler, api.CopyRequest{
  538. Source: name(),
  539. Destination: name(),
  540. }))
  541. checkManifestList()
  542. t.Logf("pushing")
  543. rr := createRequest(t, s.PushHandler, api.PushRequest{
  544. Model: name(),
  545. Insecure: true,
  546. Username: "alice",
  547. Password: "x",
  548. })
  549. checkOK(rr)
  550. if !strings.Contains(rr.Body.String(), `"status":"success"`) {
  551. t.Errorf("got = %q, want success", rr.Body.String())
  552. }
  553. }
  554. func TestShow(t *testing.T) {
  555. t.Setenv("OLLAMA_MODELS", t.TempDir())
  556. var s Server
  557. createRequest(t, s.CreateHandler, api.CreateRequest{
  558. Name: "show-model",
  559. Modelfile: fmt.Sprintf(
  560. "FROM %s\nFROM %s",
  561. createBinFile(t, llm.KV{"general.architecture": "test"}, nil),
  562. createBinFile(t, llm.KV{"general.type": "projector", "general.architecture": "clip"}, nil),
  563. ),
  564. })
  565. w := createRequest(t, s.ShowHandler, api.ShowRequest{
  566. Name: "show-model",
  567. })
  568. if w.Code != http.StatusOK {
  569. t.Fatalf("expected status code 200, actual %d", w.Code)
  570. }
  571. var resp api.ShowResponse
  572. if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
  573. t.Fatal(err)
  574. }
  575. if resp.ModelInfo["general.architecture"] != "test" {
  576. t.Fatal("Expected model architecture to be 'test', but got", resp.ModelInfo["general.architecture"])
  577. }
  578. if resp.ProjectorInfo["general.architecture"] != "clip" {
  579. t.Fatal("Expected projector architecture to be 'clip', but got", resp.ProjectorInfo["general.architecture"])
  580. }
  581. }
  582. func TestNormalize(t *testing.T) {
  583. type testCase struct {
  584. input []float32
  585. }
  586. testCases := []testCase{
  587. {input: []float32{1}},
  588. {input: []float32{0, 1, 2, 3}},
  589. {input: []float32{0.1, 0.2, 0.3}},
  590. {input: []float32{-0.1, 0.2, 0.3, -0.4}},
  591. {input: []float32{0, 0, 0}},
  592. }
  593. isNormalized := func(vec []float32) (res bool) {
  594. sum := 0.0
  595. for _, v := range vec {
  596. sum += float64(v * v)
  597. }
  598. if math.Abs(sum-1) > 1e-6 {
  599. return sum == 0
  600. } else {
  601. return true
  602. }
  603. }
  604. for _, tc := range testCases {
  605. t.Run("", func(t *testing.T) {
  606. normalized := normalize(tc.input)
  607. if !isNormalized(normalized) {
  608. t.Errorf("Vector %v is not normalized", tc.input)
  609. }
  610. })
  611. }
  612. }