. */ declare(strict_types=1); namespace Fisharebest\Webtrees\Services; use Fisharebest\Webtrees\GuestUser; use Fisharebest\Webtrees\Http\Exceptions\HttpTooManyRequestsException; use Fisharebest\Webtrees\TestCase; use LogicException; use function explode; use function implode; use function range; use function time; /** * Test harness for the class RateLimitService */ class RateLimitServiceTest extends TestCase { /** * @covers \Fisharebest\Webtrees\Services\RateLimitService * * @return void */ public function testTooMuchHistory(): void { $rate_limit_service = new RateLimitService(); $user = new GuestUser(); $this->expectException(LogicException::class); $rate_limit_service->limitRateForUser($user, 1000, 30, 'rate-limit'); } /** * @covers \Fisharebest\Webtrees\Services\RateLimitService * * @return void */ public function testLimitNotReached(): void { $rate_limit_service = new RateLimitService(); $user = new GuestUser(); $rate_limit_service->limitRateForUser($user, 3, 30, 'rate-limit'); $history = $user->getPreference('rate-limit'); $this->assertCount(1, explode(',', $history)); $rate_limit_service->limitRateForUser($user, 3, 30, 'rate-limit'); $history = $user->getPreference('rate-limit'); $this->assertCount(2, explode(',', $history)); $rate_limit_service->limitRateForUser($user, 3, 30, 'rate-limit'); $history = $user->getPreference('rate-limit'); $this->assertCount(3, explode(',', $history)); } /** * @covers \Fisharebest\Webtrees\Services\RateLimitService * * @return void */ public function testOldEventsIgnored(): void { $rate_limit_service = new RateLimitService(); $user = new GuestUser(); $history = implode(',', range(time() - 35, time() - 31)); $user->setPreference('rate-limit', $history); $rate_limit_service->limitRateForUser($user, 5, 30, 'rate-limit'); $history = $user->getPreference('rate-limit'); $this->assertCount(6, explode(',', $history)); } /** * @covers \Fisharebest\Webtrees\Services\RateLimitService * * @return void */ public function testLimitReached(): void { $rate_limit_service = new RateLimitService(); $user = new GuestUser(); $history = implode(',', range(time() - 5, time() - 1)); $user->setPreference('rate-limit', $history); $this->expectException(HttpTooManyRequestsException::class); $rate_limit_service->limitRateForUser($user, 5, 30, 'rate-limit'); } }