forked from SUSE/zypper-docker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcache_test.go
More file actions
284 lines (245 loc) · 7.09 KB
/
cache_test.go
File metadata and controls
284 lines (245 loc) · 7.09 KB
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright (c) 2015 SUSE LLC. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"reflect"
"strings"
"syscall"
"testing"
)
// NOTE: some functions are already covered in other places of this test suite,
// so there's no point to add more tests in this specific file.
func TestCachePath(t *testing.T) {
home, umask := os.Getenv("HOME"), syscall.Umask(0)
abs, _ := filepath.Abs(".")
defer func() {
syscall.Umask(umask)
_ = os.RemoveAll(filepath.Join(abs, ".cache"))
_ = os.Setenv("HOME", home)
}()
_ = os.Setenv("HOME", abs)
if err := os.Mkdir(filepath.Join(abs, ".cache"), 0777); err != nil {
t.Fatal("Could not initialize test")
}
file := cachePath()
if file == nil {
t.Fatal("The given file should be ok")
}
info, err := file.Stat()
if err != nil {
t.Fatal("I should be able to stat the given file")
}
name, mode := file.Name(), info.Mode().Perm()
_ = file.Close()
_ = os.Remove(name)
if name != filepath.Join(abs, ".cache", cacheName) {
t.Fatal("Unexpected name")
}
if mode != 0666 {
t.Fatal("Given file does not come from hell ;)")
}
}
func TestCachePathFail(t *testing.T) {
home, umask := os.Getenv("HOME"), syscall.Umask(0)
defer func() {
syscall.Umask(umask)
_ = os.Setenv("HOME", home)
}()
_ = os.Setenv("HOME", "")
file, _ := os.OpenFile(filepath.Join("/tmp", cacheName), os.O_RDONLY|os.O_CREATE, 0000)
_ = file.Close()
buffer := bytes.NewBuffer([]byte{})
log.SetOutput(buffer)
cacheFile := getCacheFile()
if cacheFile.Valid {
t.Fatal("Cache should not be valid")
}
if !strings.Contains(buffer.String(), "Could not find path for the cache!") {
t.Fatal("Wrong log")
}
}
func TestCacheBadJson(t *testing.T) {
home, umask := os.Getenv("HOME"), syscall.Umask(0)
abs, _ := filepath.Abs(".")
test := filepath.Join(abs, "test")
defer func() {
syscall.Umask(umask)
_ = os.Setenv("HOME", home)
_ = os.Rename(filepath.Join(test, ".cache", cacheName),
filepath.Join(test, ".cache", "bad.json"))
}()
_ = os.Setenv("HOME", test)
_ = os.Rename(filepath.Join(test, ".cache", "bad.json"),
filepath.Join(test, ".cache", cacheName))
buffer := bytes.NewBuffer([]byte{})
log.SetOutput(buffer)
file := getCacheFile()
if !file.Valid {
t.Fatal("It should be valid")
}
if !strings.Contains(buffer.String(), "Decoding of cache file failed") {
t.Fatal("Wrong log")
}
}
func TestCacheGoodJson(t *testing.T) {
home, umask := os.Getenv("HOME"), syscall.Umask(0)
abs, _ := filepath.Abs(".")
test := filepath.Join(abs, "test")
defer func() {
syscall.Umask(umask)
_ = os.Setenv("HOME", home)
_ = os.Rename(filepath.Join(test, ".cache", cacheName),
filepath.Join(test, ".cache", "ok.json"))
}()
_ = os.Setenv("HOME", test)
_ = os.Rename(filepath.Join(test, ".cache", "ok.json"),
filepath.Join(test, ".cache", cacheName))
file := getCacheFile()
if !file.Valid {
t.Fatal("It should be valid")
}
if file.Path != filepath.Join(test, ".cache", cacheName) {
t.Fatal("Wrong path")
}
if len(file.Suse) != 2 {
t.Fatal("Wrong value for SUSE")
}
if len(file.Other) != 2 {
t.Fatal("Wrong value for Other")
}
if len(file.Outdated) != 0 {
t.Fatal("Wrong value for Outdated")
}
elements := append(file.Suse, file.Other...)
elements = append(elements, file.Outdated...)
for i, value := range elements {
if value != fmt.Sprintf("%v", i+1) {
t.Fatal("Wrong value")
}
}
}
func TestFlush(t *testing.T) {
abs, _ := filepath.Abs(".")
test := filepath.Join(abs, "test")
path := filepath.Join(test, "testflush.json")
cd := &cachedData{
Path: path,
Valid: false,
Suse: []string{},
Other: []string{},
Outdated: []string{},
}
// Now put some contents there.
expected := "{\"suse\": [\"1\"], \"other\": [], \"outdated\": []}"
err := ioutil.WriteFile(path, []byte(expected), 0666)
if err != nil {
t.Fatal("Failed on writing a file")
}
// It's invalid, flush will do nothing.
cd.flush()
contents, err := ioutil.ReadFile(path)
if err != nil {
t.Fatal("Failed on reading a file")
}
if strings.TrimSpace(string(contents)) != expected {
t.Fatal("Wrong contents")
}
// Now it will re-read the content of the file before writing to it
// again.
cd.Valid = true
cd.flush()
expected = "{\"suse\":[\"1\"],\"other\":[],\"outdated\":[]}"
contents, err = ioutil.ReadFile(path)
if err != nil {
t.Fatal("Failed on reading a file")
}
if strings.TrimSpace(string(contents)) != expected {
fmt.Println("got", string(contents), "instead of", expected)
t.Fatal("Wrong contents")
}
// If we remove the file and try to access it, it will print a proper
// error.
buffer := bytes.NewBuffer([]byte{})
log.SetOutput(buffer)
if err := os.Remove(path); err != nil {
t.Fatal("Could not remove temporary file")
}
cd.flush()
if !strings.Contains(buffer.String(), "Cannot write to the cache file") {
t.Fatal("Didn't logged what it was expected")
}
}
func TestUpdateCacheAfterUpdateFailsBecauseOfListError(t *testing.T) {
cache := cachedData{}
safeClient.client = &mockClient{listFail: true}
err := cache.updateCacheAfterUpdate("1", "2")
if err == nil {
t.Fatal("Expected failure")
}
}
func TestUpdateCacheAfterUpdateFailsBecauseOfListEmpty(t *testing.T) {
cache := cachedData{}
safeClient.client = &mockClient{listEmpty: true}
err := cache.updateCacheAfterUpdate("1", "2")
if err == nil {
t.Fatal("Expected failure")
}
}
func TestUpdateCacheAfterUpdateNothingDoneWhenTheImageIsAlreadyKnown(t *testing.T) {
cache := cachedData{
Outdated: []string{"35ae93c88cf8ab18da63bb2ad2dfd2399d745f292a344625fbb65892b7c25a01"},
Suse: []string{"2"}}
safeClient.client = &mockClient{listEmpty: true}
err := cache.updateCacheAfterUpdate("opensuse:13.2", "2")
if err == nil {
t.Fatal("Expected failure")
}
if len(cache.Outdated) != 1 {
t.Fatal("Nothing should have changed")
}
if len(cache.Suse) != 1 {
t.Fatal("Nothing should have changed")
}
}
func TestReadCacheSuccess(t *testing.T) {
cache := cachedData{}
expected := &cachedData{
Valid: true,
Suse: []string{"1"},
Other: []string{"2"},
Outdated: []string{"3"},
}
buffer := bytes.NewBufferString(`{"suse":["1"],"other":["2"],"outdated":["3"]}`)
got := cache.readCache(buffer)
if !reflect.DeepEqual(got, expected) {
t.Fatalf("Expected %v, got %v", expected, got)
}
}
func TestReadCacheFail(t *testing.T) {
cache := cachedData{}
expected := &cachedData{
Valid: true,
}
buffer := bytes.NewBufferString(`"suse":["1"],"other":["2"],"outdated":["3"]}`)
got := cache.readCache(buffer)
if !reflect.DeepEqual(got, expected) {
t.Fatalf("Expected %v, got %v", expected, got)
}
}