~gioverse/chat

ref: ff42a2f8b59287707042461aa1ca1347fb8250eb chat/list/manager_test.go -rw-r--r-- 15.9 KiB
ff42a2f8Chris Waldon list: update Loader to return if more elements 8 months ago
                                                                                
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
package list

import (
	"image"
	"runtime"
	"strconv"
	"testing"
	"time"

	"gioui.org/io/system"
	"gioui.org/layout"
	"gioui.org/op"
	"gioui.org/unit"
)

type actuallyStatefulElement struct {
	serial string
}

func (a actuallyStatefulElement) Serial() Serial {
	return Serial(a.serial)
}

func mkStateUpdate(elements []Element, synth Synthesizer) stateUpdate {
	var su stateUpdate
	su.Synthesis = Synthesize(elements, synth)
	return su
}

func TestManager(t *testing.T) {
	// create a fake rendering context
	var ops op.Ops
	gtx := layout.NewContext(&ops, system.FrameEvent{
		Now: time.Now(),
		Metric: unit.Metric{
			PxPerDp: 1,
			PxPerSp: 1,
		},
		Size: image.Pt(1000, 1000),
	})
	var list layout.List

	allocationCounter := 0
	presenterCounter := 0

	synth := func(a, b, c Element) []Element { return []Element{b} }

	m := NewManager(6, Hooks{
		Allocator: func(e Element) interface{} {
			allocationCounter++
			switch e.(type) {
			case actuallyStatefulElement:
				// Just allocate something, doesn't matter what.
				return actuallyStatefulElement{}
			}
			return nil
		},
		Presenter: func(e Element, state interface{}) layout.Widget {
			presenterCounter++
			switch e.(type) {
			case actuallyStatefulElement:
				// Trigger a panic if the wrong state type was provided.
				_ = state.(actuallyStatefulElement)
			}
			return layout.Spacer{
				Width:  unit.Dp(5),
				Height: unit.Dp(5),
			}.Layout
		},
		Loader: func(dir Direction, relativeTo Serial) ([]Element, bool) {
			return nil, false
		},
		Invalidator: func() {},
		Comparator:  func(a, b Element) bool { return true },
		Synthesizer: synth,
	})
	// Shut down the existing background processing for this manager.
	close(m.requests)

	// Replace the background processing channels with channels we can control
	// from within the test.
	requests := make(chan interface{}, 1)
	updates := make(chan stateUpdate, 1)
	m.requests = requests
	m.stateUpdates = updates

	var persistentElements []Element

	type testcase struct {
		name                  string
		expectingRequest      bool
		expectedRequest       loadRequest
		sendUpdate            bool
		update                stateUpdate
		expectedAllocations   int
		expectedPresentations int
		stateSize             int
	}
	for _, tc := range []testcase{
		{
			name:       "load initial elements",
			sendUpdate: true,
			update: func() stateUpdate {
				// Send an update to provide a few elements to work with.
				persistentElements = testElements[0:3]
				return mkStateUpdate(persistentElements, synth)
			}(),
			expectedAllocations:   3,
			expectedPresentations: 3,
			expectingRequest:      true,
			expectedRequest: loadRequest{
				Direction: Before,
			},
			stateSize: 3,
		},
		{
			name:       "load stateless elements (shouldn't allocate, should present)",
			sendUpdate: true,
			update: func() stateUpdate {
				// Send an update to provide a few elements to work with.
				persistentElements = append(persistentElements,
					testElement{
						synthCount: 1,
						serial:     string(NoSerial),
					},
					testElement{
						synthCount: 1,
						serial:     string(NoSerial),
					})
				return mkStateUpdate(persistentElements, synth)
			}(),
			expectedAllocations:   0,
			expectedPresentations: 5,
			expectingRequest:      true,
			expectedRequest: loadRequest{
				Direction: Before,
			},
			stateSize: 3,
		},
		{
			name:       "load a truly stateful element",
			sendUpdate: true,
			update: func() stateUpdate {
				// Send an update to provide a few elements to work with.
				persistentElements = append(persistentElements, actuallyStatefulElement{
					serial: "serial",
				})
				return mkStateUpdate(persistentElements, synth)
			}(),
			expectedAllocations:   1,
			expectedPresentations: 6,
			expectingRequest:      true,
			expectedRequest: loadRequest{
				Direction: Before,
			},
			stateSize: 4,
		},
		{
			name:       "compact the stateful element",
			sendUpdate: true,
			update: func() stateUpdate {
				// Send an update to provide a few elements to work with.
				persistentElements = persistentElements[:len(persistentElements)-1]
				su := mkStateUpdate(persistentElements, synth)
				su.CompactedSerials = []Serial{"serial"}
				return su
			}(),
			expectedAllocations:   0,
			expectedPresentations: 5,
			expectingRequest:      true,
			expectedRequest: loadRequest{
				Direction: Before,
			},
			stateSize: 3,
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			// Send a state update if configured.
			if tc.sendUpdate {
				updates <- tc.update
			}

			// Lay out the managed list.
			list.Layout(gtx, m.UpdatedLen(&list), m.Layout)

			// Ensure the hooks were invoked the expected number of times.
			if allocationCounter != tc.expectedAllocations {
				t.Errorf("expected allocator to be called %d times, was called %d", tc.expectedAllocations, allocationCounter)
			}
			if presenterCounter != tc.expectedPresentations {
				t.Errorf("expected presenter to be called %d times, was called %d", tc.expectedPresentations, presenterCounter)
			}
			presenterCounter = 0
			allocationCounter = 0

			// Check the loadRequest, if any.
			var request loadRequest
			select {
			case req := <-requests:
				request = req.(loadRequest)
				if !tc.expectingRequest {
					t.Errorf("did not expect load request %v", request)
				} else if tc.expectedRequest.Direction != request.Direction {
					t.Errorf("expected loadRequest %v, got %v", tc.expectedRequest, request)
				}
			default:
			}
			if tc.stateSize != len(m.elementState) {
				t.Errorf("expected %d states allocated, got %d", tc.stateSize, len(m.elementState))
			}
		})
	}
}

// TestManagerPreftch tests that load requests are only issued when the index
// falls into the prefetch zones, and that any requests are for the proper
// direction.
func TestManagerPrefetch(t *testing.T) {
	for _, tc := range []struct {
		// name of test case.
		name string
		// prefetch percentage.
		prefetch float32
		// elements to allocate in the list.
		elements int
		// index to scroll to.
		index int
		// expcted request, nil if we are not expecting anything.
		expect *loadRequest
	}{
		{
			name:     "index outside prefetch zone: no prefetch",
			prefetch: 0.2,
			elements: 10,
			index:    5,
			expect:   nil,
		},
		{
			name:     "index on prefetch boundary: no prefetch",
			prefetch: 0.2,
			elements: 10,
			index:    2,
			expect:   nil,
		},
		{
			name:     "index on prefetch boundary: no prefetch",
			prefetch: 0.2,
			elements: 10,
			index:    7,
			expect:   nil,
		},
		{
			name:     "index inside 'before' zone: prefetch before",
			prefetch: 0.2,
			elements: 10,
			index:    1,
			expect:   &loadRequest{Direction: Before},
		},
		{
			name:     "index inside 'before' zone: prefetch before",
			prefetch: 0.2,
			elements: 10,
			index:    0,
			expect:   &loadRequest{Direction: Before},
		},
		{
			name:     "index inside 'after' zone: prefetch after",
			prefetch: 0.2,
			elements: 10,
			index:    8,
			expect:   &loadRequest{Direction: After},
		},
		{
			name:     "index inside 'after' zone: prefetch after",
			prefetch: 0.2,
			elements: 10,
			index:    9,
			expect:   &loadRequest{Direction: After},
		},
		{
			name:     "index greater than bounds: load after",
			prefetch: 0.2,
			elements: 10,
			index:    10, // zero-index means the last index would be '9'
			expect:   &loadRequest{Direction: After},
		},
		{
			name:     "index less than bounds: load before",
			prefetch: 0.2,
			elements: 10,
			index:    -1,
			expect:   &loadRequest{Direction: Before},
		},
		{
			name:     "zeroed prefetch should default",
			prefetch: 0.0,
			elements: 10,
			index:    1,
			expect:   &loadRequest{Direction: Before},
		},
		{
			name:     "too few elements: load after",
			prefetch: 0.15,
			elements: 2,
			index:    1, // indexf 0.5
			expect:   &loadRequest{Direction: After},
		},
		{
			name:     "too few elements: load after",
			prefetch: 0.15,
			elements: 6,
			index:    3, // indexf 0.6
			expect:   &loadRequest{Direction: After},
		},
		{
			name:     "just enough elements: no load",
			prefetch: 0.15,
			elements: 7,
			index:    3, // indexf 0.6
			expect:   nil,
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			var (
				ops op.Ops
				gtx = layout.NewContext(&ops, system.FrameEvent{
					Now: time.Now(),
					Metric: unit.Metric{
						PxPerDp: 1,
						PxPerSp: 1,
					},
					Size: image.Pt(1, 1),
				})
				list         layout.List
				requests     = make(chan interface{}, 1)
				stateUpdates = make(chan stateUpdate, 1)
				viewports    = make(chan viewport, 1)
			)

			// Manually allocate list manager.
			// Constructor doesn't help with testing.
			m := Manager{
				Prefetch:     tc.prefetch,
				presenter:    testHooks.Presenter,
				allocator:    testHooks.Allocator,
				requests:     requests,
				stateUpdates: stateUpdates,
				elementState: make(map[Serial]interface{}),
				elements: func() Synthesis {
					elements := make([]Element, tc.elements)
					for ii := 0; ii < tc.elements; ii++ {
						elements[ii] = &actuallyStatefulElement{
							serial: strconv.Itoa(ii),
						}
					}
					return Synthesize(elements, func(_, x, _ Element) []Element {
						return []Element{x}
					})
				}(),
				viewports: viewports,
			}

			// Set the index position to render the list at.
			list.Position = layout.Position{
				BeforeEnd: true,
				First:     tc.index,
				Count:     1,
			}

			// Lay out the managed list.
			list.Layout(gtx, m.UpdatedLen(&list), m.Layout)

			select {
			case req := <-requests:
				request := req.(loadRequest)
				if tc.expect == nil {
					t.Errorf("did not expect load request %v", request)
				}
				if tc.expect != nil && tc.expect.Direction != request.Direction {
					t.Errorf("got %v, want %v", request, tc.expect)
				}
			default:
			}
		})
	}
}

// dupSlice returns a slice composed of the same elements in the same order,
// but backed by a different array.
func dupSlice(in []Element) []Element {
	out := make([]Element, len(in))
	for i := range in {
		out[i] = in[i]
	}
	return out
}

func TestManagerViewportOnRemoval(t *testing.T) {
	// create a fake rendering context
	var ops op.Ops
	gtx := layout.NewContext(&ops, system.FrameEvent{
		Now: time.Now(),
		Metric: unit.Metric{
			PxPerDp: 1,
			PxPerSp: 1,
		},
		// Make the viewport small enough that only a few list elements
		// fit on screen at a time.
		Size: image.Pt(10, 10),
	})
	var list layout.List
	synth := func(a, b, c Element) []Element { return []Element{b} }

	m := NewManager(6, Hooks{
		Allocator: func(e Element) interface{} { return nil },
		Presenter: func(e Element, state interface{}) layout.Widget {
			return layout.Spacer{
				Width:  unit.Dp(5),
				Height: unit.Dp(5),
			}.Layout
		},
		Loader:      func(dir Direction, relativeTo Serial) ([]Element, bool) { return nil, false },
		Invalidator: func() {},
		Comparator:  func(a, b Element) bool { return true },
		Synthesizer: synth,
	})
	// Shut down the existing background processing for this manager.
	close(m.requests)

	// Replace the background processing channels with channels we can control
	// from within the test.
	updates := make(chan stateUpdate, 1)
	m.requests = nil
	m.stateUpdates = updates

	var persistentElements []Element

	type testcase struct {
		name                           string
		sendUpdate                     bool
		update                         stateUpdate
		startFirstIndex, endFirstIndex int
	}
	for _, tc := range []testcase{
		{
			name:       "load inital elements",
			sendUpdate: true,
			update: func() stateUpdate {
				// Send an update to provide a few elements to work with.
				return mkStateUpdate(dupSlice(testElements), synth)
			}(),
			startFirstIndex: 0,
			endFirstIndex:   0,
		},
		{
			name:       "remove first visible element",
			sendUpdate: true,
			update: func() stateUpdate {
				persistentElements = dupSlice(append(testElements[0:2], testElements[3:]...))
				return mkStateUpdate(persistentElements, synth)
			}(),
			startFirstIndex: 2,
			endFirstIndex:   1,
		},
		{
			name:       "replace all elements, inserting many non-serial elements",
			sendUpdate: true,
			update: func() stateUpdate {
				persistentElements = dupSlice([]Element{
					testElement{
						serial:     string(NoSerial),
						synthCount: 1,
					},
					testElement{
						serial:     string(NoSerial),
						synthCount: 1,
					},
					testElements[len(testElements)-1],
					testElement{
						serial:     string(NoSerial),
						synthCount: 1,
					},
					testElement{
						serial:     string(NoSerial),
						synthCount: 1,
					},
				})
				return mkStateUpdate(persistentElements, synth)
			}(),
			startFirstIndex: 0,
			endFirstIndex:   0,
		},
		{
			name:       "remove the one stateful element",
			sendUpdate: true,
			update: func() stateUpdate {
				persistentElements = dupSlice([]Element{
					testElement{
						serial:     string(NoSerial),
						synthCount: 1,
					},
					testElement{
						serial:     string(NoSerial),
						synthCount: 1,
					},
					testElement{
						serial:     string(NoSerial),
						synthCount: 1,
					},
					testElement{
						serial:     string(NoSerial),
						synthCount: 1,
					},
				})
				return mkStateUpdate(persistentElements, synth)
			}(),
			startFirstIndex: 2,
			endFirstIndex:   0,
		},
	} {
		t.Run(tc.name, func(t *testing.T) {
			// Send a state update if configured.
			if tc.sendUpdate {
				updates <- tc.update
			}

			// Lay out the managed list.
			list.Position.First = tc.startFirstIndex
			list.Layout(gtx, m.UpdatedLen(&list), m.Layout)

			// Ensure that the viewport is in the right place afterward.
			if list.Position.First != tc.endFirstIndex {
				t.Errorf("Expected list.Position.First to be %d after layout, got %d",
					tc.endFirstIndex, list.Position.First)
			}
		})
	}
}

// testHooks allocates default hooks for testing.
var testHooks = Hooks{
	Allocator: func(e Element) interface{} {
		switch e.(type) {
		case actuallyStatefulElement:
			// Just allocate something, doesn't matter what.
			return actuallyStatefulElement{}
		}
		return nil
	},
	Presenter: func(e Element, state interface{}) layout.Widget {
		switch e.(type) {
		case actuallyStatefulElement:
			// Trigger a panic if the wrong state type was provided.
			_ = state.(actuallyStatefulElement)
		}
		return layout.Spacer{
			Width:  unit.Dp(5),
			Height: unit.Dp(5),
		}.Layout
	},
	Loader: func(dir Direction, relativeTo Serial) ([]Element, bool) {
		return nil, false
	},
	Invalidator: func() {},
	Comparator:  func(a, b Element) bool { return true },
	Synthesizer: func(a, b, c Element) []Element { return nil },
}

// TestManagerGC ensures that the Manager cleans up its async goroutine
// when it is garbage collected.
func TestManagerGC(t *testing.T) {
	targetGoroutine := "git.sr.ht/~gioverse/chat/list.asyncProcess.func1"

	if goroutineRunning(targetGoroutine) {
		t.Skip("Another list manager is executing concurrently, cannot test cleanup.")
	}

	mgr := NewManager(10, DefaultHooks(nil, nil))
	_ = mgr // Pretend to use the variable so that it isn't "unused"
	timeout := time.NewTicker(time.Second)

	for !goroutineRunning(targetGoroutine) {
		select {
		case <-timeout.C:
			t.Fatalf("timed out waiting for async goroutine to launch")
			return
		default:
		}
		time.Sleep(time.Millisecond)
	}
	mgr = nil
	// Garbage collect twice, once to run the finalizer and once to
	// actually destroy the manager.
	runtime.GC()
	runtime.GC()
	if goroutineRunning(targetGoroutine) {
		t.Errorf("Destroying a list manager did not clean up background goroutine.")
	}
}

// goroutineRunning returns whether a goroutine is currently executing
// within the provided function name. It only checks the first 100
// goroutines, and it does not differentiate between a goroutine
// currently executing the target function and a goroutine that
// is in a deeper function with the target higher in the call
// stack.
func goroutineRunning(name string) bool {
	var grs [100]runtime.StackRecord
	n, _ := runtime.GoroutineProfile(grs[:])
	active := grs[:n]
	for _, gr := range active {
		frames := runtime.CallersFrames(gr.Stack())
	frameLoop:
		for {
			frame, more := frames.Next()
			if frame.Func.Name() == name {
				return true
			}
			if !more {
				break frameLoop
			}
		}
	}
	return false
}