github.com/axw/juju@v0.0.0-20161005053422-4bd6544d08d4/resource/resourcetesting/resource.go (about) 1 // Copyright 2016 Canonical Ltd. 2 // Licensed under the AGPLv3, see LICENCE file for details. 3 4 // This package provides helpers for testing with resources. 5 package resourcetesting 6 7 import ( 8 "io" 9 "strings" 10 "time" 11 12 "github.com/juju/testing" 13 jc "github.com/juju/testing/checkers" 14 "github.com/juju/testing/filetesting" 15 gc "gopkg.in/check.v1" 16 charmresource "gopkg.in/juju/charm.v6-unstable/resource" 17 18 "github.com/juju/juju/resource" 19 ) 20 21 // NewResource produces full resource info for the given name and 22 // content. The origin is set set to "upload". A reader is also returned 23 // which contains the content. 24 func NewResource(c *gc.C, stub *testing.Stub, name, applicationID, content string) resource.Opened { 25 username := "a-user" 26 return resource.Opened{ 27 Resource: newResource(c, name, applicationID, username, content), 28 ReadCloser: newStubReadCloser(stub, content), 29 } 30 } 31 32 // NewCharmResource produces basic resource info for the given name 33 // and content. The origin is set set to "upload". 34 func NewCharmResource(c *gc.C, name, content string) charmresource.Resource { 35 fp, err := charmresource.GenerateFingerprint(strings.NewReader(content)) 36 c.Assert(err, jc.ErrorIsNil) 37 res := charmresource.Resource{ 38 Meta: charmresource.Meta{ 39 Name: name, 40 Type: charmresource.TypeFile, 41 Path: name + ".tgz", 42 }, 43 Origin: charmresource.OriginUpload, 44 Revision: 0, 45 Fingerprint: fp, 46 Size: int64(len(content)), 47 } 48 err = res.Validate() 49 c.Assert(err, jc.ErrorIsNil) 50 51 return res 52 } 53 54 // NewPlaceholderResource returns resource info for a resource that 55 // has not been uploaded or pulled from the charm store yet. The origin 56 // is set to "upload". 57 func NewPlaceholderResource(c *gc.C, name, applicationID string) resource.Resource { 58 res := newResource(c, name, applicationID, "", "") 59 res.Fingerprint = charmresource.Fingerprint{} 60 return res 61 } 62 63 func newResource(c *gc.C, name, applicationID, username, content string) resource.Resource { 64 var timestamp time.Time 65 if username != "" { 66 // TODO(perrito666) 2016-05-02 lp:1558657 67 timestamp = time.Now().UTC() 68 } 69 res := resource.Resource{ 70 Resource: NewCharmResource(c, name, content), 71 ID: applicationID + "/" + name, 72 PendingID: "", 73 ApplicationID: applicationID, 74 Username: username, 75 Timestamp: timestamp, 76 } 77 err := res.Validate() 78 c.Assert(err, jc.ErrorIsNil) 79 return res 80 } 81 82 type stubReadCloser struct { 83 io.Reader 84 io.Closer 85 } 86 87 func newStubReadCloser(stub *testing.Stub, content string) io.ReadCloser { 88 return &stubReadCloser{ 89 Reader: filetesting.NewStubReader(stub, content), 90 Closer: &filetesting.StubCloser{ 91 Stub: stub, 92 }, 93 } 94 }