github.com/drycc/workflow-cli@v1.5.3-0.20240322092846-d4ee25983af9/pkg/testutil/testutil.go (about) 1 package testutil 2 3 import ( 4 "encoding/json" 5 "io" 6 "net/http" 7 "net/http/httptest" 8 "os" 9 "path/filepath" 10 "strings" 11 "testing" 12 13 drycc "github.com/drycc/controller-sdk-go" 14 "github.com/drycc/workflow-cli/settings" 15 ) 16 17 // TestServer represents a test HTTP server along with a path to a config file 18 type TestServer struct { 19 Server *httptest.Server 20 Mux *http.ServeMux 21 } 22 23 // NewTestServer sets up a test HTTP Server without a configuration file. 24 func NewTestServer() *TestServer { 25 // test server 26 mux := http.NewServeMux() 27 server := httptest.NewServer(mux) 28 29 return &TestServer{ 30 Server: server, 31 Mux: mux, 32 } 33 } 34 35 // Close closes the test HTTP server. 36 func (t *TestServer) Close() { 37 t.Server.Close() 38 } 39 40 // NewTestServerAndClient sets up a test HTTP Server along with a configuration file to talk to it 41 func NewTestServerAndClient() (string, *TestServer, error) { 42 server := NewTestServer() 43 44 name, err := os.MkdirTemp("", "client") 45 if err != nil { 46 server.Close() 47 return "", nil, err 48 } 49 50 filename := filepath.Join(name, "test.json") 51 52 client, err := drycc.New(false, server.Server.URL, "") 53 if err != nil { 54 server.Close() 55 return "", nil, err 56 } 57 58 config := settings.Settings{ 59 Username: "test", 60 Client: client, 61 } 62 63 filename, err = config.Save(filename) 64 if err != nil { 65 server.Close() 66 return "", nil, err 67 } 68 return filename, server, nil 69 } 70 71 // AssertBody asserts the value of the body of a request. 72 func AssertBody(t *testing.T, expected interface{}, req *http.Request) { 73 body, err := io.ReadAll(req.Body) 74 if err != nil { 75 t.Fatal(err) 76 } 77 78 value, err := json.Marshal(expected) 79 if err != nil { 80 t.Fatal(err) 81 } 82 83 if string(body) != string(value) { 84 t.Errorf("Expected body '%s' actually got '%s'\n", value, body) 85 } 86 } 87 88 // StripProgress strips the output from the progress method 89 func StripProgress(input string) string { 90 first := strings.Index(input, "\b") 91 // If \b charecter not part of string 92 if first == -1 { 93 return input 94 } 95 last := strings.LastIndex(input, "\b") 96 97 // return string without \b or the characters it deletes. 98 return input[:first-(last-first+1)] + input[last+1:] 99 } 100 101 // SetHeaders sets standard headers for requests 102 func SetHeaders(w http.ResponseWriter) { 103 w.Header().Add("DRYCC_API_VERSION", drycc.APIVersion) 104 }