github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/cmd/juju/commands/register_test.go (about) 1 // Copyright 2015 Canonical Ltd. All rights reserved. 2 3 package commands 4 5 import ( 6 "encoding/json" 7 "net/http" 8 "net/http/httptest" 9 "net/url" 10 11 gc "gopkg.in/check.v1" 12 ) 13 14 var _ = gc.Suite(®istrationSuite{}) 15 16 type registrationSuite struct { 17 handler *testMetricsRegistrationHandler 18 server *httptest.Server 19 } 20 21 func (s *registrationSuite) SetUpTest(c *gc.C) { 22 s.handler = &testMetricsRegistrationHandler{} 23 s.server = httptest.NewServer(s.handler) 24 } 25 26 func (s *registrationSuite) TearDownTest(c *gc.C) { 27 s.server.Close() 28 } 29 30 func (s *registrationSuite) TestHttpMetricsRegistrar(c *gc.C) { 31 data, err := registerMetrics(s.server.URL, "environment uuid", "charm url", "service name", &http.Client{}, func(*url.URL) error { return nil }) 32 c.Assert(err, gc.IsNil) 33 var b []byte 34 err = json.Unmarshal(data, &b) 35 c.Assert(err, gc.IsNil) 36 c.Assert(string(b), gc.Equals, "hello registration") 37 c.Assert(s.handler.registrationCalls, gc.HasLen, 1) 38 c.Assert(s.handler.registrationCalls[0], gc.DeepEquals, metricRegistrationPost{EnvironmentUUID: "environment uuid", CharmURL: "charm url", ServiceName: "service name"}) 39 } 40 41 type testMetricsRegistrationHandler struct { 42 registrationCalls []metricRegistrationPost 43 } 44 45 // ServeHTTP implements http.Handler. 46 func (c *testMetricsRegistrationHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { 47 if req.Method != "POST" { 48 http.Error(w, "method not allowed", http.StatusMethodNotAllowed) 49 return 50 } 51 52 var registrationPost metricRegistrationPost 53 decoder := json.NewDecoder(req.Body) 54 err := decoder.Decode(®istrationPost) 55 if err != nil { 56 http.Error(w, "bad request", http.StatusBadRequest) 57 return 58 } 59 60 err = json.NewEncoder(w).Encode([]byte("hello registration")) 61 if err != nil { 62 panic(err) 63 } 64 65 c.registrationCalls = append(c.registrationCalls, registrationPost) 66 }