github.com/m-lab/locate@v0.17.6/cmd/monitoring-token/monitoring-token_test.go (about) 1 package main 2 3 import ( 4 "flag" 5 "net/http" 6 "net/http/httptest" 7 "net/url" 8 "os" 9 "strings" 10 "testing" 11 12 "github.com/m-lab/go/logx" 13 "github.com/m-lab/go/rtx" 14 ) 15 16 var ( 17 insecurePrivateKey = `{"use":"sig","kty":"OKP","kid":"insecure","crv":"Ed25519","alg":"EdDSA","x":"E50_cwU7ACoH_XM6We3AFLHVWA63xm2crFhKL-PUc3Y","d":"3JRzWpk6aILrhOnry41Fu3u9l0XbloAVhuVNowWqT_Y"}` 18 insecurePublicKey = `{"use":"sig","kty":"OKP","kid":"insecure","crv":"Ed25519","alg":"EdDSA","x":"E50_cwU7ACoH_XM6We3AFLHVWA63xm2crFhKL-PUc3Y"}` 19 ) 20 21 func Test_main(t *testing.T) { 22 tests := []struct { 23 name string 24 resp string 25 args []string 26 }{ 27 { 28 name: "error-service-url-error-not-nil", 29 resp: `{"error":{"type":"fake-error"}}`, 30 args: []string{"monitoring-token", "-service-url"}, 31 }, 32 { 33 name: "error-service-url-nil-target", 34 resp: `{}`, 35 args: []string{"monitoring-token", "-service-url"}, 36 }, 37 { 38 name: "error-service-url-args-target-len-zero", 39 resp: `{"target": {"urls": {"wss://:3010/ndt_protocol":""}}}`, 40 args: []string{"monitoring-token", "-service-url"}, 41 }, 42 { 43 name: "success-service-url-value-matches-check_env-arg", 44 // The value "FAKE_URL" is provided to the check_env.sh command via the environment. 45 // The argument to check_env.sh is the value it expects in the SERVICE_URL env variable. 46 resp: `{"target": {"urls": {"wss://:3010/ndt_protocol":"FAKE_VALUE"}}}`, 47 args: []string{"monitoring-token", "-service-url", "-env-name=SVC_URL", "--", "testdata/check_env.sh", "SVC_URL", "FAKE_VALUE"}, 48 }, 49 { 50 name: "success-locate-monitoring-url", 51 resp: `{}`, 52 args: []string{"monitoring-token"}, 53 }, 54 } 55 for _, tt := range tests { 56 t.Run(tt.name, func(t *testing.T) { 57 // Completely reset command line flags, since main uses these to run a command. 58 os.Args = tt.args 59 flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError) 60 if strings.Contains(tt.name, "success") { 61 // Enable debug logging on the success case to visit the 62 // stdout/stderr path when executing the command. 63 logx.LogxDebug.Set("true") 64 } 65 setupFlags() 66 67 logFatalf = func(format string, v ...interface{}) {} 68 handler := func(rw http.ResponseWriter, req *http.Request) { 69 rw.Write([]byte(tt.resp)) 70 } 71 privKey = []byte(insecurePrivateKey) 72 mux := http.NewServeMux() 73 mux.HandleFunc("/v2/platform/monitoring/", handler) 74 srv := httptest.NewServer(mux) 75 defer srv.Close() 76 var err error 77 locate.URL, err = url.Parse(srv.URL + "/v2/platform/monitoring/") 78 rtx.Must(err, "failed to parse url: %q", srv.URL) 79 80 main() 81 }) 82 } 83 }