Skip to content

Commit

Permalink
Add rate limits
Browse files Browse the repository at this point in the history
  • Loading branch information
MrGoodBytes committed Apr 12, 2021
1 parent 501cde7 commit 20bbd06
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Providers/Twitch.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,40 @@ public function accessToken(): string
}
//endregion

//region Mock Rate Limits

/**
* @param bool $noRemaining
* @return array
*/
public function rateLimitArray(bool $noRemaining = false): array
{
$reset = $this->generator->dateTimeInInterval('now', '+3 seconds')->getTimestamp();

$info = [
'RateLimit-Limit' => self::rateLimit(),
'RateLimit-Remaining' => 4,
'RateLimit-Reset' => $reset,
];
if ($noRemaining) {
$info['RateLimit-Remaining'] = 0;
} else {
$info['RateLimit-Remaining'] = self::rateLimit($info['RateLimit-Limit']);
}

return $info;
}

/**
* @return int
*/
public function rateLimit(int $max = 60)
{
if($max < 5) {
$max = 5;
}
return $this->generator->numberBetween(5, $max);
}
//endregion

}
31 changes: 31 additions & 0 deletions Tests/Providers/TwitchTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,35 @@ public function testRefreshToken(int $index)
$words = $this->faker->refreshToken();
$this->assertEquals(30, strlen($words));
}

/**
*
*/
public function testRateLimit()
{
foreach(range(1, 10) as $j) {
foreach (range(-5, 65) as $index) {
$result = $this->faker->rateLimit($index);
$this->assertGreaterThanOrEqual(5, $result);
}
}
}

/**
*
*/
public function testRateLimitArray()
{
$result = $this->faker->rateLimitArray();
$this->assertArrayHasKey('RateLimit-Limit', $result);
$this->assertArrayHasKey('RateLimit-Remaining', $result);
$this->assertArrayHasKey('RateLimit-Reset', $result);

$result = $this->faker->rateLimitArray(true);
$this->assertArrayHasKey('RateLimit-Limit', $result);
$this->assertArrayHasKey('RateLimit-Remaining', $result);
$this->assertEquals(0, $result['RateLimit-Remaining']);
$this->assertArrayHasKey('RateLimit-Reset', $result);

}
}

0 comments on commit 20bbd06

Please sign in to comment.