Skip to content

Commit de76fef

Browse files
authored
Merge pull request #5463 from kenjis/fix-ThrottleTest
refactor: fix `ThrottleTest::testFlooding`
2 parents 6cd0839 + f8c2245 commit de76fef

2 files changed

Lines changed: 8 additions & 3 deletions

File tree

system/Throttle/Throttler.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ public function check(string $key, int $capacity, int $seconds, int $cost = 1):
100100
// If it hasn't been created, then we'll set it to the maximum
101101
// capacity - 1, and save it to the cache.
102102
$this->cache->save($tokenName, $capacity - $cost, $seconds);
103-
$this->cache->save($tokenName . 'Time', time(), $seconds);
103+
$this->cache->save($tokenName . 'Time', $this->time(), $seconds);
104104

105105
return true;
106106
}
@@ -129,7 +129,7 @@ public function check(string $key, int $capacity, int $seconds, int $cost = 1):
129129
// we need to decrement the number of available tokens.
130130
if ($tokens >= 1) {
131131
$this->cache->save($tokenName, $tokens - $cost, $seconds);
132-
$this->cache->save($tokenName . 'Time', time(), $seconds);
132+
$this->cache->save($tokenName . 'Time', $this->time(), $seconds);
133133

134134
return true;
135135
}
@@ -164,6 +164,8 @@ public function setTestTime(int $time)
164164

165165
/**
166166
* Return the test time, defaulting to current.
167+
*
168+
* @TODO should be private
167169
*/
168170
public function time(): int
169171
{

tests/system/Throttle/ThrottleTest.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,7 +127,10 @@ public function testOverload()
127127

128128
public function testFlooding()
129129
{
130+
$time = 1639441295;
131+
130132
$throttler = new Throttler($this->cache);
133+
$throttler->setTestTime($time);
131134

132135
$rate = 60; // allow 1 per second after the bucket is emptied
133136
$cost = 1;
@@ -141,7 +144,7 @@ public function testFlooding()
141144
$this->assertFalse($throttler->check('127.0.0.1', $rate, MINUTE, $cost));
142145
$this->assertSame(0, $this->cache->get('throttler_127.0.0.1'));
143146

144-
$throttler = $throttler->setTestTime(strtotime('+10 seconds'));
147+
$throttler = $throttler->setTestTime($time + 10);
145148

146149
$this->assertTrue($throttler->check('127.0.0.1', $rate, MINUTE, 0));
147150
$this->assertSame(10.0, round($this->cache->get('throttler_127.0.0.1')));

0 commit comments

Comments
 (0)