github.com/GuanceCloud/cliutils@v1.1.21/pipeline/ptinput/refertable/runner_test.go (about) 1 // Unless explicitly stated otherwise all files in this repository are licensed 2 // under the MIT License. 3 // This product includes software developed at Guance Cloud (https://www.guance.com/). 4 // Copyright 2021-present Guance, Inc. 5 6 package refertable 7 8 import ( 9 "context" 10 "net/http" 11 "net/http/httptest" 12 "testing" 13 "time" 14 15 "github.com/stretchr/testify/assert" 16 ) 17 18 func TestCheckUrl(t *testing.T) { 19 cases := []struct { 20 url string 21 scheme string 22 fail bool 23 }{ 24 { 25 url: "ht\tp//localss(", 26 scheme: "http", 27 fail: true, 28 }, 29 { 30 url: "httpS://localss(", 31 scheme: "https", 32 fail: true, 33 }, 34 { 35 url: "https://localhost/aa?a", 36 scheme: "https", 37 }, 38 { 39 url: "http://localhost/aa?a", 40 scheme: "http", 41 }, 42 { 43 url: "oss://localhost/aa?a", 44 scheme: "oss", 45 fail: true, 46 }, 47 } 48 49 for _, v := range cases { 50 scheme, err := checkURL(v.url) 51 if err != nil { 52 if !v.fail { 53 t.Error(err) 54 } 55 continue 56 } 57 assert.Equal(t, v.scheme, scheme) 58 } 59 } 60 61 func TestRunner(t *testing.T) { 62 files := map[string]string{ 63 "a.json": testTableData, 64 } 65 server := newJSONDataServer(files) 66 defer server.Close() 67 68 url := server.URL 69 70 ctx := context.Background() 71 ctx, cancel := context.WithCancel(ctx) 72 defer cancel() 73 74 refT, err := NewReferTable(RefTbCfg{ 75 URL: url + "?name=a.json", 76 Interval: time.Second * 5, 77 }) 78 if err != nil { 79 t.Fatal(err) 80 } 81 82 ok := refT.InitFinished(time.Second) 83 if ok { 84 t.Fatal("should not be done") 85 } 86 87 go refT.PullWorker(ctx) 88 89 ok = refT.InitFinished(time.Second) 90 if !ok { 91 t.Fatal("init not finishd") 92 } 93 94 tables := refT.Tables() 95 if tables == nil { 96 t.Fatal("refT == nil") 97 } 98 99 v, ok := tables.Query("table1", []string{"key1"}, []any{"a"}, nil) 100 if !ok || len(v) == 0 { 101 t.Error("!ok") 102 } 103 104 stats := tables.Stats() 105 assert.Equal(t, stats.Name[0], "table1") 106 assert.Equal(t, stats.Name[1], "table2") 107 assert.Equal(t, stats.Row[0], 3) 108 assert.Equal(t, stats.Row[1], 2) 109 } 110 111 func newJSONDataServer(files map[string]string) *httptest.Server { 112 server := httptest.NewServer(http.HandlerFunc( 113 func(w http.ResponseWriter, r *http.Request) { 114 switch r.Method { 115 case http.MethodGet: 116 default: 117 w.WriteHeader(http.StatusBadRequest) 118 return 119 } 120 name := r.FormValue("name") 121 data := files[name] 122 w.Write([]byte(data)) 123 w.WriteHeader(http.StatusOK) 124 }, 125 )) 126 return server 127 }