| 1 | package keepawake |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "testing" |
| 7 | "time" |
| 8 | ) |
| 9 | |
| 10 | func TestRetryAndRelease(t *testing.T) { |
| 11 | ctx, cancel := context.WithCancel(context.Background()) |
| 12 | defer cancel() |
| 13 | states := make(chan State, 8) |
| 14 | done := make(chan struct{}) |
| 15 | released := make(chan struct{}) |
| 16 | attempts := 0 |
| 17 | go func() { |
| 18 | defer close(done) |
| 19 | run(ctx, func(state State) { states <- state }, func(ctx context.Context, ready func()) error { |
| 20 | attempts++ |
| 21 | if attempts == 1 { |
| 22 | return errors.New("inhibitor unavailable") |
| 23 | } |
| 24 | ready() |
| 25 | <-ctx.Done() |
| 26 | close(released) |
| 27 | return ctx.Err() |
| 28 | }) |
| 29 | }() |
| 30 | read := func() State { |
| 31 | t.Helper() |
| 32 | select { |
| 33 | case state := <-states: |
| 34 | return state |
| 35 | case <-time.After(3 * time.Second): |
| 36 | t.Fatal("missing power request state") |
| 37 | return State{} |
| 38 | } |
| 39 | } |
| 40 | if state := read(); state.Active || state.Error == "" { |
| 41 | t.Fatal("failed request was hidden", state) |
| 42 | } |
| 43 | if state := read(); !state.Active || state.Error != "" { |
| 44 | t.Fatal("request did not recover", state) |
| 45 | } |
| 46 | cancel() |
| 47 | select { |
| 48 | case <-done: |
| 49 | case <-time.After(time.Second): |
| 50 | t.Fatal("request leaked after cancellation") |
| 51 | } |
| 52 | select { |
| 53 | case <-released: |
| 54 | default: |
| 55 | t.Fatal("native request was not released") |
| 56 | } |
| 57 | if state := read(); state != (State{}) { |
| 58 | t.Fatal("stopped request remained active", state) |
| 59 | } |
| 60 | } |