-
Notifications
You must be signed in to change notification settings - Fork 5
/
s3cache_test.go
113 lines (87 loc) · 2.49 KB
/
s3cache_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
// Copyright (c) 2016 Danilo Bürger <[email protected]>
package s3cache
import (
"bytes"
"context"
"io/ioutil"
"net/http"
"testing"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3iface"
"github.com/stretchr/testify/assert"
"golang.org/x/crypto/acme/autocert"
)
type testLogger struct {
called bool
}
func (l *testLogger) Printf(format string, v ...interface{}) {
l.called = true
}
func TestLogger(t *testing.T) {
c := &Cache{}
assert.NotPanics(t, func() {
c.log("")
})
l := &testLogger{}
c.Logger = l
assert.False(t, l.called)
c.log("")
assert.True(t, l.called)
}
type testS3 struct {
s3iface.S3API
cache map[string][]byte
}
func (t *testS3) GetObject(input *s3.GetObjectInput) (*s3.GetObjectOutput, error) {
b, ok := t.cache[*input.Key]
if !ok {
return nil, awserr.NewRequestFailure(nil, http.StatusNotFound, "")
}
return &s3.GetObjectOutput{
Body: ioutil.NopCloser(bytes.NewReader(b)),
}, nil
}
func (t *testS3) PutObject(input *s3.PutObjectInput) (*s3.PutObjectOutput, error) {
b, err := ioutil.ReadAll(input.Body)
if err != nil {
return nil, err
}
t.cache[*input.Key] = b
return &s3.PutObjectOutput{}, nil
}
func (t *testS3) DeleteObject(input *s3.DeleteObjectInput) (*s3.DeleteObjectOutput, error) {
delete(t.cache, *input.Key)
return &s3.DeleteObjectOutput{}, nil
}
func TestCache(t *testing.T) {
cache := &Cache{s3: &testS3{cache: map[string][]byte{}}}
ctx := context.Background()
_, err := cache.Get(ctx, "nonexistent")
assert.Equal(t, autocert.ErrCacheMiss, err)
b1 := []byte{1}
assert.NoError(t, cache.Put(ctx, "dummy", b1))
b2, err := cache.Get(ctx, "dummy")
assert.NoError(t, err)
assert.Equal(t, b1, b2)
assert.NoError(t, cache.Delete(ctx, "dummy"))
_, err = cache.Get(ctx, "dummy")
assert.Equal(t, autocert.ErrCacheMiss, err)
}
func TestCacheWithPrefix(t *testing.T) {
testS3Cache := &testS3{cache: map[string][]byte{}}
cache := &Cache{bucket: "my-bucket", s3: testS3Cache}
cache.Prefix = "/path/to/certs/here/"
ctx := context.Background()
_, err := cache.Get(ctx, "nonexistent")
assert.Equal(t, autocert.ErrCacheMiss, err)
b1 := []byte{1}
assert.NoError(t, cache.Put(ctx, "dummy", b1))
assert.Contains(t, testS3Cache.cache, "/path/to/certs/here/dummy")
b2, err := cache.Get(ctx, "dummy")
assert.NoError(t, err)
assert.Equal(t, b1, b2)
assert.NoError(t, cache.Delete(ctx, "dummy"))
_, err = cache.Get(ctx, "dummy")
assert.Equal(t, autocert.ErrCacheMiss, err)
}