fork/gdu

git clone https://git.julia.blue/fork/gdu

ShivamB25feat: stop scanning and keep partial results (#606)99a7f2a

subvolume
7.5 KiB301 linesraw
1package tui
2
3import (
4	"bytes"
5	"os"
6	"sync"
7	"testing"
8	"time"
9
10	"github.com/dundee/gdu/v5/internal/common"
11	"github.com/dundee/gdu/v5/internal/testanalyze"
12	"github.com/dundee/gdu/v5/internal/testapp"
13	"github.com/dundee/gdu/v5/pkg/fs"
14	"github.com/gdamore/tcell/v2"
15	"github.com/rivo/tview"
16	"github.com/stretchr/testify/require"
17)
18
19type cancelRaceApp struct {
20	*testapp.MockedApp
21	updates chan func()
22	mu      sync.Mutex
23	stops   int
24}
25
26func newCancelRaceApp() *cancelRaceApp {
27	return &cancelRaceApp{
28		MockedApp: &testapp.MockedApp{},
29		updates:   make(chan func(), 8),
30	}
31}
32
33func (app *cancelRaceApp) QueueUpdateDraw(update func()) *tview.Application {
34	app.updates <- update
35	return nil
36}
37
38func (app *cancelRaceApp) Stop() {
39	app.mu.Lock()
40	app.stops++
41	app.mu.Unlock()
42}
43
44func (app *cancelRaceApp) stopCount() int {
45	app.mu.Lock()
46	defer app.mu.Unlock()
47	return app.stops
48}
49
50func (app *cancelRaceApp) nextUpdate(t *testing.T) func() {
51	t.Helper()
52	select {
53	case update := <-app.updates:
54		return update
55	case <-time.After(2 * time.Second):
56		t.Fatal("timed out waiting for queued UI update")
57		return nil
58	}
59}
60
61type failOnceSignalScreen struct {
62	tcell.Screen
63	attempted chan struct{}
64	fail      bool
65}
66
67func (screen *failOnceSignalScreen) PostEvent(event tcell.Event) error {
68	if screen.fail {
69		screen.fail = false
70		close(screen.attempted)
71		return tcell.ErrEventQFull
72	}
73	return screen.Screen.PostEvent(event)
74}
75
76type signalLifecycleApp struct {
77	*testapp.MockedApp
78	signalAttempted <-chan struct{}
79}
80
81func (app *signalLifecycleApp) Run() error {
82	<-app.signalAttempted
83	return nil
84}
85
86type cancelRaceAnalyzer struct {
87	*testanalyze.MockedAnalyzer
88	started   chan struct{}
89	release   chan struct{}
90	cancelled chan struct{}
91	done      common.SignalGroup
92	cancelMu  sync.Mutex
93	cancels   int
94	once      sync.Once
95}
96
97func newCancelRaceAnalyzer() *cancelRaceAnalyzer {
98	progressDone := make(common.SignalGroup)
99	progressDone.Broadcast()
100	return &cancelRaceAnalyzer{
101		MockedAnalyzer: &testanalyze.MockedAnalyzer{},
102		started:        make(chan struct{}),
103		release:        make(chan struct{}),
104		cancelled:      make(chan struct{}),
105		done:           progressDone,
106	}
107}
108
109func (a *cancelRaceAnalyzer) AnalyzeDir(
110	path string, ignore common.ShouldDirBeIgnored, fileTypeFilter common.ShouldFileBeIgnored,
111) fs.Item {
112	close(a.started)
113	select {
114	case <-a.cancelled:
115	case <-a.release:
116	}
117	return a.MockedAnalyzer.AnalyzeDir(path, ignore, fileTypeFilter)
118}
119
120func (a *cancelRaceAnalyzer) Cancel() {
121	a.cancelMu.Lock()
122	a.cancels++
123	a.cancelMu.Unlock()
124	a.once.Do(func() { close(a.cancelled) })
125}
126
127func (a *cancelRaceAnalyzer) cancelCount() int {
128	a.cancelMu.Lock()
129	defer a.cancelMu.Unlock()
130	return a.cancels
131}
132
133func (a *cancelRaceAnalyzer) GetDone() common.SignalGroup {
134	return a.done
135}
136
137func newCancelRaceUI(app *cancelRaceApp, analyzer *cancelRaceAnalyzer) *UI {
138	screen := testapp.CreateSimScreen()
139	ui := CreateUI(app, screen, &bytes.Buffer{}, true, true, false, false)
140	ui.Analyzer = analyzer
141	ui.done = make(chan struct{})
142	return ui
143}
144
145func drainScanUpdates(t *testing.T, app *cancelRaceApp, ui *UI) {
146	t.Helper()
147	// One update finalizes progress and one applies the completed scan. The
148	// progress channel is already closed, so the first update is deterministic.
149	first := app.nextUpdate(t)
150	second := app.nextUpdate(t)
151	first()
152	second()
153	require.False(t, ui.scanning)
154	require.False(t, ui.pages.HasPage("progress"))
155}
156
157func TestAnalyzePathImmediateCtrlCIsNotLost(t *testing.T) {
158	app := newCancelRaceApp()
159	analyzer := newCancelRaceAnalyzer()
160	ui := newCancelRaceUI(app, analyzer)
161
162	require.NoError(t, ui.AnalyzePath("test_dir", nil))
163	// Ctrl-C is intentionally delivered immediately, before AnalyzeDir is
164	// guaranteed to have started. Cancel must still be observed by the double.
165	require.Nil(t, ui.keyPressed(tcell.NewEventKey(tcell.KeyCtrlC, 0, 0)))
166	_ = ui.keyPressed(tcell.NewEventKey(tcell.KeyCtrlC, 0, 0))
167
168	select {
169	case <-analyzer.started:
170	case <-time.After(2 * time.Second):
171		t.Fatal("AnalyzeDir did not start")
172	}
173	select {
174	case <-ui.done:
175	case <-time.After(2 * time.Second):
176		t.Fatal("scan did not complete after cancellation")
177	}
178	drainScanUpdates(t, app, ui)
179
180	require.Equal(t, 1, analyzer.cancelCount())
181	require.Equal(t, 0, app.stopCount())
182	require.Equal(t, "test_dir", ui.currentDir.GetName())
183}
184
185func TestCtrlCBeforeQueuedCompletionKeepsResults(t *testing.T) {
186	app := newCancelRaceApp()
187	analyzer := newCancelRaceAnalyzer()
188	ui := newCancelRaceUI(app, analyzer)
189
190	require.NoError(t, ui.AnalyzePath("test_dir", nil))
191	close(analyzer.release)
192	select {
193	case <-ui.done:
194	case <-time.After(2 * time.Second):
195		t.Fatal("scan did not complete")
196	}
197
198	// The completion draw is queued, but has not run yet. Cancellation must
199	// not discard the result or make the completion callback unsafe.
200	require.Nil(t, ui.keyPressed(tcell.NewEventKey(tcell.KeyCtrlC, 0, 0)))
201	drainScanUpdates(t, app, ui)
202
203	require.Equal(t, 1, analyzer.cancelCount())
204	require.Equal(t, "test_dir", ui.currentDir.GetName())
205	require.Equal(t, 4, ui.table.GetRowCount())
206}
207
208func TestRepeatedSignalCtrlCIsIdempotent(t *testing.T) {
209	app := newCancelRaceApp()
210	analyzer := newCancelRaceAnalyzer()
211	ui := newCancelRaceUI(app, analyzer)
212
213	require.NoError(t, ui.AnalyzePath("test_dir", nil))
214	ui.keyPressed(signalEvent(os.Interrupt))
215	ui.keyPressed(signalEvent(os.Interrupt))
216	require.Equal(t, 1, analyzer.cancelCount())
217	require.Equal(t, 0, app.stopCount())
218
219	close(analyzer.release)
220	select {
221	case <-ui.done:
222	case <-time.After(2 * time.Second):
223		t.Fatal("scan did not complete")
224	}
225	drainScanUpdates(t, app, ui)
226
227	// Once the completion callback has marked the scan finished, SIGINT takes
228	// the normal quit path.
229	ui.keyPressed(signalEvent(os.Interrupt))
230	require.Equal(t, 1, app.stopCount())
231}
232
233func TestSignalLoopQueuesScanCancellation(t *testing.T) {
234	app := newCancelRaceApp()
235	analyzer := &testanalyze.MockedAnalyzer{}
236	screen := testapp.CreateSimScreen()
237	require.NoError(t, screen.Init())
238	defer screen.Fini()
239	ui := CreateUI(app, screen, &bytes.Buffer{}, true, true, false, false)
240	ui.Analyzer = analyzer
241	ui.progress = tview.NewTextView()
242	ui.scanning = true
243
244	signals := make(chan os.Signal, 1)
245	signals <- os.Interrupt
246	close(signals)
247	ui.handleSignals(signals, make(chan struct{}))
248
249	event, ok := screen.PollEvent().(*tcell.EventKey)
250	require.True(t, ok)
251	ui.keyPressed(event)
252
253	require.True(t, analyzer.IsCancelled())
254	require.True(t, ui.scanCancelled)
255	require.Equal(t, 0, app.stopCount())
256}
257
258func TestSignalLoopRetriesFullEventQueue(t *testing.T) {
259	app := newCancelRaceApp()
260	analyzer := &testanalyze.MockedAnalyzer{}
261	simScreen := testapp.CreateSimScreen()
262	require.NoError(t, simScreen.Init())
263	defer simScreen.Fini()
264	screen := &failOnceSignalScreen{
265		Screen:    simScreen,
266		attempted: make(chan struct{}),
267		fail:      true,
268	}
269	ui := CreateUI(app, screen, &bytes.Buffer{}, true, true, false, false)
270	ui.Analyzer = analyzer
271	ui.progress = tview.NewTextView()
272	ui.scanning = true
273
274	signals := make(chan os.Signal, 1)
275	signals <- os.Interrupt
276	close(signals)
277	done := make(chan struct{})
278	go func() {
279		defer close(done)
280		ui.handleSignals(signals, make(chan struct{}))
281	}()
282
283	select {
284	case <-screen.attempted:
285	case <-time.After(time.Second):
286		t.Fatal("signal event delivery was not attempted")
287	}
288	select {
289	case <-done:
290	case <-time.After(time.Second):
291		t.Fatal("signal event was not retried")
292	}
293
294	event, ok := simScreen.PollEvent().(*tcell.EventKey)
295	require.True(t, ok)
296	ui.keyPressed(event)
297
298	require.True(t, analyzer.IsCancelled())
299	require.True(t, ui.scanCancelled)
300	require.Equal(t, 0, app.stopCount())
301}