Repository navigation
Expand file tree
/
Copy pathconfig_test.go
More file actions
332 lines (293 loc) · 10.2 KB
/
Copy pathconfig_test.go
File metadata and controls
332 lines (293 loc) · 10.2 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
package posthog
import (
"fmt"
"strings"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestConfigZeroValue(t *testing.T) {
c := Config{}
if err := c.Validate(); err != nil {
t.Error("validating the zero-value configuration failed:", err)
}
}
func TestConfigValidateTrimsWhitespaceSensitiveFields(t *testing.T) {
c := Config{
Endpoint: " \nhttps://app.posthog.com\t ",
PersonalApiKey: " \ttest-personal-key\n ",
}
require.NoError(t, c.Validate())
require.Equal(t, "https://app.posthog.com", c.Endpoint)
require.Equal(t, "test-personal-key", c.PersonalApiKey)
}
func TestConfigEffectiveSecretKey(t *testing.T) {
for _, tc := range []struct {
name string
config Config
want string
}{
{"neither", Config{}, ""},
{"personal only", Config{PersonalApiKey: "phx_personal"}, "phx_personal"},
{"secret only", Config{SecretKey: "phs_secret"}, "phs_secret"},
{"secret precedence", Config{SecretKey: "phs_secret", PersonalApiKey: "phx_personal"}, "phs_secret"},
} {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.want, tc.config.effectiveSecretKey())
})
}
}
func TestConfigValidateTrimsSecretKey(t *testing.T) {
c := Config{SecretKey: " \tphs_secret\n "}
require.NoError(t, c.Validate())
require.Equal(t, "phs_secret", c.SecretKey)
}
func TestMakeConfigDefaultsWhitespaceEndpoint(t *testing.T) {
got := makeConfig(Config{Endpoint: " \n\t "})
require.Equal(t, DefaultEndpoint, got.Endpoint)
}
func TestConfigInvalidInterval(t *testing.T) {
c := Config{
Interval: -1 * time.Second,
}
if err := c.Validate(); err == nil {
t.Error("no error returned when validating a malformed config")
} else if e, ok := err.(ConfigError); !ok {
t.Error("invalid error returned when checking a malformed config:", err)
} else if e.Field != "Interval" || e.Value.(time.Duration) != (-1*time.Second) {
t.Error("invalid field error reported:", e)
}
}
func TestConfig_MaxRetries(t *testing.T) {
c := Config{}
require.NoError(t, c.Validate())
got := makeConfig(c)
require.Equal(t, DefaultMaxAttempts, got.maxAttempts)
c.MaxRetries = Ptr[int](-1)
require.ErrorContains(t, c.Validate(),
"posthog.NewWithConfig: max retries out of range [0,9] (posthog.Config.MaxRetries: -1)")
got = makeConfig(c)
require.Equal(t, DefaultMaxAttempts, got.maxAttempts)
c.MaxRetries = Ptr[int](10)
require.ErrorContains(t, c.Validate(),
"posthog.NewWithConfig: max retries out of range [0,9] (posthog.Config.MaxRetries: 10)")
got = makeConfig(c)
require.Equal(t, DefaultMaxAttempts, got.maxAttempts)
c.MaxRetries = Ptr[int](5)
require.NoError(t, c.Validate())
got = makeConfig(c)
require.Equal(t, 6, got.maxAttempts)
}
func TestConfigInvalidBatchSize(t *testing.T) {
c := Config{
BatchSize: -1,
}
if err := c.Validate(); err == nil {
t.Error("no error returned when validating a malformed config")
} else if e, ok := err.(ConfigError); !ok {
t.Error("invalid error returned when checking a malformed config:", err)
} else if e.Field != "BatchSize" || e.Value.(int) != -1 {
t.Error("invalid field error reported:", e)
}
}
func TestMakeConfigBatchSizeDefault(t *testing.T) {
require.Equal(t, 100, DefaultBatchSize, "backend SDKs share a BatchSize default of 100")
require.Equal(t, DefaultBatchSize, makeConfig(Config{}).BatchSize)
}
func TestMakeConfigMaxQueueSize(t *testing.T) {
for _, tc := range []struct {
name string
batchSize int
maxQueueSize int
want int
}{
{"defaults", 0, 0, DefaultMaxQueueSize},
{"explicit override honored", 1, 42, 42},
{"clamped up to explicit BatchSize", 500, 10, 500},
{"clamped up to BatchSize larger than default", 20000, 0, 20000},
{"equal to BatchSize is left untouched", 100, 100, 100},
} {
t.Run(tc.name, func(t *testing.T) {
got := makeConfig(Config{BatchSize: tc.batchSize, MaxQueueSize: tc.maxQueueSize})
require.Equal(t, tc.want, got.MaxQueueSize)
require.GreaterOrEqual(t, got.MaxQueueSize, got.BatchSize,
"the queue must always hold at least one full batch")
})
}
}
func TestConfigInvalidMaxQueueSize(t *testing.T) {
c := Config{MaxQueueSize: -1}
err := c.Validate()
require.Error(t, err)
e, ok := err.(ConfigError)
require.True(t, ok, "expected a ConfigError, got %T", err)
require.Equal(t, "MaxQueueSize", e.Field)
require.Equal(t, -1, e.Value.(int))
}
func TestConfigBoolDefaults(t *testing.T) {
tests := []struct {
name string
set func(*Config, *bool)
get func(Config) bool
}{
{"DisableGeoIP", func(c *Config, value *bool) { c.DisableGeoIP = value }, func(c Config) bool { return c.GetDisableGeoIP() }},
{"IsServer", func(c *Config, value *bool) { c.IsServer = value }, func(c Config) bool { return c.GetIsServer() }},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
assertConfigBoolDefaultTrue(t, tt.set, tt.get)
})
}
}
func assertConfigBoolDefaultTrue(t *testing.T, set func(*Config, *bool), get func(Config) bool) {
t.Helper()
var c Config
tv := true
fv := false
require.True(t, get(c))
set(&c, &tv)
require.True(t, get(c))
set(&c, &fv)
require.False(t, get(c))
}
func TestConfigCompression(t *testing.T) {
// Every codec the capture endpoint decodes is valid; unknown values are
// rejected.
cases := []struct {
name string
compression CompressionMode
wantErr string // reason substring; "" means valid
wantValue CompressionMode
}{
{"none", CompressionNone, "", 0},
{"gzip", CompressionGzip, "", 0},
{"zstd", CompressionZstd, "", 0},
{"deflate", CompressionDeflate, "", 0},
{"brotli", CompressionBrotli, "", 0},
{"unknown", CompressionMode(255), "invalid compression mode", CompressionMode(255)},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c := Config{Compression: tc.compression}
err := c.Validate()
if tc.wantErr == "" {
require.NoError(t, err)
return
}
require.Error(t, err)
configErr, ok := err.(ConfigError)
require.True(t, ok, "expected ConfigError")
require.Equal(t, "Compression", configErr.Field)
require.Equal(t, tc.wantValue, configErr.Value)
require.Contains(t, configErr.Reason, tc.wantErr)
})
}
}
func TestConfigByteLimitDefaults(t *testing.T) {
c := makeConfig(Config{})
require.Zero(t, c.MaxEventBytes, "no per-event cap by default")
require.Equal(t, DefaultMaxBatchBytes, c.MaxBatchBytes)
// Explicit values survive; the defaults only fill a zero. Batch stays >=
// event so this models a config Validate accepts.
custom := makeConfig(Config{MaxEventBytes: 5 << 20, MaxBatchBytes: 8 << 20})
require.Equal(t, 5<<20, custom.MaxEventBytes)
require.Equal(t, 8<<20, custom.MaxBatchBytes)
}
// TestConfigRejectsBatchBytesBelowEventBytes pins the invariant that makes the
// MaxBatchBytes doc comment true: an event that passes the per-event check must
// always fit in one request. Without it an event sized between the two limits
// is accepted, finds an empty batch, and is sent alone in a request larger than
// MaxBatchBytes -- which a proxy or the endpoint answers with a terminal 413.
func TestConfigRejectsBatchBytesBelowEventBytes(t *testing.T) {
cases := []struct {
name string
eventB int
batchB int
wantErr bool
wantValue int
}{
// Without a per-event cap, a lowered batch target is valid: a larger event ships alone.
{"batch_lowered_no_event_cap", 0, 1000, false, 0},
// The mirror: only MaxEventBytes is raised, above the default request cap.
{"event_raised_batch_defaulted", DefaultMaxBatchBytes + 1, 0, true, DefaultMaxBatchBytes},
{"both_explicit_batch_smaller", 8 << 20, 5 << 20, true, 5 << 20},
{"both_defaulted", 0, 0, false, 0},
{"equal", 2000, 2000, false, 0},
{"batch_larger", 2000, 4000, false, 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cfg := Config{MaxEventBytes: tc.eventB, MaxBatchBytes: tc.batchB}
err := cfg.Validate()
if !tc.wantErr {
require.NoError(t, err)
return
}
require.Error(t, err)
configErr, ok := err.(ConfigError)
require.True(t, ok, "expected ConfigError")
require.Equal(t, "MaxBatchBytes", configErr.Field)
// Reports the effective value, so a defaulted field is actionable
// rather than being shown as 0.
require.Equal(t, tc.wantValue, configErr.Value)
require.Contains(t, configErr.Reason, "single event fits in one request")
})
}
}
func TestConfigMaxEventBytesRejectsOversizedEvent(t *testing.T) {
var failures []error
var mu sync.Mutex
server := captureOKTestServer(t)
defer server.Close()
client, err := NewWithConfig("phc_test", Config{
Endpoint: server.URL,
BatchSize: 1,
MaxEventBytes: 2000,
Callback: testCallback{
nil,
func(_ APIMessage, e error) { mu.Lock(); failures = append(failures, e); mu.Unlock() },
},
})
require.NoError(t, err)
big := NewProperties()
for i := 0; i < 200; i++ {
big.Set(fmt.Sprintf("k%03d", i), strings.Repeat("v", 50))
}
require.NoError(t, client.Enqueue(Capture{DistinctId: "d", Event: "too-big", Properties: big}))
require.NoError(t, client.Enqueue(Capture{DistinctId: "d", Event: "small"}))
require.NoError(t, client.Close())
mu.Lock()
defer mu.Unlock()
require.Len(t, failures, 1, "only the oversized event should fail")
require.ErrorIs(t, failures[0], ErrMessageTooBig)
}
// TestConfigRejectsNegativeKnobs pins that only zero selects a default. A
// negative value is a caller mistake and used to be silently swallowed.
func TestConfigRejectsNegativeKnobs(t *testing.T) {
cases := []struct {
field string
cfg Config
}{
{"MaxEventBytes", Config{MaxEventBytes: -1}},
{"MaxBatchBytes", Config{MaxBatchBytes: -1}},
{"MaxQueueSize", Config{MaxQueueSize: -1}},
{"CaptureAIMaxQueueSize", Config{CaptureAIMaxQueueSize: -1}},
{"MaxRetryBackoff", Config{MaxRetryBackoff: -1}},
{"BatchUploadTimeout", Config{BatchUploadTimeout: -1}},
{"CaptureAIBatchUploadTimeout", Config{CaptureAIBatchUploadTimeout: -1}},
}
for _, tc := range cases {
t.Run(tc.field, func(t *testing.T) {
err := tc.cfg.Validate()
require.Error(t, err)
configErr, ok := err.(ConfigError)
require.True(t, ok, "expected ConfigError")
require.Equal(t, tc.field, configErr.Field)
require.Contains(t, configErr.Reason, "negative")
})
}
// Zero still selects the documented default.
zero := Config{}
require.NoError(t, zero.Validate())
}