Passed
Pull Request — master (#204)
by Alexander
01:58
created

statisticsShouldBeCorrectWhenLimitIsNotReached()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 0
dl 0
loc 10
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Yiisoft\Yii\Web\Tests\RateLimiter;
4
5
use InvalidArgumentException;
6
use PHPUnit\Framework\TestCase;
7
use Yiisoft\Cache\ArrayCache;
8
use Yiisoft\Yii\Web\RateLimiter\Counter;
9
10
final class CounterTest extends TestCase
11
{
12
    /**
13
     * @test
14
     */
15
    public function statisticsShouldBeCorrectWhenLimitIsNotReached(): void
16
    {
17
        $counter = new Counter(2, 5, new ArrayCache());
18
        $counter->setId('key');
19
20
        $statistics = $counter->incrementAndGetResult();
21
        $this->assertEquals(2, $statistics->getLimit());
22
        $this->assertEquals(1, $statistics->getRemaining());
23
        $this->assertEquals(2500, $statistics->getReset());
24
        $this->assertFalse($statistics->isLimitReached());
25
    }
26
27
    /**
28
     * @test
29
     */
30
    public function statisticsShouldBeCorrectWhenLimitIsReached(): void
31
    {
32
        $cache = new ArrayCache();
33
        $cache->set(Counter::ID_PREFIX . 'key', (time() * 1000) + 55000);
34
35
        $counter = new Counter(10, 60, $cache);
36
        $counter->setId('key');
37
38
        $statistics = $counter->incrementAndGetResult();
39
        $this->assertEquals(10, $statistics->getLimit());
40
        $this->assertEquals(0, $statistics->getRemaining());
41
        $this->assertEquals(61000, $statistics->getReset());
42
        $this->assertTrue($statistics->isLimitReached());
43
    }
44
45
    /**
46
     * @test
47
     */
48
    public function shouldNotBeAbleToSetInvalidId(): void
49
    {
50
        $this->expectException(\LogicException::class);
51
        (new Counter(10, 60, new ArrayCache()))->incrementAndGetResult();
52
    }
53
54
    /**
55
     * @test
56
     */
57
    public function shouldNotBeAbleToSetInvalidLimit(): void
58
    {
59
        $this->expectException(InvalidArgumentException::class);
60
        new Counter(0, 60, new ArrayCache());
61
    }
62
63
    /**
64
     * @test
65
     */
66
    public function shouldNotBeAbleToSetInvalidPeriod(): void
67
    {
68
        $this->expectException(InvalidArgumentException::class);
69
        new Counter(10, 0, new ArrayCache());
70
    }
71
}
72