-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker_wiring_internal_test.go
More file actions
427 lines (326 loc) · 10.8 KB
/
Copy pathworker_wiring_internal_test.go
File metadata and controls
427 lines (326 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package main
import (
"context"
"errors"
"os"
"path/filepath"
"sync/atomic"
"testing"
"time"
"github.com/gdamore/tcell/v2"
"github.com/hyperized/uAirwaves/pkg/location"
"github.com/hyperized/uAirwaves/pkg/selflocate"
"github.com/rivo/tview"
)
const (
workerDeadline = 3 * time.Second
// tickSettleDelay lets the millisecond-cadence UI loop fire several
// ticks before a test cancels it, so the ticker.C -> tickUI path is
// exercised deterministically.
tickSettleDelay = 30 * time.Millisecond
)
// errInjectedLoop is the sentinel a test pushes onto errChan to drive
// runUIUpdateLoop's error-teardown branch.
var errInjectedLoop = errors.New("injected loop failure")
// newCancelledUIC builds a uiComponents with its context already
// cancelled, so any worker started against it returns on its first
// context check instead of running its real poll/stream loop. The
// cleanup cancel is idempotent.
func newCancelledUIC(t *testing.T, cfg cliConfig) *uiComponents {
t.Helper()
uic := configureUI(cfg)
t.Cleanup(uic.cancel)
uic.cancel()
return uic
}
// waitGroupDone drains a WaitGroup with a deadline so a wedged worker
// fails the test loudly instead of hanging the suite.
func waitGroupDone(t *testing.T, uic *uiComponents) {
t.Helper()
done := make(chan struct{})
go func() {
uic.waitGroup.Wait()
close(done)
}()
select {
case <-done:
case <-time.After(workerDeadline):
t.Fatal("workers did not return after context cancellation")
}
}
// TestStartBatteryWatcherAutoDiscover covers the empty-path branch:
// battery.Watch is launched and returns once the cancelled context
// stops its poll loop, without landing anything on errChan.
func TestStartBatteryWatcherAutoDiscover(t *testing.T) {
t.Parallel()
uic := newCancelledUIC(t, cliConfig{})
startBatteryWatcher(uic, "")
waitGroupDone(t, uic)
if len(uic.errChan) != 0 {
t.Errorf("errChan len = %d, want 0 on clean cancellation", len(uic.errChan))
}
}
// TestStartBatteryWatcherExplicitPath covers the non-empty-path branch:
// WatchWithInterval is selected instead of Watch. The path points at a
// non-existent file so any read fails transiently and the cancelled
// context ends the loop cleanly.
func TestStartBatteryWatcherExplicitPath(t *testing.T) {
t.Parallel()
uic := newCancelledUIC(t, cliConfig{})
path := filepath.Join(t.TempDir(), "uevent")
startBatteryWatcher(uic, path)
waitGroupDone(t, uic)
if len(uic.errChan) != 0 {
t.Errorf("errChan len = %d, want 0 on clean cancellation", len(uic.errChan))
}
}
// TestStartGPSWatcher covers the GPS wiring: startGPSWatcher composes
// the fix-stamp callback and runs runGPSWatch with an explicit address.
// The cancelled context makes the reconnecting watch return without a
// live gpsd.
func TestStartGPSWatcher(t *testing.T) {
t.Parallel()
uic := newCancelledUIC(t, cliConfig{})
startGPSWatcher(uic, "127.0.0.1:0")
waitGroupDone(t, uic)
if len(uic.errChan) != 0 {
t.Errorf("errChan len = %d, want 0 on clean cancellation", len(uic.errChan))
}
}
// TestRunGPSWatchDefaultsReturnOnCancel covers the address-empty and
// nil-callback branches of runGPSWatch directly. A cancelled context
// drives the reconnecting watch to a clean nil return whether or not a
// gpsd is reachable.
func TestRunGPSWatchDefaultsReturnOnCancel(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
cancel()
done := make(chan error, 1)
go func() {
done <- runGPSWatch(ctx, location.New(), "", nil)
}()
select {
case err := <-done:
if err != nil {
t.Errorf("runGPSWatch = %v, want nil after cancellation", err)
}
case <-time.After(workerDeadline):
t.Fatal("runGPSWatch did not return after cancellation")
}
}
// TestStartSelfLocateWorker covers the self-locate wiring: the worker
// is launched and its ticker loop returns on the first context check.
func TestStartSelfLocateWorker(t *testing.T) {
t.Parallel()
uic := newCancelledUIC(t, cliConfig{})
startSelfLocateWorker(uic)
waitGroupDone(t, uic)
if len(uic.errChan) != 0 {
t.Errorf("errChan len = %d, want 0 on clean cancellation", len(uic.errChan))
}
}
// TestStartADSBStreamer covers the ADSB streamer wiring. A replay source
// pointed at a non-existent file makes Stream fail its first open and
// return the error, which LaunchWorker forwards to errChan — proving the
// wrapper wires the stream, worker supervision, and error channel
// together.
func TestStartADSBStreamer(t *testing.T) {
t.Parallel()
uic := newCancelledUIC(t, cliConfig{replayIQPath: "/nonexistent/uairwaves-test.iq"})
startADSBStreamer(uic)
waitGroupDone(t, uic)
select {
case err := <-uic.errChan:
if err == nil {
t.Error("errChan delivered a nil error; want the failed replay open")
}
default:
t.Error("startADSBStreamer did not forward the replay-open failure to errChan")
}
}
// TestStartADSBStreamerOpensReplay covers the replay receiver factory's
// success return: a readable file opens cleanly, so the factory hands
// back a receiver before the cancelled context stops the read. The
// non-existent-file sibling test covers the factory's error return.
func TestStartADSBStreamerOpensReplay(t *testing.T) {
t.Parallel()
path := filepath.Join(t.TempDir(), "capture.iq")
if err := os.WriteFile(path, []byte{0, 0}, 0o600); err != nil {
t.Fatalf("write replay fixture: %v", err)
}
uic := newCancelledUIC(t, cliConfig{replayIQPath: path})
startADSBStreamer(uic)
waitGroupDone(t, uic)
}
// TestStartUIUpdater covers the startUIUpdater wrapper: it registers the
// redraw loop on the WaitGroup, and the loop returns on the pre-cancelled
// context.
func TestStartUIUpdater(t *testing.T) {
t.Parallel()
uic := newCancelledUIC(t, cliConfig{})
startUIUpdater(uic)
waitGroupDone(t, uic)
}
// TestRunSelfLocateSkipsWhenEstimateNotReady covers the not-ready branch:
// with GPS stale but the locator empty, every tick's Estimate returns
// false, so the worker skips without ever touching myLocation.
func TestRunSelfLocateSkipsWhenEstimateNotReady(t *testing.T) {
t.Parallel()
loc := location.New()
locator := selflocate.New()
var slot atomic.Pointer[time.Time]
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
runSelfLocate(ctx, loc, locator, &slot, time.Millisecond, time.Hour)
}()
time.Sleep(tickSettleDelay)
cancel()
<-done
if lat, lon := loc.GetCoordinates(); lat != 0 || lon != 0 {
t.Errorf("location updated from an empty locator: (%v, %v)", lat, lon)
}
}
// TestRunSelfLocateDedupsRepeatEstimate covers the dedup branch: once a
// fix is applied, a subsequent identical estimate is skipped rather than
// re-written into myLocation. The fixture yields a deterministic estimate,
// so every tick after the first repeats it. feedSelfLocateFixture is the
// shared seeder from the self-locate wiring tests.
func TestRunSelfLocateDedupsRepeatEstimate(t *testing.T) {
t.Parallel()
loc := location.New()
locator := selflocate.New()
feedSelfLocateFixture(locator)
var slot atomic.Pointer[time.Time]
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
defer close(done)
runSelfLocate(ctx, loc, locator, &slot, time.Millisecond, time.Hour)
}()
deadline := time.Now().Add(workerDeadline)
for {
if lat, lon := loc.GetCoordinates(); lat != 0 || lon != 0 {
break
}
if time.Now().After(deadline) {
cancel()
<-done
t.Fatal("no fix applied before deadline")
}
time.Sleep(time.Millisecond)
}
firstLat, firstLon := loc.GetCoordinates()
// Let several more ticks fire so the repeated identical estimate
// exercises the dedup skip, then stop.
time.Sleep(tickSettleDelay)
cancel()
<-done
if lat, lon := loc.GetCoordinates(); lat != firstLat || lon != firstLon {
t.Errorf("dedup failed: coords changed from (%v, %v) to (%v, %v)", firstLat, firstLon, lat, lon)
}
}
// TestRunUIUpdateLoopReturnsOnCancel covers the context-done branch: a
// pre-cancelled context ends the loop without tearing anything down.
func TestRunUIUpdateLoopReturnsOnCancel(t *testing.T) {
t.Parallel()
uic := newCancelledUIC(t, cliConfig{})
done := make(chan struct{})
go func() {
runUIUpdateLoop(uic, time.Millisecond)
close(done)
}()
select {
case <-done:
case <-time.After(workerDeadline):
t.Fatal("runUIUpdateLoop did not return on a cancelled context")
}
}
// TestRunUIUpdateLoopTearsDownOnError covers the errChan branch: an error
// on the shared channel makes the loop cancel the context, stop the app,
// and return.
func TestRunUIUpdateLoopTearsDownOnError(t *testing.T) {
t.Parallel()
uic := configureUI(cliConfig{})
t.Cleanup(uic.cancel)
uic.errChan <- errInjectedLoop
done := make(chan struct{})
go func() {
runUIUpdateLoop(uic, uiUpdateInterval)
close(done)
}()
select {
case <-done:
case <-time.After(workerDeadline):
t.Fatal("runUIUpdateLoop did not return after an errChan failure")
}
if uic.ctx.Err() == nil {
t.Error("errChan teardown did not cancel the context")
}
}
// TestRunUIUpdateLoopRunsTickPath covers the ticker branch: with a live
// context, a running simulation-screen app, and a millisecond cadence, a
// tick fires and hands off to tickUI before the context is cancelled.
func TestRunUIUpdateLoopRunsTickPath(t *testing.T) {
t.Parallel()
uic := newRenderableUIC(t)
screen := tcell.NewSimulationScreen("UTF-8")
if err := screen.Init(); err != nil {
t.Fatalf("screen.Init: %v", err)
}
uic.app.SetScreen(screen).SetRoot(uic.grid, true)
appDone := make(chan struct{})
go func() {
_ = uic.app.Run()
close(appDone)
}()
loopDone := make(chan struct{})
go func() {
runUIUpdateLoop(uic, time.Millisecond)
close(loopDone)
}()
// Let several ticks fire so the ticker.C -> tickUI path runs, then
// cancel to unwind the loop.
time.Sleep(tickSettleDelay)
uic.cancel()
select {
case <-loopDone:
case <-time.After(workerDeadline):
t.Fatal("runUIUpdateLoop did not return after cancellation")
}
uic.app.Stop()
select {
case <-appDone:
case <-time.After(workerDeadline):
t.Fatal("app.Run did not return after Stop")
}
}
// TestRunUIUpdateLoopRecoversTickPanic covers the deferred recover: a nil
// ADSB stream makes tickUI panic on the first tick (Sweeping dereferences
// the nil receiver). The recover must cancel the context, stop the app,
// and let the goroutine exit rather than aborting the process.
func TestRunUIUpdateLoopRecoversTickPanic(t *testing.T) {
t.Parallel()
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
uic := &uiComponents{
ctx: ctx,
cancel: cancel,
app: tview.NewApplication(),
errChan: make(chan error, 1),
}
done := make(chan struct{})
go func() {
runUIUpdateLoop(uic, time.Millisecond)
close(done)
}()
select {
case <-done:
case <-time.After(workerDeadline):
t.Fatal("runUIUpdateLoop did not recover the tick panic and return")
}
if ctx.Err() == nil {
t.Error("panic recovery did not cancel the context")
}
}