|
14 | 14 | package dynacache
|
15 | 15 |
|
16 | 16 | import (
|
| 17 | + "errors" |
17 | 18 | "fmt"
|
18 | 19 | "path/filepath"
|
19 | 20 | "testing"
|
@@ -174,18 +175,47 @@ func TestPanicInCreate(t *testing.T) {
|
174 | 175 |
|
175 | 176 | p1 := GetOrCreatePartition[string, testItem](cache, "/aaaa/bbbb", OptionsPartition{Weight: 30, ClearWhen: ClearOnRebuild})
|
176 | 177 |
|
| 178 | + willPanic := func(i int) func() { |
| 179 | + return func() { |
| 180 | + p1.GetOrCreate(fmt.Sprintf("panic-%d", i), func(key string) (testItem, error) { |
| 181 | + panic(errors.New(key)) |
| 182 | + }) |
| 183 | + } |
| 184 | + } |
| 185 | + |
| 186 | + // GetOrCreateWitTimeout needs to recover from panics in the create func. |
| 187 | + willErr := func(i int) error { |
| 188 | + _, err := p1.GetOrCreateWitTimeout(fmt.Sprintf("error-%d", i), 10*time.Second, func(key string) (testItem, error) { |
| 189 | + return testItem{}, errors.New(key) |
| 190 | + }) |
| 191 | + return err |
| 192 | + } |
| 193 | + |
177 | 194 | for i := 0; i < 3; i++ {
|
178 | 195 | for j := 0; j < 3; j++ {
|
179 |
| - _, err := p1.GetOrCreate(fmt.Sprintf("panic1-%d", i), func(string) (testItem, error) { |
180 |
| - panic("failed") |
181 |
| - }) |
| 196 | + c.Assert(willPanic(i), qt.PanicMatches, fmt.Sprintf("panic-%d", i)) |
| 197 | + c.Assert(willErr(i), qt.ErrorMatches, fmt.Sprintf("error-%d", i)) |
| 198 | + } |
| 199 | + } |
182 | 200 |
|
183 |
| - c.Assert(err, qt.Not(qt.IsNil)) |
| 201 | + // Test the same keys again without the panic. |
| 202 | + for i := 0; i < 3; i++ { |
| 203 | + for j := 0; j < 3; j++ { |
| 204 | + v, err := p1.GetOrCreate(fmt.Sprintf("panic-%d", i), func(key string) (testItem, error) { |
| 205 | + return testItem{ |
| 206 | + name: key, |
| 207 | + }, nil |
| 208 | + }) |
| 209 | + c.Assert(err, qt.IsNil) |
| 210 | + c.Assert(v.name, qt.Equals, fmt.Sprintf("panic-%d", i)) |
184 | 211 |
|
185 |
| - _, err = p1.GetOrCreateWitTimeout(fmt.Sprintf("panic2-%d", i), 10*time.Second, func(string) (testItem, error) { |
186 |
| - panic("failed") |
| 212 | + v, err = p1.GetOrCreateWitTimeout(fmt.Sprintf("error-%d", i), 10*time.Second, func(key string) (testItem, error) { |
| 213 | + return testItem{ |
| 214 | + name: key, |
| 215 | + }, nil |
187 | 216 | })
|
188 |
| - c.Assert(err, qt.Not(qt.IsNil)) |
| 217 | + c.Assert(err, qt.IsNil) |
| 218 | + c.Assert(v.name, qt.Equals, fmt.Sprintf("error-%d", i)) |
189 | 219 | }
|
190 | 220 | }
|
191 | 221 | }
|
|
0 commit comments