| 1263 | } |
| 1264 | |
| 1265 | func TestUpdate(t *testing.T) { |
| 1266 | testName := "Update" |
| 1267 | cache := NewCache(1024) |
| 1268 | key := []byte("abcd") |
| 1269 | val1 := []byte("efgh") |
| 1270 | val2 := []byte("ijkl") |
| 1271 | |
| 1272 | var found, replaced bool |
| 1273 | var err error |
| 1274 | var prevVal, updaterVal []byte |
| 1275 | updaterReplace := false |
| 1276 | expireSeconds := 123 |
| 1277 | |
| 1278 | updater := func(value []byte, found bool) ([]byte, bool, int) { |
| 1279 | prevVal = value |
| 1280 | return updaterVal, updaterReplace, expireSeconds |
| 1281 | } |
| 1282 | |
| 1283 | setUpdaterResponse := func(value []byte, replace bool) { |
| 1284 | updaterVal = value |
| 1285 | updaterReplace = replace |
| 1286 | } |
| 1287 | |
| 1288 | assertExpectations := func(testCase int, expectedFound, expectedReplaced bool, expectedPrevVal []byte, |
| 1289 | expectedVal []byte, |
| 1290 | ) { |
| 1291 | failPrefix := fmt.Sprintf("%s(%d)", testName, testCase) |
| 1292 | |
| 1293 | if expectedFound != found { |
| 1294 | t.Fatalf("%s found should be %v", failPrefix, expectedFound) |
| 1295 | } |
| 1296 | if expectedReplaced != replaced { |
| 1297 | t.Fatalf("%s found should be %v", failPrefix, expectedReplaced) |
| 1298 | } |
| 1299 | if err != nil { |
| 1300 | t.Fatalf("%s unexpected err %v", failPrefix, err) |
| 1301 | } |
| 1302 | if string(prevVal) != string(expectedPrevVal) { |
| 1303 | t.Fatalf("%s previous value expected %s instead of %s", failPrefix, string(expectedPrevVal), |
| 1304 | string(prevVal)) |
| 1305 | } |
| 1306 | |
| 1307 | // Check value |
| 1308 | value, err := cache.Get(key) |
| 1309 | if err == ErrNotFound && expectedVal != nil { |
| 1310 | t.Fatalf("%s previous value expected %s instead of nil", failPrefix, string(expectedVal)) |
| 1311 | } |
| 1312 | if string(value) != string(expectedVal) { |
| 1313 | t.Fatalf("%s previous value expected %s instead of %s", failPrefix, string(expectedVal), string(value)) |
| 1314 | } |
| 1315 | } |
| 1316 | |
| 1317 | // Doesn't exist yet, decide not to update, set should not be called |
| 1318 | found, replaced, err = cache.Update(key, updater) |
| 1319 | assertExpectations(1, false, false, nil, nil) |
| 1320 | |
| 1321 | // Doesn't exist yet, decide to update, set should be called with new value |
| 1322 | setUpdaterResponse(val1, true) |