Commit e7938207 authored by Max Woolf's avatar Max Woolf
Browse files

test(rate_limit): replace sleep-based TTL assertions with state anchoring

The two TTL invariance tests (\"does not reset the TTL\" on check;
\"does not extend the TTL of an existing key\" on peek) both used
sleep 1.1 to let Redis's second-resolution TTL clock tick down, then
asserted second_ttl < first_ttl. The temporal assertion conflates two
things — \"Redis clock moved\" and \"no EXPIRE happened\" — and pays
~1.1s per test.

Replace with: pin a distinctive TTL via raw_redis.expire(key, 7) that
the rule's period would never produce (60-120), then assert the TTL
is still in (1, 7] after the operation under test. A mistaken EXPIRE
would have clobbered it back to the rule's period; an unchanged TTL
provably means EXPIRE didn't fire.

Local suite for evaluator_spec.rb drops from ~2.6s to ~0.4s.

Addresses !291 review thread 7e996fa9.
parent 3c15ecb6
Loading
Loading
Loading
Loading
+9 −7
Original line number Diff line number Diff line
@@ -116,12 +116,13 @@ RSpec.describe Labkit::RateLimit::Evaluator do
      ev = evaluator(rules: [rule])

      ev.check(identifier)
      first_ttl = raw_redis.ttl(key)
      sleep 1.1
      # Force a distinctive TTL the rule's period would never produce; a
      # subsequent check that mistakenly EXPIRE'd would clobber it back to ~120.
      raw_redis.expire(key, 7)

      ev.check(identifier)
      second_ttl = raw_redis.ttl(key)

      expect(second_ttl).to be < first_ttl
      expect(raw_redis.ttl(key)).to be_between(1, 7)
    end

    it "self-heals a key that exists without expiry (TTL = -1)" do
@@ -230,12 +231,13 @@ RSpec.describe Labkit::RateLimit::Evaluator do
    it "does not extend the TTL of an existing key" do
      ev = evaluator(rules: [peek_rule])
      ev.check(identifier)
      first_ttl = raw_redis.ttl(key)
      sleep 1.1
      # Same trick as the check-side TTL test: pin a distinctive TTL that a
      # mistaken EXPIRE would replace, then assert it's untouched after peek.
      raw_redis.expire(key, 7)

      ev.peek(identifier)

      expect(raw_redis.ttl(key)).to be < first_ttl
      expect(raw_redis.ttl(key)).to be_between(1, 7)
    end

    it "reads back the integer-valued count from an INCR-style counter" do