-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathFeatureFlagErrorTest.php
More file actions
595 lines (498 loc) · 22.7 KB
/
FeatureFlagErrorTest.php
File metadata and controls
595 lines (498 loc) · 22.7 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
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
<?php
// phpcs:ignoreFile
namespace PostHog\Test;
// comment out below to print all logs instead of failing tests
require_once 'test/error_log_mock.php';
use PHPUnit\Framework\TestCase;
use PostHog\Client;
use PostHog\FeatureFlagError;
use PostHog\PostHog;
use PostHog\Test\Assets\MockedResponses;
class FeatureFlagErrorTest extends TestCase
{
use ClockMockTrait;
public const FAKE_API_KEY = "random_key";
private $http_client;
private $client;
public function setUp($flagsEndpointResponse = MockedResponses::FLAGS_RESPONSE, $personalApiKey = null): void
{
date_default_timezone_set("UTC");
$this->http_client = new MockedHttpClient("app.posthog.com", flagsEndpointResponse: $flagsEndpointResponse);
$this->client = new Client(
self::FAKE_API_KEY,
[
"debug" => true,
],
$this->http_client,
$personalApiKey
);
PostHog::init(null, null, $this->client);
// Reset the errorMessages array before each test
global $errorMessages;
$errorMessages = [];
}
public function testFlagMissingError()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
$this->setUp(MockedResponses::FLAGS_RESPONSE, personalApiKey: null);
// Request a flag that doesn't exist in the response
$result = PostHog::getFeatureFlag('non-existent-flag', 'user-id');
$this->assertNull($result);
PostHog::flush();
// Check that the $feature_flag_called event includes the flag_missing error
$calls = $this->http_client->calls;
$this->assertCount(2, $calls);
// First call is to /flags/
$this->assertStringStartsWith("/flags/", $calls[0]['path']);
// Second call is to /batch/ with the $feature_flag_called event
$this->assertEquals("/batch/", $calls[1]['path']);
$payload = json_decode($calls[1]['payload'], true);
$event = $payload['batch'][0];
$this->assertEquals('$feature_flag_called', $event['event']);
$this->assertEquals('non-existent-flag', $event['properties']['$feature_flag']);
$this->assertNull($event['properties']['$feature_flag_response']);
$this->assertEquals(FeatureFlagError::FLAG_MISSING, $event['properties']['$feature_flag_error']);
});
}
public function testErrorsWhileComputingFlagsError()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
// Create a response with errorsWhileComputingFlags set to true
$responseWithErrors = array_merge(MockedResponses::FLAGS_RESPONSE, [
'errorsWhileComputingFlags' => true
]);
$this->setUp($responseWithErrors, personalApiKey: null);
// Request a flag that exists in the response
$result = PostHog::getFeatureFlag('simple-test', 'user-id');
$this->assertTrue($result);
PostHog::flush();
// Check that the $feature_flag_called event includes the errors_while_computing_flags error
$calls = $this->http_client->calls;
$this->assertCount(2, $calls);
$payload = json_decode($calls[1]['payload'], true);
$event = $payload['batch'][0];
$this->assertEquals('$feature_flag_called', $event['event']);
$this->assertEquals('simple-test', $event['properties']['$feature_flag']);
$this->assertTrue($event['properties']['$feature_flag_response']);
$this->assertEquals(
FeatureFlagError::ERRORS_WHILE_COMPUTING_FLAGS,
$event['properties']['$feature_flag_error']
);
});
}
public function testMultipleErrors()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
// Create a response with errorsWhileComputingFlags set to true
// and request a flag that doesn't exist
$responseWithErrors = array_merge(MockedResponses::FLAGS_RESPONSE, [
'errorsWhileComputingFlags' => true
]);
$this->setUp($responseWithErrors, personalApiKey: null);
// Request a flag that doesn't exist
$result = PostHog::getFeatureFlag('non-existent-flag', 'user-id');
$this->assertNull($result);
PostHog::flush();
// Check that the $feature_flag_called event includes both errors
$calls = $this->http_client->calls;
$this->assertCount(2, $calls);
$payload = json_decode($calls[1]['payload'], true);
$event = $payload['batch'][0];
$this->assertEquals('$feature_flag_called', $event['event']);
$this->assertEquals('non-existent-flag', $event['properties']['$feature_flag']);
$this->assertNull($event['properties']['$feature_flag_response']);
// Errors should be joined with commas
$expectedErrors = FeatureFlagError::ERRORS_WHILE_COMPUTING_FLAGS . ',' . FeatureFlagError::FLAG_MISSING;
$this->assertEquals($expectedErrors, $event['properties']['$feature_flag_error']);
});
}
public function testNoErrorWhenFlagEvaluatesSuccessfully()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
$this->setUp(MockedResponses::FLAGS_RESPONSE, personalApiKey: null);
// Request a flag that exists in the response
$result = PostHog::getFeatureFlag('simple-test', 'user-id');
$this->assertTrue($result);
PostHog::flush();
// Check that the $feature_flag_called event does NOT include an error
$calls = $this->http_client->calls;
$this->assertCount(2, $calls);
$payload = json_decode($calls[1]['payload'], true);
$event = $payload['batch'][0];
$this->assertEquals('$feature_flag_called', $event['event']);
$this->assertEquals('simple-test', $event['properties']['$feature_flag']);
$this->assertTrue($event['properties']['$feature_flag_response']);
// Should not have $feature_flag_error property
$this->assertArrayNotHasKey('$feature_flag_error', $event['properties']);
});
}
public function testUnknownErrorWhenExceptionThrown()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
// Create a mocked client that will throw an exception
$this->http_client = new class ("app.posthog.com") extends MockedHttpClient {
public function sendRequest(
string $path,
?string $payload,
array $extraHeaders = [],
array $requestOptions = []
): \PostHog\HttpResponse {
if (!isset($this->calls)) {
$this->calls = [];
}
array_push($this->calls, array(
"path" => $path,
"payload" => $payload,
"extraHeaders" => $extraHeaders,
"requestOptions" => $requestOptions
));
if (str_starts_with($path, "/flags/")) {
throw new \Exception("Network error");
}
return parent::sendRequest($path, $payload, $extraHeaders, $requestOptions);
}
};
$this->client = new Client(
self::FAKE_API_KEY,
[
"debug" => true,
],
$this->http_client,
null
);
PostHog::init(null, null, $this->client);
// Reset error messages
global $errorMessages;
$errorMessages = [];
// Request a flag - this should trigger an exception
$result = PostHog::getFeatureFlag('simple-test', 'user-id');
$this->assertNull($result);
PostHog::flush();
// Check that the $feature_flag_called event includes the unknown_error
$calls = $this->http_client->calls;
// Find the batch call (there might be multiple calls)
$batchCall = null;
foreach ($calls as $call) {
if ($call['path'] === '/batch/') {
$batchCall = $call;
break;
}
}
$this->assertNotNull($batchCall, "Expected to find a /batch/ call");
$payload = json_decode($batchCall['payload'], true);
$event = $payload['batch'][0];
$this->assertEquals('$feature_flag_called', $event['event']);
$this->assertEquals('simple-test', $event['properties']['$feature_flag']);
$this->assertNull($event['properties']['$feature_flag_response']);
$this->assertEquals(FeatureFlagError::UNKNOWN_ERROR, $event['properties']['$feature_flag_error']);
});
}
public function testApiErrorMethod()
{
// Test the apiError static method
$this->assertEquals('api_error_500', FeatureFlagError::apiError(500));
$this->assertEquals('api_error_404', FeatureFlagError::apiError(404));
$this->assertEquals('api_error_429', FeatureFlagError::apiError(429));
}
public function testTimeoutError()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
// Create a mocked client that simulates a timeout (responseCode=0, curlErrno=28)
$this->http_client = new MockedHttpClient(
"app.posthog.com",
flagsEndpointResponse: MockedResponses::FLAGS_RESPONSE,
flagsEndpointResponseCode: 0,
flagsEndpointCurlErrno: 28 // CURLE_OPERATION_TIMEDOUT
);
$this->client = new Client(
self::FAKE_API_KEY,
["debug" => true],
$this->http_client,
null
);
PostHog::init(null, null, $this->client);
global $errorMessages;
$errorMessages = [];
$result = PostHog::getFeatureFlag('simple-test', 'user-id');
$this->assertNull($result);
PostHog::flush();
$calls = $this->http_client->calls;
$batchCall = null;
foreach ($calls as $call) {
if ($call['path'] === '/batch/') {
$batchCall = $call;
break;
}
}
$this->assertNotNull($batchCall, "Expected to find a /batch/ call");
$payload = json_decode($batchCall['payload'], true);
$event = $payload['batch'][0];
$this->assertEquals('$feature_flag_called', $event['event']);
$this->assertEquals(FeatureFlagError::TIMEOUT, $event['properties']['$feature_flag_error']);
});
}
public function testConnectionError()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
// Create a mocked client that simulates a connection error (responseCode=0, curlErrno=6)
$this->http_client = new MockedHttpClient(
"app.posthog.com",
flagsEndpointResponse: MockedResponses::FLAGS_RESPONSE,
flagsEndpointResponseCode: 0,
flagsEndpointCurlErrno: 6 // CURLE_COULDNT_RESOLVE_HOST
);
$this->client = new Client(
self::FAKE_API_KEY,
["debug" => true],
$this->http_client,
null
);
PostHog::init(null, null, $this->client);
global $errorMessages;
$errorMessages = [];
$result = PostHog::getFeatureFlag('simple-test', 'user-id');
$this->assertNull($result);
PostHog::flush();
$calls = $this->http_client->calls;
$batchCall = null;
foreach ($calls as $call) {
if ($call['path'] === '/batch/') {
$batchCall = $call;
break;
}
}
$this->assertNotNull($batchCall, "Expected to find a /batch/ call");
$payload = json_decode($batchCall['payload'], true);
$event = $payload['batch'][0];
$this->assertEquals('$feature_flag_called', $event['event']);
$this->assertEquals(FeatureFlagError::CONNECTION_ERROR, $event['properties']['$feature_flag_error']);
});
}
public function testApiError500()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
// Create a mocked client that simulates a 500 error
$this->http_client = new MockedHttpClient(
"app.posthog.com",
flagsEndpointResponse: MockedResponses::FLAGS_RESPONSE,
flagsEndpointResponseCode: 500
);
$this->client = new Client(
self::FAKE_API_KEY,
["debug" => true],
$this->http_client,
null
);
PostHog::init(null, null, $this->client);
global $errorMessages;
$errorMessages = [];
$result = PostHog::getFeatureFlag('simple-test', 'user-id');
$this->assertNull($result);
PostHog::flush();
$calls = $this->http_client->calls;
$batchCall = null;
foreach ($calls as $call) {
if ($call['path'] === '/batch/') {
$batchCall = $call;
break;
}
}
$this->assertNotNull($batchCall, "Expected to find a /batch/ call");
$payload = json_decode($batchCall['payload'], true);
$event = $payload['batch'][0];
$this->assertEquals('$feature_flag_called', $event['event']);
$this->assertEquals('api_error_500', $event['properties']['$feature_flag_error']);
});
}
public function testQuotaLimitedError()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
// Create a response with quotaLimited containing feature_flags
$quotaLimitedResponse = array_merge(MockedResponses::FLAGS_RESPONSE, [
'quotaLimited' => ['feature_flags']
]);
$this->http_client = new MockedHttpClient(
"app.posthog.com",
flagsEndpointResponse: $quotaLimitedResponse
);
$this->client = new Client(
self::FAKE_API_KEY,
["debug" => true],
$this->http_client,
null
);
PostHog::init(null, null, $this->client);
global $errorMessages;
$errorMessages = [];
$result = PostHog::getFeatureFlag('simple-test', 'user-id');
$this->assertNull($result);
PostHog::flush();
$calls = $this->http_client->calls;
$batchCall = null;
foreach ($calls as $call) {
if ($call['path'] === '/batch/') {
$batchCall = $call;
break;
}
}
$this->assertNotNull($batchCall, "Expected to find a /batch/ call");
$payload = json_decode($batchCall['payload'], true);
$event = $payload['batch'][0];
$this->assertEquals('$feature_flag_called', $event['event']);
$this->assertEquals(FeatureFlagError::QUOTA_LIMITED, $event['properties']['$feature_flag_error']);
});
}
public function testFailedFlagIsFilteredOutByFailedField()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
// V4 response with three flags:
// - 'failed-flag': failed=true (transient error), should be filtered out
// - 'disabled-flag': enabled=false, failed=false (legitimately disabled), should NOT be filtered
// - 'good-flag': enabled=true, failed=false (successful), should NOT be filtered
$responseWithFailedFlag = [
'flags' => [
'failed-flag' => [
'key' => 'failed-flag',
'enabled' => false,
'variant' => null,
'reason' => [
'code' => 'database_error',
'description' => 'Database connection error during evaluation',
'condition_index' => null,
],
'metadata' => ['id' => 1, 'version' => 1, 'payload' => null],
'failed' => true,
],
'disabled-flag' => [
'key' => 'disabled-flag',
'enabled' => false,
'variant' => null,
'reason' => [
'code' => 'condition_match',
'description' => 'No conditions matched',
'condition_index' => null,
],
'metadata' => ['id' => 2, 'version' => 1, 'payload' => null],
'failed' => false,
],
'good-flag' => [
'key' => 'good-flag',
'enabled' => true,
'variant' => null,
'reason' => [
'code' => 'condition_match',
'description' => 'Matched condition set 1',
'condition_index' => 0,
],
'metadata' => ['id' => 3, 'version' => 1, 'payload' => null],
'failed' => false,
],
],
'errorsWhileComputingFlags' => true,
'requestId' => 'test-request-id',
];
$this->setUp($responseWithFailedFlag, personalApiKey: null);
// The failed flag should be filtered out entirely (null, not false)
$failedResult = PostHog::getFeatureFlag('failed-flag', 'user-id');
$this->assertNull($failedResult);
// A legitimately disabled flag (failed=false) should still return false
$disabledResult = PostHog::getFeatureFlag('disabled-flag', 'user-id');
$this->assertFalse($disabledResult);
// A successfully enabled flag should return its value
$goodResult = PostHog::getFeatureFlag('good-flag', 'user-id');
$this->assertTrue($goodResult);
});
}
public function testGetAllFlagsDoesNotOverwriteLocalResultWithFailedServerFlag()
{
$this->executeAtFrozenDateTime(new \DateTime('2022-05-01'), function () {
// Local flags: simple-flag evaluates locally; ec-flag requires server
// due to experience continuity.
$localFlags = [
'flags' => [
[
"id" => 1,
"name" => "",
"key" => "simple-flag",
"filters" => [
"groups" => [
["properties" => [], "rollout_percentage" => 100]
]
],
"deleted" => false,
"active" => true,
"is_simple_flag" => true,
],
[
"id" => 2,
"name" => "EC Feature",
"key" => "ec-flag",
"filters" => [
"groups" => [
["properties" => [], "rollout_percentage" => 100]
]
],
"ensure_experience_continuity" => true,
"deleted" => false,
"active" => true,
"is_simple_flag" => true,
],
],
];
// Server response (v4): simple-flag failed due to transient error,
// ec-flag evaluated successfully.
$serverResponse = [
'flags' => [
'simple-flag' => [
'key' => 'simple-flag',
'enabled' => false,
'variant' => null,
'reason' => [
'code' => 'database_error',
'description' => 'Database connection error',
'condition_index' => null,
],
'metadata' => ['id' => 1, 'version' => 1, 'payload' => null],
'failed' => true,
],
'ec-flag' => [
'key' => 'ec-flag',
'enabled' => true,
'variant' => null,
'reason' => [
'code' => 'condition_match',
'description' => 'Matched condition set 1',
'condition_index' => 0,
],
'metadata' => ['id' => 2, 'version' => 1, 'payload' => null],
'failed' => false,
],
],
'errorsWhileComputingFlags' => true,
'requestId' => 'test-request-id',
];
$this->http_client = new MockedHttpClient(
host: "app.posthog.com",
flagEndpointResponse: $localFlags,
flagsEndpointResponse: $serverResponse
);
$this->client = new Client(
self::FAKE_API_KEY,
["debug" => true],
$this->http_client,
"test" // personal API key enables local evaluation
);
PostHog::init(null, null, $this->client);
global $errorMessages;
$errorMessages = [];
$flags = PostHog::getAllFlags('distinct-id');
// simple-flag was locally evaluated as true. The server returned it
// as failed (enabled=false, failed=true). The failed server result
// must NOT overwrite the local value via array_merge.
$this->assertTrue($flags['simple-flag']);
// ec-flag could not be evaluated locally (experience continuity),
// so the successful server result should be used.
$this->assertTrue($flags['ec-flag']);
});
}
}