1<?php 2 3/** 4 * webtrees: online genealogy 5 * Copyright (C) 2023 webtrees development team 6 * This program is free software: you can redistribute it and/or modify 7 * it under the terms of the GNU General Public License as published by 8 * the Free Software Foundation, either version 3 of the License, or 9 * (at your option) any later version. 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <https://www.gnu.org/licenses/>. 16 */ 17 18declare(strict_types=1); 19 20namespace Fisharebest\Webtrees\Services; 21 22use Fisharebest\Webtrees\GuestUser; 23use Fisharebest\Webtrees\Http\Exceptions\HttpTooManyRequestsException; 24use Fisharebest\Webtrees\TestCase; 25use LogicException; 26 27use PHPUnit\Framework\Attributes\CoversClass; 28 29use function explode; 30use function implode; 31use function range; 32use function time; 33 34 35#[CoversClass(RateLimitService::class)] 36class RateLimitServiceTest extends TestCase 37{ 38 public function testTooMuchHistory(): void 39 { 40 $rate_limit_service = new RateLimitService(); 41 42 $user = new GuestUser(); 43 44 $this->expectException(LogicException::class); 45 46 $rate_limit_service->limitRateForUser($user, 1000, 30, 'rate-limit'); 47 } 48 49 public function testLimitNotReached(): void 50 { 51 $rate_limit_service = new RateLimitService(); 52 53 $user = new GuestUser(); 54 55 $rate_limit_service->limitRateForUser($user, 3, 30, 'rate-limit'); 56 $history = $user->getPreference('rate-limit'); 57 static::assertCount(1, explode(',', $history)); 58 59 $rate_limit_service->limitRateForUser($user, 3, 30, 'rate-limit'); 60 $history = $user->getPreference('rate-limit'); 61 static::assertCount(2, explode(',', $history)); 62 63 $rate_limit_service->limitRateForUser($user, 3, 30, 'rate-limit'); 64 $history = $user->getPreference('rate-limit'); 65 static::assertCount(3, explode(',', $history)); 66 } 67 68 public function testOldEventsIgnored(): void 69 { 70 $rate_limit_service = new RateLimitService(); 71 72 $user = new GuestUser(); 73 74 $history = implode(',', range(time() - 35, time() - 31)); 75 $user->setPreference('rate-limit', $history); 76 77 $rate_limit_service->limitRateForUser($user, 5, 30, 'rate-limit'); 78 $history = $user->getPreference('rate-limit'); 79 static::assertCount(6, explode(',', $history)); 80 } 81 82 public function testLimitReached(): void 83 { 84 $rate_limit_service = new RateLimitService(); 85 86 $user = new GuestUser(); 87 88 $history = implode(',', range(time() - 5, time() - 1)); 89 $user->setPreference('rate-limit', $history); 90 91 $this->expectException(HttpTooManyRequestsException::class); 92 $rate_limit_service->limitRateForUser($user, 5, 30, 'rate-limit'); 93 } 94} 95