github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/cmd/modelcmd/apicontext_test.go (about) 1 // Copyright 2018 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package modelcmd_test 5 6 import ( 7 "io/ioutil" 8 "net/http" 9 "net/http/httptest" 10 11 jc "github.com/juju/testing/checkers" 12 gc "gopkg.in/check.v1" 13 "gopkg.in/macaroon-bakery.v2-unstable/httpbakery" 14 15 "github.com/juju/juju/cmd/modelcmd" 16 "github.com/juju/juju/jujuclient" 17 "github.com/juju/juju/testing" 18 ) 19 20 type APIContextSuite struct { 21 testing.FakeJujuXDGDataHomeSuite 22 } 23 24 var _ = gc.Suite(&APIContextSuite{}) 25 26 func (s *APIContextSuite) TestNewAPIContext(c *gc.C) { 27 store := jujuclient.NewFileClientStore() 28 29 ctx, err := modelcmd.NewAPIContext(nil, nil, store, "testcontroller") 30 c.Assert(err, jc.ErrorIsNil) 31 32 handler := func(w http.ResponseWriter, req *http.Request) { 33 // Set a cookie so we can check that cookies are 34 // saved. 35 http.SetCookie(w, &http.Cookie{ 36 Name: "cook", 37 Value: "val", 38 MaxAge: 1000, 39 }) 40 w.Write([]byte("hello")) 41 } 42 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 43 handler(w, req) 44 })) 45 defer srv.Close() 46 // Check that we can use the client. 47 assertClientGet(c, ctx.NewBakeryClient(), srv.URL, "hello") 48 49 // Close the context, which should save the cookies. 50 err = ctx.Close() 51 c.Assert(err, jc.ErrorIsNil) 52 53 // Make another APIContext which should 54 // get the cookies just saved. 55 ctx, err = modelcmd.NewAPIContext(nil, nil, store, "testcontroller") 56 c.Assert(err, jc.ErrorIsNil) 57 58 handler = func(w http.ResponseWriter, req *http.Request) { 59 c.Check(req.Cookies(), jc.DeepEquals, []*http.Cookie{{ 60 Name: "cook", 61 Value: "val", 62 }}) 63 w.Write([]byte("goodbye")) 64 } 65 assertClientGet(c, ctx.NewBakeryClient(), srv.URL, "goodbye") 66 } 67 68 func (s *APIContextSuite) TestDomainCookie(c *gc.C) { 69 store := jujuclient.NewFileClientStore() 70 s.PatchEnvironment("JUJU_USER_DOMAIN", "something") 71 ctx, err := modelcmd.NewAPIContext(nil, nil, store, "testcontroller") 72 c.Assert(err, jc.ErrorIsNil) 73 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { 74 c.Check(req.Cookies(), jc.DeepEquals, []*http.Cookie{{ 75 Name: "domain", 76 Value: "something", 77 }}) 78 w.Write([]byte("hello")) 79 })) 80 defer srv.Close() 81 // Check that we can use the client. 82 assertClientGet(c, ctx.NewBakeryClient(), srv.URL, "hello") 83 } 84 85 func assertClientGet(c *gc.C, client *httpbakery.Client, url string, expectBody string) { 86 req, err := http.NewRequest("GET", url, nil) 87 c.Assert(err, jc.ErrorIsNil) 88 resp, err := client.Do(req) 89 c.Assert(err, jc.ErrorIsNil) 90 defer resp.Body.Close() 91 c.Assert(resp.StatusCode, gc.Equals, http.StatusOK) 92 data, _ := ioutil.ReadAll(resp.Body) 93 c.Assert(string(data), gc.Equals, expectBody) 94 }