limiter.test.ts (1426B)
1 import { assertThrows } from "$std/assert/assert_throws.ts"; 2 import { SECOND } from "$std/datetime/constants.ts"; 3 import { FakeTime } from "$std/testing/time.ts"; 4 import { ExceedingLimit, Limiter } from "#core/domain/limiter.ts"; 5 6 Deno.test({ 7 name: "unit limiter should accept initial operation", 8 fn() { 9 const limiter = new Limiter(1, SECOND); 10 const act = () => limiter.increment(); 11 act(); 12 }, 13 }); 14 15 Deno.test({ 16 name: "unit limiter should deny overrated operation", 17 fn() { 18 const limiter = new Limiter(1, SECOND); 19 limiter.increment(); 20 const act = () => limiter.increment(); 21 assertThrows(act, ExceedingLimit); 22 }, 23 }); 24 25 Deno.test({ 26 name: "unit limiter should not deny operation after reset", 27 fn() { 28 const clock = new FakeTime(); 29 try { 30 const limiter = new Limiter(2, SECOND); 31 const act = () => { 32 limiter.increment(); 33 limiter.increment(); 34 clock.tick(SECOND); 35 limiter.increment(); 36 }; 37 act(); // assert not failed 38 } finally { 39 clock.restore(); 40 } 41 }, 42 }); 43 44 Deno.test({ 45 name: "unit limiter should deny operation before reset", 46 fn() { 47 const clock = new FakeTime(); 48 try { 49 const limiter = new Limiter(1, SECOND); 50 limiter.increment(); 51 clock.tick(500); 52 const act = () => limiter.increment(); 53 assertThrows(act, ExceedingLimit); 54 } finally { 55 clock.restore(); 56 } 57 }, 58 });