|
1 | 1 | package icingadb
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "context" |
| 5 | + "github.com/icinga/icinga-go-library/database" |
4 | 6 | "github.com/icinga/icinga-go-library/types"
|
5 | 7 | "github.com/icinga/icingadb/pkg/icingadb/v1"
|
6 | 8 | "github.com/stretchr/testify/require"
|
7 | 9 | "testing"
|
| 10 | + "time" |
8 | 11 | )
|
9 | 12 |
|
10 | 13 | func TestEntitiesById_Keys(t *testing.T) {
|
@@ -70,3 +73,77 @@ func TestEntitiesById_IDs(t *testing.T) {
|
70 | 73 | })
|
71 | 74 | }
|
72 | 75 | }
|
| 76 | + |
| 77 | +func TestEntitiesById_Entities(t *testing.T) { |
| 78 | + subtests := []struct { |
| 79 | + name string |
| 80 | + io EntitiesById |
| 81 | + }{ |
| 82 | + {name: "nil"}, |
| 83 | + { |
| 84 | + name: "empty", |
| 85 | + io: EntitiesById{}, |
| 86 | + }, |
| 87 | + { |
| 88 | + name: "one", |
| 89 | + io: EntitiesById{"one": newEntity([]byte{23})}, |
| 90 | + }, |
| 91 | + { |
| 92 | + name: "two", |
| 93 | + io: EntitiesById{"one": newEntity([]byte{23}), "two": newEntity([]byte{42})}, |
| 94 | + }, |
| 95 | + } |
| 96 | + |
| 97 | + for _, st := range subtests { |
| 98 | + t.Run(st.name, func(t *testing.T) { |
| 99 | + ctx, cancel := context.WithCancel(context.Background()) |
| 100 | + defer cancel() |
| 101 | + |
| 102 | + expected := make([]database.Entity, 0, len(st.io)) |
| 103 | + actual := make([]database.Entity, 0, len(st.io)) |
| 104 | + |
| 105 | + for _, v := range st.io { |
| 106 | + expected = append(expected, v) |
| 107 | + } |
| 108 | + |
| 109 | + ch := st.io.Entities(ctx) |
| 110 | + require.NotNil(t, ch) |
| 111 | + |
| 112 | + for range expected { |
| 113 | + select { |
| 114 | + case v, ok := <-ch: |
| 115 | + require.True(t, ok, "channel closed too early") |
| 116 | + actual = append(actual, v) |
| 117 | + case <-time.After(time.Second): |
| 118 | + require.Fail(t, "channel should not block") |
| 119 | + } |
| 120 | + } |
| 121 | + |
| 122 | + require.ElementsMatch(t, expected, actual) |
| 123 | + |
| 124 | + select { |
| 125 | + case v, ok := <-ch: |
| 126 | + require.False(t, ok, "channel should be closed, got %#v", v) |
| 127 | + case <-time.After(time.Second): |
| 128 | + require.Fail(t, "channel should not block") |
| 129 | + } |
| 130 | + }) |
| 131 | + } |
| 132 | + |
| 133 | + t.Run("closed-ctx", func(t *testing.T) { |
| 134 | + ctx, cancel := context.WithCancel(context.Background()) |
| 135 | + cancel() |
| 136 | + |
| 137 | + ch := EntitiesById{"one": newEntity([]byte{23})}.Entities(ctx) |
| 138 | + require.NotNil(t, ch) |
| 139 | + |
| 140 | + time.Sleep(time.Millisecond) |
| 141 | + |
| 142 | + select { |
| 143 | + case v, ok := <-ch: |
| 144 | + require.False(t, ok, "channel should be closed, got %#v", v) |
| 145 | + case <-time.After(time.Second): |
| 146 | + require.Fail(t, "channel should not block") |
| 147 | + } |
| 148 | + }) |
| 149 | +} |
0 commit comments