cat / 012
clone

a spreadsheet for the terminal: lotus 1-2-3 looks, google sheets keys and formulas, one go binary

main
012 / internal / jev / check_test.go
check_test.go 2.4K
1package jev23import (4 "context"5 "encoding/json"6 "net/http"7 "net/http/httptest"8 "strings"9 "sync/atomic"10 "testing"11)1213// fakeTypeSafe stands in for the TypeSafe API, accepting only key and14// answering yes/no questions with 0.9. It counts requests and remembers15// the last question.16func fakeTypeSafe(t *testing.T, key string) (*httptest.Server, *atomic.Int32, *atomic.Value) {17 t.Helper()18 var n atomic.Int3219 var last atomic.Value20 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {21 n.Add(1)22 if r.Header.Get("Authorization") != "Bearer "+key {23 w.Header().Set("Content-Type", "application/json")24 w.WriteHeader(http.StatusUnauthorized)25 w.Write([]byte(`{"error":{"message":"invalid api key"}}`))26 return27 }28 var req struct {29 Questions map[string]struct {30 Type string `json:"type"`31 Instructions string `json:"instructions"`32 } `json:"questions"`33 }34 json.NewDecoder(r.Body).Decode(&req)35 last.Store(req.Questions["answer"].Instructions)36 json.NewEncoder(w).Encode(map[string]any{37 "model": "jev-latest",38 "answers": map[string]any{"answer": map[string]any{"type": "noul", "noul": 0.9}},39 "usage": map[string]int{"input_tokens": 1, "output_tokens": 1},40 })41 }))42 t.Cleanup(srv.Close)43 return srv, &n, &last44}4546// Check asks one fixed question; a key the service refuses fails with47// a reason that doesn't hold the key.48func TestCheck(t *testing.T) {49 srv, n, last := fakeTypeSafe(t, "good-key")50 c, err := NewClient(Config{APIKey: "good-key", BaseURL: srv.URL})51 if err != nil {52 t.Fatal(err)53 }54 if err := Check(context.Background(), c); err != nil {55 t.Fatalf("good key: %v", err)56 }57 if n.Load() != 1 || last.Load() != CheckQuestion {58 t.Errorf("%d requests, question %q", n.Load(), last.Load())59 }6061 const bad = "bad-key-12345"62 c, _ = NewClient(Config{APIKey: bad, BaseURL: srv.URL})63 err = Check(context.Background(), c)64 if err == nil || !strings.Contains(err.Error(), "refused the key (HTTP 401)") || strings.Contains(err.Error(), bad) {65 t.Errorf("bad key: %v", err)66 }67}6869// A service that can't be reached is said in few words.70func TestCheckUnreachable(t *testing.T) {71 c, err := NewClient(Config{APIKey: "k", BaseURL: "http://127.0.0.1:1"})72 if err != nil {73 t.Fatal(err)74 }75 if err := Check(context.Background(), c); err == nil || err.Error() != "couldn't reach the service: connection refused" {76 t.Errorf("unreachable: %v", err)77 }78}