github.com/keybase/client/go@v0.0.0-20240309051027-028f7c731f8b/kbnm/main_test.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "io" 7 "os/exec" 8 "strings" 9 "testing" 10 ) 11 12 func TestProcess(t *testing.T) { 13 h := newHandler() 14 15 var ranCmd string 16 h.Run = func(cmd *exec.Cmd) error { 17 ranCmd = strings.Join(cmd.Args, " ") 18 _ = ranCmd 19 return nil 20 } 21 h.FindKeybaseBinary = func() (string, error) { 22 return "/mocked/test/path/keybase", nil 23 } 24 25 var inBuf, outBuf bytes.Buffer 26 in := json.NewDecoder(&inBuf) 27 out := json.NewEncoder(&outBuf) 28 29 // Check invalid JSON: 30 _, err := io.WriteString(&inBuf, "invalid json, hi\n") 31 if err != nil { 32 t.Fatalf("Error writing string: %+v", err) 33 } 34 err = process(h, in, out) 35 if _, ok := err.(*json.SyntaxError); !ok { 36 t.Errorf("incorrect error on invalid JSON: %T", err) 37 } 38 // Reset the decoder 39 inBuf.Reset() 40 in = json.NewDecoder(&inBuf) 41 42 testCases := []struct { 43 In string 44 ExpectOut string 45 }{ 46 { 47 `{"method": "foo"}` + "\n", 48 `{"client":0,"status":"error","message":"invalid method"}` + "\n", 49 }, 50 { 51 `{"method": "chat", "to": "shazow", "body": "Hello, world."}` + "\n", 52 `{"client":0,"status":"ok","message":""}` + "\n", 53 }, 54 } 55 56 for i, test := range testCases { 57 outBuf.Reset() 58 59 _, err = io.WriteString(&inBuf, test.In) 60 if err != nil { 61 t.Fatalf("Error writing string: %+v", err) 62 } 63 if err := process(h, in, out); err != nil { 64 t.Fatalf("[case #%d] processing failed early: %s", i, err) 65 } 66 67 if want, got := test.ExpectOut, outBuf.String(); want != got { 68 t.Errorf("[case #%d] want:\n%s\ngot:\n%s", i, want, got) 69 } 70 } 71 }