diff options
author | 2019-02-15 23:00:48 -0800 | |
---|---|---|
committer | 2019-02-19 11:19:09 -0800 | |
commit | d7cfaeeebc3a28077deeceec3ec6e0b81bec058a (patch) | |
tree | 9e016dbf002982ed8d677fd8ae7ee30553af620b | |
parent | 4f41bc2bed906b3baf973ffcdcf3f7f0cb987a1d (diff) |
Fix a bug in OncePer.Get that could return a waiter
OncePer.Get must call maybeWaitFor on the value it reads, otherwise
it could return a waiter instead of the real value.
Test: onceper_test.go
Change-Id: I7d407bd1c577dbb43bc14fa107d5f606bf2b1c67
-rw-r--r-- | android/onceper.go | 2 | ||||
-rw-r--r-- | android/onceper_test.go | 31 |
2 files changed, 32 insertions, 1 deletions
diff --git a/android/onceper.go b/android/onceper.go index f06f428d5..5ad17fa91 100644 --- a/android/onceper.go +++ b/android/onceper.go @@ -70,7 +70,7 @@ func (once *OncePer) Get(key OnceKey) interface{} { panic(fmt.Errorf("Get() called before Once()")) } - return v + return once.maybeWaitFor(key, v) } // OnceStringSlice is the same as Once, but returns the value cast to a []string diff --git a/android/onceper_test.go b/android/onceper_test.go index f27799bec..95303bafd 100644 --- a/android/onceper_test.go +++ b/android/onceper_test.go @@ -16,6 +16,7 @@ package android import ( "testing" + "time" ) func TestOncePer_Once(t *testing.T) { @@ -34,6 +35,21 @@ func TestOncePer_Once(t *testing.T) { } } +func TestOncePer_Once_wait(t *testing.T) { + once := OncePer{} + key := NewOnceKey("key") + + ch := make(chan bool) + + go once.Once(key, func() interface{} { close(ch); time.Sleep(100 * time.Millisecond); return "foo" }) + <-ch + a := once.Once(key, func() interface{} { return "bar" }).(string) + + if a != "foo" { + t.Errorf("expect %q, got %q", "foo", a) + } +} + func TestOncePer_Get(t *testing.T) { once := OncePer{} key := NewOnceKey("key") @@ -65,6 +81,21 @@ func TestOncePer_Get_panic(t *testing.T) { once.Get(key) } +func TestOncePer_Get_wait(t *testing.T) { + once := OncePer{} + key := NewOnceKey("key") + + ch := make(chan bool) + + go once.Once(key, func() interface{} { close(ch); time.Sleep(100 * time.Millisecond); return "foo" }) + <-ch + a := once.Get(key).(string) + + if a != "foo" { + t.Errorf("expect %q, got %q", "foo", a) + } +} + func TestOncePer_OnceStringSlice(t *testing.T) { once := OncePer{} key := NewOnceKey("key") |