| 1 | package gcache |
| 2 | |
| 3 | /* |
| 4 | Copyright 2012 Google Inc. |
| 5 | |
| 6 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 7 | you may not use this file except in compliance with the License. |
| 8 | You may obtain a copy of the License at |
| 9 | |
| 10 | http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | |
| 12 | Unless required by applicable law or agreed to in writing, software |
| 13 | distributed under the License is distributed on an "AS IS" BASIS, |
| 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 15 | See the License for the specific language governing permissions and |
| 16 | limitations under the License. |
| 17 | */ |
| 18 | |
| 19 | import ( |
| 20 | "errors" |
| 21 | "fmt" |
| 22 | "sync" |
| 23 | "sync/atomic" |
| 24 | "testing" |
| 25 | "time" |
| 26 | ) |
| 27 | |
| 28 | func TestDo(t *testing.T) { |
| 29 | var g Group |
| 30 | g.cache = New(32).Build() |
| 31 | v, _, err := g.Do("key", func() (interface{}, error) { |
| 32 | return "bar", nil |
| 33 | }, true) |
| 34 | if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want { |
| 35 | t.Errorf("Do = %v; want %v", got, want) |
| 36 | } |
| 37 | if err != nil { |
| 38 | t.Errorf("Do error = %v", err) |
| 39 | } |
| 40 | } |
| 41 | |
| 42 | func TestDoErr(t *testing.T) { |
| 43 | var g Group |
| 44 | g.cache = New(32).Build() |
| 45 | someErr := errors.New("Some error") |
| 46 | v, _, err := g.Do("key", func() (interface{}, error) { |
| 47 | return nil, someErr |
| 48 | }, true) |
| 49 | if err != someErr { |
| 50 | t.Errorf("Do error = %v; want someErr", err) |
| 51 | } |
| 52 | if v != nil { |
| 53 | t.Errorf("unexpected non-nil value %#v", v) |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | func TestDoDupSuppress(t *testing.T) { |
| 58 | var g Group |
| 59 | g.cache = New(32).Build() |
| 60 | c := make(chan string) |
| 61 | var calls int32 |
| 62 | fn := func() (interface{}, error) { |
| 63 | atomic.AddInt32(&calls, 1) |
| 64 | return <-c, nil |
| 65 | } |
| 66 | |
| 67 | const n = 10 |
| 68 | var wg sync.WaitGroup |
| 69 | for i := 0; i < n; i++ { |
| 70 | wg.Add(1) |
| 71 | go func() { |
| 72 | v, _, err := g.Do("key", fn, true) |
| 73 | if err != nil { |
| 74 | t.Errorf("Do error: %v", err) |
| 75 | } |
| 76 | if v.(string) != "bar" { |
| 77 | t.Errorf("got %q; want %q", v, "bar") |
| 78 | } |
| 79 | wg.Done() |
| 80 | }() |
| 81 | } |
| 82 | time.Sleep(100 * time.Millisecond) // let goroutines above block |
| 83 | c <- "bar" |
| 84 | wg.Wait() |
| 85 | if got := atomic.LoadInt32(&calls); got != 1 { |
| 86 | t.Errorf("number of calls = %d; want 1", got) |
| 87 | } |
| 88 | } |