github.com/cloud-green/juju@v0.0.0-20151002100041-a00291338d3d/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  
    10  	gc "gopkg.in/check.v1"
    11  	"gopkg.in/macaroon-bakery.v1/httpbakery"
    12  )
    13  
    14  var _ = gc.Suite(&registrationSuite{})
    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  	client := httpbakery.NewClient()
    32  	data, err := registerMetrics(s.server.URL, "environment uuid", "charm url", "service name", client)
    33  	c.Assert(err, gc.IsNil)
    34  	var b []byte
    35  	err = json.Unmarshal(data, &b)
    36  	c.Assert(err, gc.IsNil)
    37  	c.Assert(string(b), gc.Equals, "hello registration")
    38  	c.Assert(s.handler.registrationCalls, gc.HasLen, 1)
    39  	c.Assert(s.handler.registrationCalls[0], gc.DeepEquals, metricRegistrationPost{EnvironmentUUID: "environment uuid", CharmURL: "charm url", ServiceName: "service name"})
    40  }
    41  
    42  type testMetricsRegistrationHandler struct {
    43  	registrationCalls []metricRegistrationPost
    44  }
    45  
    46  // ServeHTTP implements http.Handler.
    47  func (c *testMetricsRegistrationHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
    48  	if req.Method != "POST" {
    49  		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
    50  		return
    51  	}
    52  
    53  	var registrationPost metricRegistrationPost
    54  	decoder := json.NewDecoder(req.Body)
    55  	err := decoder.Decode(&registrationPost)
    56  	if err != nil {
    57  		http.Error(w, "bad request", http.StatusBadRequest)
    58  		return
    59  	}
    60  
    61  	err = json.NewEncoder(w).Encode([]byte("hello registration"))
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  
    66  	c.registrationCalls = append(c.registrationCalls, registrationPost)
    67  }