controls_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package app_test
  2. import (
  3. "net"
  4. "net/http"
  5. "net/http/httptest"
  6. "net/url"
  7. "strings"
  8. "testing"
  9. "time"
  10. "github.com/gorilla/mux"
  11. "github.com/ugorji/go/codec"
  12. "github.com/weaveworks/scope/app"
  13. "github.com/weaveworks/scope/common/xfer"
  14. "github.com/weaveworks/scope/probe/appclient"
  15. )
  16. func TestControl(t *testing.T) {
  17. router := mux.NewRouter()
  18. app.RegisterControlRoutes(router, app.NewLocalControlRouter())
  19. server := httptest.NewServer(router)
  20. defer server.Close()
  21. ip, port, err := net.SplitHostPort(strings.TrimPrefix(server.URL, "http://"))
  22. if err != nil {
  23. t.Fatal(err)
  24. }
  25. probeConfig := appclient.ProbeConfig{
  26. ProbeID: "foo",
  27. }
  28. controlHandler := xfer.ControlHandlerFunc(func(req xfer.Request) xfer.Response {
  29. if req.NodeID != "nodeid" {
  30. t.Fatalf("'%s' != 'nodeid'", req.NodeID)
  31. }
  32. if req.Control != "control" {
  33. t.Fatalf("'%s' != 'control'", req.Control)
  34. }
  35. return xfer.Response{
  36. Value: "foo",
  37. }
  38. })
  39. url := url.URL{Scheme: "http", Host: ip + ":" + port}
  40. client, err := appclient.NewAppClient(probeConfig, ip+":"+port, url, controlHandler)
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. client.ControlConnection()
  45. defer client.Stop()
  46. time.Sleep(100 * time.Millisecond)
  47. httpClient := http.Client{
  48. Timeout: 1 * time.Second,
  49. }
  50. resp, err := httpClient.Post(
  51. server.URL+"/api/control/foo/nodeid/control",
  52. "application/json",
  53. strings.NewReader("{}"),
  54. )
  55. if err != nil {
  56. t.Fatal(err)
  57. }
  58. defer resp.Body.Close()
  59. var response xfer.Response
  60. decoder := codec.NewDecoder(resp.Body, &codec.JsonHandle{})
  61. if err := decoder.Decode(&response); err != nil {
  62. t.Fatal(err)
  63. }
  64. if response.Value != "foo" {
  65. t.Fatalf("'%s' != 'foo'", response.Value)
  66. }
  67. }