github.com/wallyworld/juju@v0.0.0-20161013125918-6cf1bc9d917a/featuretests/bakerystorage_test.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 package featuretests 5 6 import ( 7 "time" 8 9 "github.com/juju/juju/mongo" 10 "github.com/juju/juju/state/bakerystorage" 11 gitjujutesting "github.com/juju/testing" 12 jc "github.com/juju/testing/checkers" 13 gc "gopkg.in/check.v1" 14 "gopkg.in/macaroon-bakery.v1/bakery" 15 "gopkg.in/macaroon.v1" 16 "gopkg.in/mgo.v2" 17 ) 18 19 // This suite is not about a feature tests per se, but tests the integration 20 // of the mongo-based bakery storage with the macaroon bakery service. 21 type BakeryStorageSuite struct { 22 gitjujutesting.MgoSuite 23 24 store bakerystorage.ExpirableStorage 25 service *bakery.Service 26 db *mgo.Database 27 coll *mgo.Collection 28 } 29 30 func (s *BakeryStorageSuite) SetUpTest(c *gc.C) { 31 s.MgoSuite.SetUpTest(c) 32 s.db = s.Session.DB("bakerydb") 33 s.coll = s.db.C("bakedgoods") 34 s.ensureIndexes(c) 35 s.initService(c, false) 36 } 37 38 func (s *BakeryStorageSuite) initService(c *gc.C, enableExpiry bool) { 39 store, err := bakerystorage.New(bakerystorage.Config{ 40 GetCollection: func() (mongo.Collection, func()) { 41 return mongo.CollectionFromName(s.db, s.coll.Name) 42 }, 43 }) 44 c.Assert(err, jc.ErrorIsNil) 45 if enableExpiry { 46 store = store.ExpireAt(time.Now()) 47 } 48 s.store = store 49 50 service, err := bakery.NewService(bakery.NewServiceParams{ 51 Location: "straya", 52 Store: s.store, 53 }) 54 c.Assert(err, jc.ErrorIsNil) 55 s.service = service 56 } 57 58 func (s *BakeryStorageSuite) ensureIndexes(c *gc.C) { 59 for _, index := range bakerystorage.MongoIndexes() { 60 err := s.coll.EnsureIndex(index) 61 c.Assert(err, jc.ErrorIsNil) 62 } 63 } 64 65 func (s *BakeryStorageSuite) TestCheckNewMacaroon(c *gc.C) { 66 mac, err := s.service.NewMacaroon("", nil, nil) 67 c.Assert(err, jc.ErrorIsNil) 68 _, err = s.service.CheckAny([]macaroon.Slice{{mac}}, nil, nil) 69 c.Assert(err, jc.ErrorIsNil) 70 } 71 72 func (s *BakeryStorageSuite) TestExpiryTime(c *gc.C) { 73 // Reinitialise bakery service with storage that will expire 74 // items immediately. 75 s.initService(c, true) 76 77 mac, err := s.service.NewMacaroon("", nil, nil) 78 c.Assert(err, jc.ErrorIsNil) 79 80 // The background thread that removes records runs every 60s. 81 // Give a little bit of leeway for loaded systems. 82 for i := 0; i < 90; i++ { 83 _, err = s.service.CheckAny([]macaroon.Slice{{mac}}, nil, nil) 84 if err == nil { 85 time.Sleep(time.Second) 86 continue 87 } 88 c.Assert(err, gc.ErrorMatches, "verification failed: macaroon not found in storage") 89 return 90 } 91 c.Fatal("timed out waiting for storage expiry") 92 }