Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing redis key expiration

I was wondering if anyone has a clever way of testing behavior after a redis key expires. I am essentially building a small redis backed cache for my application and would like to test what happens after a redis key is set to expire.

I am using rspec as my testing framework. I tried to use Timecop to change the time during testing but realized that it would only effect the testing frame work and not the external redis server.

I can set the TTL to 1 and then use a sleep(1) but I would rather not introduce sleeps into my tests.

Does anyone have a good way of testing this?

like image 655
ajorgensen Avatar asked Jan 26 '13 20:01

ajorgensen


People also ask

Do Redis keys expire?

Normally Redis keys are created without an associated time to live. The key will simply live forever, unless it is removed by the user in an explicit way, for instance using the DEL command.

Can you define an expiration time of a field in a hash Redis?

All the Redis objects have an expiration time. By default, the value is set to never. However, by changing this value, we can set Redis keys that will expire automatically after a fixed amount of time. Once the expiration time is passed, the key is deleted from the database.

What happens when TTL expires Redis?

Redis is an in-memory data structure store, used as a distributed, in-memory key–value database. And TTL stands for Time-to-Live. While setting a key in Redis, you can specify the time to live for key when the TTL elapses, the key is automatically destroyed.


2 Answers

Why not use http://redis.io/commands/expire to expire the key right away?

like image 58
Jim Deville Avatar answered Oct 13 '22 12:10

Jim Deville


The proper way to fix this for the testing environment is to mock out the redis client and have it return the expected value. I have confidence redis will do the right thing and is implemented correctly so mocking this interaction out is probably better than letting the test actually hit redis.

redis_client.should_receive(:ttl).with(key).then_return(-1)

or just mock out the request for the key

redis_client.should_receive(:get).with(key).then_return(nil)

With the newer RSpecs version,

expect(redis_client).to receive(:get).with(key).and_return(value)
like image 1
ajorgensen Avatar answered Oct 13 '22 13:10

ajorgensen