OLD | NEW |
(Empty) | |
| 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 package memlock |
| 6 |
| 7 import ( |
| 8 "fmt" |
| 9 "infra/gae/libs/wrapper" |
| 10 "infra/gae/libs/wrapper/memory" |
| 11 "testing" |
| 12 "time" |
| 13 |
| 14 . "github.com/smartystreets/goconvey/convey" |
| 15 "golang.org/x/net/context" |
| 16 |
| 17 "appengine/memcache" |
| 18 ) |
| 19 |
| 20 func init() { |
| 21 delay = time.Millisecond |
| 22 memcacheLockTime = time.Millisecond * 4 |
| 23 } |
| 24 |
| 25 func TestSimple(t *testing.T) { |
| 26 // TODO(riannucci): Mock time.After so that we don't have to delay for r
eal. |
| 27 |
| 28 Convey("basic locking", t, func() { |
| 29 c := memory.Use(context.Background()) |
| 30 mc := wrapper.GetMC(c).(interface { |
| 31 wrapper.Testable |
| 32 wrapper.MCSingleReadWriter |
| 33 }) |
| 34 |
| 35 Convey("fails to acquire when memcache is down", func() { |
| 36 mc.BreakFeatures(nil, "Add") |
| 37 err := TryWithLock(c, "testkey", "id", func(check func()
bool) error { |
| 38 // should never reach here |
| 39 So(false, ShouldBeTrue) |
| 40 return nil |
| 41 }) |
| 42 So(err, ShouldEqual, ErrFailedToLock) |
| 43 }) |
| 44 |
| 45 Convey("returns the inner error", func() { |
| 46 toRet := fmt.Errorf("sup") |
| 47 err := TryWithLock(c, "testkey", "id", func(check func()
bool) error { |
| 48 return toRet |
| 49 }) |
| 50 So(err, ShouldEqual, toRet) |
| 51 }) |
| 52 |
| 53 Convey("can acquire when empty", func() { |
| 54 err := TryWithLock(c, "testkey", "id", func(check func()
bool) error { |
| 55 So(check(), ShouldBeTrue) |
| 56 |
| 57 Convey("waiting for a while keeps refreshing the
lock", func() { |
| 58 time.Sleep(memcacheLockTime * 8) |
| 59 So(check(), ShouldBeTrue) |
| 60 }) |
| 61 |
| 62 Convey("but sometimes we might lose it", func()
{ |
| 63 Convey("because it was evicted", func()
{ |
| 64 mc.Delete(memlockKeyPrefix + "te
stkey") |
| 65 time.Sleep(memcacheLockTime) |
| 66 So(check(), ShouldBeFalse) |
| 67 }) |
| 68 |
| 69 Convey("because it got evicted (but we r
ace)", func() { |
| 70 mc.Set(&memcache.Item{ |
| 71 Key: memlockKeyPrefix
+ "testkey", |
| 72 Value: []byte(""), |
| 73 }) |
| 74 }) |
| 75 |
| 76 Convey("or because it was stolen", func(
) { |
| 77 mc.Set(&memcache.Item{ |
| 78 Key: memlockKeyPrefix
+ "testkey", |
| 79 Value: []byte("wat"), |
| 80 }) |
| 81 time.Sleep(memcacheLockTime) |
| 82 So(check(), ShouldBeFalse) |
| 83 }) |
| 84 |
| 85 Convey("or because of service issues", f
unc() { |
| 86 mc.BreakFeatures(nil, "CompareAn
dSwap") |
| 87 time.Sleep(memcacheLockTime) |
| 88 So(check(), ShouldBeFalse) |
| 89 }) |
| 90 }) |
| 91 return nil |
| 92 }) |
| 93 So(err, ShouldBeNil) |
| 94 }) |
| 95 |
| 96 Convey("an empty context id is an error", func() { |
| 97 So(TryWithLock(c, "testkey", "", nil), ShouldEqual, ErrE
mptyClientID) |
| 98 }) |
| 99 }) |
| 100 } |
OLD | NEW |