|
| 1 | +package runner_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "reflect" |
| 6 | + "syscall" |
| 7 | + "testing" |
| 8 | + "time" |
| 9 | + |
| 10 | + "github.com/raksly/runner" |
| 11 | + "github.com/stretchr/testify/assert" |
| 12 | +) |
| 13 | + |
| 14 | +func run() { |
| 15 | + time.Sleep(time.Second) |
| 16 | +} |
| 17 | + |
| 18 | +func runContext(ctx context.Context) { |
| 19 | + <-ctx.Done() |
| 20 | +} |
| 21 | + |
| 22 | +func assertChan(assert *assert.Assertions, c interface{}, expectClosed bool) { |
| 23 | + if expectClosed { |
| 24 | + _, ok := reflect.ValueOf(c).Recv() |
| 25 | + assert.False(ok) |
| 26 | + } else { |
| 27 | + chosen, _, _ := reflect.Select([]reflect.SelectCase{ |
| 28 | + reflect.SelectCase{Dir: reflect.SelectDefault}, |
| 29 | + reflect.SelectCase{Dir: reflect.SelectRecv, Chan: reflect.ValueOf(c)}, |
| 30 | + }) |
| 31 | + assert.Equal(0, chosen) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +func Test1(t *testing.T) { |
| 36 | + assert := assert.New(t) |
| 37 | + |
| 38 | + ctx, cancel := context.WithCancel(context.Background()) |
| 39 | + runner := runner.New(ctx) |
| 40 | + |
| 41 | + assert.Equal(ctx, runner.Context()) |
| 42 | + |
| 43 | + c1 := runner.Run(run) |
| 44 | + c2 := runner.RunContext(runContext) |
| 45 | + c3 := runner.RunOtherContext(ctx, runContext) |
| 46 | + c4 := runner.RunSigs(syscall.SIGINT) |
| 47 | + |
| 48 | + select { |
| 49 | + case <-c1: |
| 50 | + case <-c2: |
| 51 | + assert.Fail("should not run") |
| 52 | + case <-c3: |
| 53 | + assert.Fail("should not run") |
| 54 | + case <-c4: |
| 55 | + assert.Fail("should not run") |
| 56 | + } |
| 57 | + |
| 58 | + assertChan(assert, c1, true) |
| 59 | + assertChan(assert, c2, false) |
| 60 | + assertChan(assert, c3, false) |
| 61 | + assertChan(assert, c4, false) |
| 62 | + |
| 63 | + cancel() |
| 64 | + runner.Wait() |
| 65 | + |
| 66 | + assertChan(assert, c2, true) |
| 67 | + assertChan(assert, c3, true) |
| 68 | + assertChan(assert, c4, false) |
| 69 | +} |
0 commit comments