Merge pull request #27903 from overleaf/em-unit-tests-redis

Make Redis available to unit tests

GitOrigin-RevId: 7bd403d9ad4be504a87bc9108d60686e6c2a9fb1
This commit is contained in:
Eric Mc Sween
2025-08-18 08:05:40 +00:00
committed by Copybot
parent d43f09ca4f
commit cd64720abe
4 changed files with 72 additions and 155 deletions
@@ -2,29 +2,36 @@ const Settings = require('@overleaf/settings')
const redis = require('@overleaf/redis-wrapper')
const { addConnectionDrainer } = require('./GracefulShutdown')
if (
(typeof global.beforeEach === 'function' &&
process.argv.join(' ').match(/unit/)) ||
process.env.VITEST
) {
throw new Error(
'It looks like unit tests are running, but you are connecting to Redis. Missing a stub?'
)
/**
* A per-feature interface to Redis, looks up the feature in `settings.redis`
* and returns an appropriate client. Necessary because we don't want to
* migrate web over to redis-cluster all at once.
*
* @param feature - one of 'websessions' | 'ratelimiter' | ...
*/
function client(feature) {
const redisFeatureSettings = Settings.redis[feature] || Settings.redis.web
const client = redis.createClient(redisFeatureSettings)
addConnectionDrainer(`redis ${feature}`, async () => {
await client.disconnect()
})
return client
}
// A per-feature interface to Redis,
// looks up the feature in `settings.redis`
// and returns an appropriate client.
// Necessary because we don't want to migrate web over
// to redis-cluster all at once.
module.exports = {
// feature = 'websessions' | 'ratelimiter' | ...
client(feature) {
const redisFeatureSettings = Settings.redis[feature] || Settings.redis.web
const client = redis.createClient(redisFeatureSettings)
addConnectionDrainer(`redis ${feature}`, async () => {
await client.disconnect()
})
return client
},
async function cleanupTestRedis() {
const rclient = client()
ensureTestRedis(rclient)
await rclient.flushall()
}
function ensureTestRedis(rclient) {
const host = rclient.options.host
const env = process.env.NODE_ENV
if (host !== 'redis_test' || env !== 'test') {
throw new Error(
`Refusing to clear Redis instance '${host}' in environment '${env}'`
)
}
}
module.exports = { client, cleanupTestRedis }