|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Yiisoft\Yii\Web\Tests\RateLimiter; |
|
4
|
|
|
|
|
5
|
|
|
use RuntimeException; |
|
6
|
|
|
use InvalidArgumentException; |
|
7
|
|
|
use PHPUnit\Framework\TestCase; |
|
8
|
|
|
use Yiisoft\Cache\ArrayCache; |
|
9
|
|
|
use Yiisoft\Yii\Web\RateLimiter\CacheCounter; |
|
10
|
|
|
|
|
11
|
|
|
final class CacheCounterTest extends TestCase |
|
12
|
|
|
{ |
|
13
|
|
|
/** |
|
14
|
|
|
* @test |
|
15
|
|
|
*/ |
|
16
|
|
|
public function limitNotExhausted(): void |
|
17
|
|
|
{ |
|
18
|
|
|
$counter = new CacheCounter(2, 5, new ArrayCache()); |
|
19
|
|
|
$counter->setId('key'); |
|
20
|
|
|
|
|
21
|
|
|
$this->assertFalse($counter->limitIsReached()); |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @test |
|
26
|
|
|
*/ |
|
27
|
|
|
public function limitIsExhausted(): void |
|
28
|
|
|
{ |
|
29
|
|
|
$cache = new ArrayCache(); |
|
30
|
|
|
$cache->set('key', time() + 55); |
|
31
|
|
|
|
|
32
|
|
|
$counter = new CacheCounter(10, 60, $cache); |
|
33
|
|
|
$counter->setId('key'); |
|
34
|
|
|
|
|
35
|
|
|
$this->assertTrue($counter->limitIsReached()); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* @test |
|
40
|
|
|
*/ |
|
41
|
|
|
public function invalidIdArgument(): void |
|
42
|
|
|
{ |
|
43
|
|
|
$this->expectException(RuntimeException::class); |
|
44
|
|
|
(new CacheCounter(10, 60, new ArrayCache()))->limitIsReached(); |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* @test |
|
49
|
|
|
*/ |
|
50
|
|
|
public function invalidLimitArgument(): void |
|
51
|
|
|
{ |
|
52
|
|
|
$this->expectException(InvalidArgumentException::class); |
|
53
|
|
|
$counter = new CacheCounter(0, 60, new ArrayCache()); |
|
54
|
|
|
$counter->setId('key'); |
|
55
|
|
|
$counter->limitIsReached(); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @test |
|
60
|
|
|
*/ |
|
61
|
|
|
public function invalidPeriodArgument(): void |
|
62
|
|
|
{ |
|
63
|
|
|
$this->expectException(InvalidArgumentException::class); |
|
64
|
|
|
$counter = new CacheCounter(10, 0, new ArrayCache()); |
|
65
|
|
|
$counter->setId('key'); |
|
66
|
|
|
$counter->limitIsReached(); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|