107 lines
2.7 KiB
PHP
107 lines
2.7 KiB
PHP
<?php
|
|
|
|
use Illuminate\Support\Facades\Http;
|
|
use Mattitja\Analytics\Services\AnalyticsClient;
|
|
|
|
beforeEach(function () {
|
|
Http::fake();
|
|
});
|
|
|
|
it('sends analytics data to the correct endpoint', function () {
|
|
$client = new AnalyticsClient;
|
|
$data = [
|
|
'k' => 'test-site-key',
|
|
'u' => 'https://example.com/test',
|
|
'r' => 'https://google.com',
|
|
'ip' => '192.168.1.1',
|
|
'ua' => 'Mozilla/5.0 Chrome',
|
|
];
|
|
|
|
$client->send($data);
|
|
|
|
Http::assertSent(function ($request) use ($data) {
|
|
return $request->url() === 'https://analytics.mattitja.cloud/api/send' &&
|
|
$request->method() === 'POST' &&
|
|
$request->data() === $data;
|
|
});
|
|
});
|
|
|
|
it('handles API failures gracefully', function () {
|
|
Http::fake([
|
|
'analytics.mattitja.cloud/*' => Http::response('Server Error', 500),
|
|
]);
|
|
|
|
$client = new AnalyticsClient;
|
|
$data = [
|
|
'k' => 'test-site-key',
|
|
'u' => 'https://example.com/test',
|
|
'r' => 'https://google.com',
|
|
'ip' => '192.168.1.1',
|
|
'ua' => 'Mozilla/5.0 Chrome',
|
|
];
|
|
|
|
expect(fn () => $client->send($data))->not->toThrow(Exception::class);
|
|
});
|
|
|
|
it('uses hardcoded timeout', function () {
|
|
$client = new AnalyticsClient;
|
|
$data = [
|
|
'k' => 'test-site-key',
|
|
'u' => 'https://example.com/test',
|
|
'r' => '',
|
|
'ip' => '192.168.1.1',
|
|
'ua' => 'Mozilla/5.0 Chrome',
|
|
];
|
|
|
|
$client->send($data);
|
|
|
|
Http::assertSent(function ($request) {
|
|
return $request->data()['k'] === 'test-site-key';
|
|
});
|
|
});
|
|
|
|
it('skips sending when required data fields are missing', function () {
|
|
$client = new AnalyticsClient;
|
|
|
|
// Should not throw exceptions, just skip silently
|
|
$client->send([]);
|
|
$client->send(['k' => 'test']);
|
|
$client->send(['k' => 'test', 'u' => 'url', 'ip' => '1.1.1.1']);
|
|
|
|
// No HTTP requests should be sent for invalid data
|
|
Http::assertNothingSent();
|
|
});
|
|
|
|
it('skips sending when URL exceeds 512 characters', function () {
|
|
$client = new AnalyticsClient;
|
|
$longUrl = 'https://example.com/'.str_repeat('a', 500);
|
|
|
|
$client->send([
|
|
'k' => 'testsiteky',
|
|
'u' => $longUrl,
|
|
'ip' => '192.168.1.1',
|
|
'ua' => 'Mozilla/5.0 Chrome',
|
|
]);
|
|
|
|
Http::assertNothingSent();
|
|
});
|
|
|
|
it('filters out empty referrer URLs', function () {
|
|
$client = new AnalyticsClient;
|
|
$data = [
|
|
'k' => 'test-site-key',
|
|
'u' => 'https://example.com/test',
|
|
'r' => '',
|
|
'ip' => '192.168.1.1',
|
|
'ua' => 'Mozilla/5.0 Chrome',
|
|
];
|
|
|
|
$client->send($data);
|
|
|
|
Http::assertSent(function ($request) {
|
|
$sentData = $request->data();
|
|
|
|
return ! isset($sentData['r']);
|
|
});
|
|
});
|