File: group_test.go

package info (click to toggle)
incus 6.0.5-2
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,428 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (51 lines) | stat: -rw-r--r-- 1,031 bytes parent folder | download | duplicates (5)
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
package task_test

import (
	"context"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"

	"github.com/lxc/incus/v6/internal/server/task"
)

func TestGroup_Add(t *testing.T) {
	group := &task.Group{}
	ok := make(chan struct{})
	f := func(context.Context) { close(ok) }
	group.Add(f, task.Every(time.Second))
	group.Start(context.Background())

	assertRecv(t, ok)

	assert.NoError(t, group.Stop(time.Second))
}

func TestGroup_StopUngracefully(t *testing.T) {
	group := &task.Group{}

	// Create a task function that blocks.
	ok := make(chan struct{})
	defer close(ok)
	f := func(context.Context) {
		ok <- struct{}{}
		<-ok
	}

	group.Add(f, task.Every(time.Second))
	group.Start(context.Background())

	assertRecv(t, ok)

	assert.EqualError(t, group.Stop(time.Millisecond), "Task(s) still running: IDs [0]")
}

// Assert that the given channel receives an object within a second.
func assertRecv(t *testing.T, ch chan struct{}) {
	select {
	case <-ch:
	case <-time.After(time.Second):
		t.Fatal("no object received")
	}
}