| 99 | } |
| 100 | |
| 101 | func TestChainDelayIfStillRunning(t *testing.T) { |
| 102 | |
| 103 | t.Run("runs immediately", func(t *testing.T) { |
| 104 | var j countJob |
| 105 | wrappedJob := NewChain(DelayIfStillRunning(DiscardLogger)).Then(&j) |
| 106 | go wrappedJob.Run() |
| 107 | time.Sleep(2 * time.Millisecond) // Give the job 2ms to complete. |
| 108 | if c := j.Done(); c != 1 { |
| 109 | t.Errorf("expected job run once, immediately, got %d", c) |
| 110 | } |
| 111 | }) |
| 112 | |
| 113 | t.Run("second run immediate if first done", func(t *testing.T) { |
| 114 | var j countJob |
| 115 | wrappedJob := NewChain(DelayIfStillRunning(DiscardLogger)).Then(&j) |
| 116 | go func() { |
| 117 | go wrappedJob.Run() |
| 118 | time.Sleep(time.Millisecond) |
| 119 | go wrappedJob.Run() |
| 120 | }() |
| 121 | time.Sleep(3 * time.Millisecond) // Give both jobs 3ms to complete. |
| 122 | if c := j.Done(); c != 2 { |
| 123 | t.Errorf("expected job run twice, immediately, got %d", c) |
| 124 | } |
| 125 | }) |
| 126 | |
| 127 | t.Run("second run delayed if first not done", func(t *testing.T) { |
| 128 | var j countJob |
| 129 | j.delay = 10 * time.Millisecond |
| 130 | wrappedJob := NewChain(DelayIfStillRunning(DiscardLogger)).Then(&j) |
| 131 | go func() { |
| 132 | go wrappedJob.Run() |
| 133 | time.Sleep(time.Millisecond) |
| 134 | go wrappedJob.Run() |
| 135 | }() |
| 136 | |
| 137 | // After 5ms, the first job is still in progress, and the second job was |
| 138 | // run but should be waiting for it to finish. |
| 139 | time.Sleep(5 * time.Millisecond) |
| 140 | started, done := j.Started(), j.Done() |
| 141 | if started != 1 || done != 0 { |
| 142 | t.Error("expected first job started, but not finished, got", started, done) |
| 143 | } |
| 144 | |
| 145 | // Verify that the second job completes. |
| 146 | time.Sleep(25 * time.Millisecond) |
| 147 | started, done = j.Started(), j.Done() |
| 148 | if started != 2 || done != 2 { |
| 149 | t.Error("expected both jobs done, got", started, done) |
| 150 | } |
| 151 | }) |
| 152 | |
| 153 | } |
| 154 | |
| 155 | func TestChainSkipIfStillRunning(t *testing.T) { |
| 156 | |