Add rate limiter test case for cache misses.

This commit is contained in:
Jeff Stieler 2021-10-15 16:02:14 -04:00
parent f218571fec
commit 20614cfdcb
1 changed files with 29 additions and 0 deletions

View File

@ -49,4 +49,33 @@ class WC_Tests_Rate_Limiter extends WC_Unit_Test_Case {
$this->assertEquals( false, WC_Rate_Limiter::retried_too_soon( $rate_limit_id_2 ), 'retried_too_soon did not allow action to run for another user after the designated delay.' );
}
/**
* Test setting the limit and running rate limited actions when missing cache.
*/
public function test_rate_limit_limits_without_cache() {
$action_identifier = 'action_1';
$user_1_id = 10;
$user_2_id = 15;
$rate_limit_id_1 = $action_identifier . $user_1_id;
$rate_limit_id_2 = $action_identifier . $user_2_id;
WC_Rate_Limiter::set_rate_limit( $rate_limit_id_1, 1 );
// Clear cached value for user 1.
wp_cache_delete( WC_Cache_Helper::get_cache_prefix( 'rate_limit' . $rate_limit_id_1 ), WC_Rate_Limiter::CACHE_GROUP );
$this->assertEquals( true, WC_Rate_Limiter::retried_too_soon( $rate_limit_id_1 ), 'retried_too_soon allowed action to run too soon before the delay.' );
$this->assertEquals( false, WC_Rate_Limiter::retried_too_soon( $rate_limit_id_2 ), 'retried_too_soon did not allow action to run for another user before the delay.' );
// Clear cached values for both users.
wp_cache_delete( WC_Cache_Helper::get_cache_prefix( 'rate_limit' . $rate_limit_id_1 ), WC_Rate_Limiter::CACHE_GROUP );
wp_cache_delete( WC_Cache_Helper::get_cache_prefix( 'rate_limit' . $rate_limit_id_2 ), WC_Rate_Limiter::CACHE_GROUP );
// As retired_too_soon bails if current time <= limit, the actual time needs to be at least 1 second after the limit.
sleep( 2 );
$this->assertEquals( false, WC_Rate_Limiter::retried_too_soon( $rate_limit_id_1 ), 'retried_too_soon did not allow action to run after the designated delay.' );
$this->assertEquals( false, WC_Rate_Limiter::retried_too_soon( $rate_limit_id_2 ), 'retried_too_soon did not allow action to run for another user after the designated delay.' );
}
}