Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
173 changes: 173 additions & 0 deletions test/EventSnapshotsTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
<?php

namespace PostHog\Test;

use PostHog\Client;
use PostHog\PostHog;
use Symfony\Component\Clock\Clock;
use Symfony\Component\Clock\MockClock;
use Symfony\Component\Clock\NativeClock;

class EventSnapshotsTest extends JsonSnapshotTestCase
{
private const API_KEY = 'phc_snapshot_project_key';

private MockedHttpClient $httpClient;
private Client $client;

protected function setUp(): void
{
date_default_timezone_set('UTC');
Clock::set(new MockClock(new \DateTimeImmutable('2024-01-02T03:04:05.123456+00:00')));
$this->httpClient = new MockedHttpClient('snapshot.posthog.test');
$this->client = new Client(
self::API_KEY,
[
'batch_size' => 100,
'debug' => true,
],
$this->httpClient,
null,
false
);
PostHog::init(null, null, $this->client);
}

protected function tearDown(): void
{
$this->client->shutdown();
Clock::set(new NativeClock());
}

public function testEventFamilyBatchRequestMatchesSnapshot(): void
{
self::assertTrue($this->client->capture([
'distinctId' => 'person-123',
'event' => 'checkout completed',
'groups' => [
'organization' => 'org-42',
'project' => 'project-7',
],
'properties' => [
'boolean_false' => false,
'boolean_true' => true,
'empty_list' => [],
'empty_object' => (object) [],
'empty_string' => '',
'float' => 42.5,
'floating_zero' => 0.0,
'integer' => 42,
'large_integer' => 9007199254740991,
'negative_floating_zero' => -0.0,
'negative_integer' => -42,
'list_order' => ['third', 'first', 'second'],
'nested_object' => [
'zeta' => null,
'alpha' => 'first',
],
'null' => null,
'numeric_string' => '0',
'text' => "line one\n\"quoted\" \\ slash / café 🌍",
'zero' => 0,
],
]));

self::assertTrue($this->client->identify([
'distinctId' => 'person-123',
'properties' => [
'email' => 'person@example.com',
'roles' => ['admin', 'editor'],
'preferences' => (object) [],
],
]));

self::assertTrue($this->client->alias([
'distinctId' => 'person-123',
'alias' => 'anonymous-456',
'properties' => [
'source' => 'snapshot-suite',
],
]));

self::assertTrue(PostHog::groupIdentify([
'groupType' => 'organization',
'groupKey' => 'org-42',
'properties' => [
'employees' => 150,
'labels' => ['customer', 'beta'],
'metadata' => (object) [],
'name' => 'PostHog',
],
]));

self::assertTrue($this->client->flush());
self::assertCount(1, $this->httpClient->calls);

$this->assertJsonSnapshot(
'event-family-request.json',
$this->structuredRequest($this->httpClient->calls[0])
);
}

public function testCompleteFlagsRequestMatchesSnapshot(): void
{
$this->client->flags(
'person-123',
[
'organization' => 'org-42',
'project' => 'project-7',
],
[
'empty_list' => [],
'empty_object' => (object) [],
'nullable' => null,
'plan' => 'enterprise',
'roles' => ['admin', 'editor'],
],
[
'organization' => [
'employee_count' => 150,
'industry' => 'analytics',
'settings' => (object) [],
],
'project' => [
'enabled' => false,
'tags' => ['php', 'server'],
],
],
true,
['checkout-redesign', 'server-rollout']
);

self::assertCount(1, $this->httpClient->calls);
$this->assertJsonSnapshot(
'flags-request.json',
$this->structuredRequest($this->httpClient->calls[0])
);
}

/**
* @param array{
* path: string,
* payload: string,
* extraHeaders: array<int, string>,
* requestOptions: array<string, mixed>
* } $call
* @return array<string, mixed>
*/
private function structuredRequest(array $call): array
{
$headers = [];
foreach ($call['extraHeaders'] as $header) {
[$name, $value] = explode(':', $header, 2);
$headers[trim($name)] = trim($value);
}

return [
'body' => json_decode($call['payload'], false, 512, JSON_THROW_ON_ERROR),
'headers' => $headers,
'options' => $call['requestOptions'],
'path' => $call['path'],
];
}
}
100 changes: 100 additions & 0 deletions test/JsonSnapshotTestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

namespace PostHog\Test;

use PHPUnit\Framework\TestCase;
use stdClass;

abstract class JsonSnapshotTestCase extends TestCase
{
/** @var array<string, string> */
private array $uuidPlaceholders = [];

protected function assertJsonSnapshot(string $name, mixed $actual): void
{
$this->uuidPlaceholders = [];
$normalized = $this->normalizeValue($actual);
$rendered = json_encode(
$normalized,
JSON_PRETTY_PRINT
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
| JSON_PRESERVE_ZERO_FRACTION
| JSON_THROW_ON_ERROR
) . "\n";
$path = __DIR__ . '/assests/snapshots/' . $name;

if (getenv('UPDATE_EVENT_SHAPE_SNAPSHOTS') === '1') {
file_put_contents($path, $rendered);
}

self::assertFileExists($path, "Missing snapshot {$name}");
self::assertSame(
file_get_contents($path),
$rendered,
"Snapshot {$name} changed. Re-record with UPDATE_EVENT_SHAPE_SNAPSHOTS=1."
);
}

private function normalizeValue(mixed $value, ?string $key = null): mixed
{
if ($key === 'api_key' || $key === 'personal_api_key' || $key === 'secret_key') {
return '<redacted>';
}

if ($key === '$lib_version') {
return '<sdk-version>';
}

if (is_string($value)) {
if (preg_match('/^posthog-php\/.+$/', $value) === 1) {
return 'posthog-php/<sdk-version>';
}

if ($this->isUuid($value)) {
if (!isset($this->uuidPlaceholders[$value])) {
$this->uuidPlaceholders[$value] = '<uuid-' . (count($this->uuidPlaceholders) + 1) . '>';
}

return $this->uuidPlaceholders[$value];
}

return $value;
}

if ($value instanceof stdClass) {
$properties = get_object_vars($value);
ksort($properties, SORT_STRING);
$normalized = new stdClass();
foreach ($properties as $property => $propertyValue) {
$normalized->{$property} = $this->normalizeValue($propertyValue, $property);
}

return $normalized;
}

if (is_array($value)) {
if (array_is_list($value)) {
return array_map(fn(mixed $item): mixed => $this->normalizeValue($item), $value);
}

ksort($value, SORT_STRING);
$normalized = [];
foreach ($value as $property => $propertyValue) {
$normalized[$property] = $this->normalizeValue($propertyValue, (string) $property);
}

return $normalized;
}

return $value;
}

private function isUuid(string $value): bool
{
return preg_match(
'/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i',
$value
) === 1;
}
}
Loading
Loading