Skip to content

Commit

Permalink
fix: failing unit tests
Browse files Browse the repository at this point in the history
Signed-off-by: Victor Yanev <[email protected]>
  • Loading branch information
victor-yanev committed Oct 11, 2024
1 parent a77f1cf commit dea36d2
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 60 deletions.
8 changes: 2 additions & 6 deletions packages/relay/src/lib/clients/cache/redisCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,12 +199,8 @@ export class RedisCache implements IRedisCacheClient {
serializedKeyValuePairs[key] = JSON.stringify(value);
}

try {
// Perform mSet operation
await client.mSet(serializedKeyValuePairs);
} catch (e) {
this.logger.error(e);
}
// Perform mSet operation
await client.mSet(serializedKeyValuePairs);

// Log the operation
const entriesLength = Object.keys(keyValuePairs).length;
Expand Down
55 changes: 27 additions & 28 deletions packages/relay/tests/lib/clients/localLRUCache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,27 +36,16 @@ describe('LocalLRUCache Test Suite', async function () {
const logger = pino();
const registry = new Registry();
const callingMethod = 'localLRUCacheTest';
const requestDetails = new RequestDetails({ requestId: 'localLRUCacheTest', ipAddress: '0.0.0.0' });

let localLRUCache: LocalLRUCache;
let lruCacheSpy: sinon.SinonSpiedInstance<LRUCache<string, any>>;
let cacheTTL: string | undefined;

const requestDetails = new RequestDetails({ requestId: 'localLRUCacheTest', ipAddress: '0.0.0.0' });

this.beforeAll(() => {
cacheTTL = process.env.CACHE_TTL;
process.env.CACHE_TTL = '200'; // set default cache ttl to 200ms for testing
localLRUCache = new LocalLRUCache(logger.child({ name: `cache` }), registry);
lruCacheSpy = sinon.spy(localLRUCache['cache']);
});

this.afterAll(() => {
process.env.CACHE_TTL = cacheTTL;
});

this.beforeEach(() => {
localLRUCache.clear();
sinon.resetHistory();
});

describe('verify simple cache', async function () {
Expand Down Expand Up @@ -147,41 +136,51 @@ describe('LocalLRUCache Test Suite', async function () {
});

it('verify cache LRU nature', async function () {
const customLocalLRUCache = new LocalLRUCache(logger.child({ name: `cache` }), registry);
const key = 'key';
let valueCount = 0; // keep track of values sets
await localLRUCache.set(key, ++valueCount, callingMethod, requestDetails);
await localLRUCache.set(key, ++valueCount, callingMethod, requestDetails);
await localLRUCache.set(key, ++valueCount, callingMethod, requestDetails);
const cacheValue = await localLRUCache.get(key, callingMethod, requestDetails);
await customLocalLRUCache.set(key, ++valueCount, callingMethod, requestDetails);
await customLocalLRUCache.set(key, ++valueCount, callingMethod, requestDetails);
await customLocalLRUCache.set(key, ++valueCount, callingMethod, requestDetails);
const cacheValue = await customLocalLRUCache.get(key, callingMethod, requestDetails);
// expect cache to have the latest value for key
expect(cacheValue).to.be.equal(valueCount);
});

it('verify cache ttl nature', async function () {
const customLocalLRUCache = new LocalLRUCache(logger.child({ name: `cache` }), registry);
const key = 'key';
const ttl = 100;
await localLRUCache.set(key, 'value', callingMethod, requestDetails, ttl);
await customLocalLRUCache.set(key, 'value', callingMethod, requestDetails, ttl);

await new Promise((r) => setTimeout(r, ttl + 100)); // wait for ttl to expire
const cacheValue = await localLRUCache.get(key, callingMethod, requestDetails);
const cacheValue = await customLocalLRUCache.get(key, callingMethod, requestDetails);
expect(cacheValue).to.be.null;
});

it('it should set without TTL if -1 is passed for TTL', async () => {
const key = 'key';
const value = { intField: 1, stringField: 'string', boolField: true, arrField: [1, 2, 3] };
const ttl = -1;
try {
process.env.CACHE_TTL = '100'; // set default cache ttl to 100ms for testing
const customLocalLRUCache = new LocalLRUCache(logger.child({ name: `cache` }), registry);
const lruCacheSpy = sinon.spy(customLocalLRUCache['cache']);

const key = 'key';
const value = { intField: 1, stringField: 'string', boolField: true, arrField: [1, 2, 3] };
const ttl = -1;

await localLRUCache.set(key, value, callingMethod, requestDetails, ttl);
sinon.assert.calledOnceWithExactly(lruCacheSpy.set, key, value, { ttl: 0 });
await customLocalLRUCache.set(key, value, callingMethod, requestDetails, ttl);
sinon.assert.calledOnceWithExactly(lruCacheSpy.set, key, value, { ttl: 0 });

const cachedValue = await localLRUCache.get(key, callingMethod, requestDetails);
expect(cachedValue).equal(value);
const cachedValue = await customLocalLRUCache.get(key, callingMethod, requestDetails);
expect(cachedValue).equal(value);

await new Promise((resolve) => setTimeout(resolve, localLRUCache['options'].ttl + 100));
await new Promise((resolve) => setTimeout(resolve, customLocalLRUCache['options'].ttl + 100));

const cachedValueAfterTTL = await localLRUCache.get(key, callingMethod, requestDetails);
expect(cachedValueAfterTTL).equal(value);
const cachedValueAfterTTL = await customLocalLRUCache.get(key, callingMethod, requestDetails);
expect(cachedValueAfterTTL).equal(value);
} finally {
delete process.env.CACHE_TTL;
}
});
});

Expand Down
2 changes: 1 addition & 1 deletion packages/relay/tests/lib/clients/redisCache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ describe('RedisCache Test Suite', async function () {

this.beforeAll(async () => {
redisCache = new RedisCache(logger.child({ name: `cache` }), registry);
redisCache['options'].ttl = 200; // Set default TTL to 200 milliseconds for testing
redisCache['options'].ttl = 100; // set default cache ttl to 100ms for testing
redisClientSpy = sinon.spy(redisCache['client']);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ describe('EthAddressHbarSpendingPlanRepository', function () {
}

const result = await repository.findAllByPlanId(planId, 'findAllByPlanId', requestDetails);
expect(result).to.deep.equal(ethAddressPlans);
expect(result).to.have.deep.members(ethAddressPlans);
});

it('returns an empty array if no address plans are found for the plan ID', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,12 @@ describe('HbarSpendingPlanRepository', function () {
const ttl = 86_400_000; // 1 day

const tests = (isSharedCacheEnabled: boolean) => {
let cacheService: CacheService;
let cacheServiceSpy: sinon.SinonSpiedInstance<CacheService>;
let repository: HbarSpendingPlanRepository;

before(async () => {
const cacheService = new CacheService(logger.child({ name: `CacheService` }), registry);
cacheService = new CacheService(logger.child({ name: `CacheService` }), registry);
cacheServiceSpy = sinon.spy(cacheService);
repository = new HbarSpendingPlanRepository(cacheService, logger.child({ name: `HbarSpendingPlanRepository` }));
});
Expand All @@ -59,11 +60,11 @@ describe('HbarSpendingPlanRepository', function () {
}

afterEach(async () => {
await cacheServiceSpy.clear(requestDetails);
await cacheService.clear(requestDetails);
});

after(async () => {
await cacheServiceSpy.disconnectRedisClient();
await cacheService.disconnectRedisClient();
});

describe('create', () => {
Expand Down Expand Up @@ -137,7 +138,7 @@ describe('HbarSpendingPlanRepository', function () {

const key = `${repository['collectionKey']}:${createdPlan.id}:spendingHistory`;
const hbarSpending = { amount: 100, timestamp: new Date() } as IHbarSpendingRecord;
await cacheServiceSpy.rPush(key, hbarSpending, 'test', requestDetails);
await cacheService.rPush(key, hbarSpending, 'test', requestDetails);

const spendingHistory = await repository.getSpendingHistory(createdPlan.id, requestDetails);
expect(spendingHistory).to.have.lengthOf(1);
Expand Down Expand Up @@ -299,7 +300,7 @@ describe('HbarSpendingPlanRepository', function () {

// Manually set the plan to inactive
const key = `${repository['collectionKey']}:${createdPlan.id}`;
await cacheServiceSpy.set(key, { ...createdPlan, active: false }, 'test', requestDetails);
await cacheService.set(key, { ...createdPlan, active: false }, 'test', requestDetails);

const amount = 50;
await expect(
Expand All @@ -326,7 +327,7 @@ describe('HbarSpendingPlanRepository', function () {

// Manually set the plan to inactive
const key = `${repository['collectionKey']}:${createdPlan.id}`;
await cacheServiceSpy.set(key, { ...createdPlan, active: false }, 'test', requestDetails);
await cacheService.set(key, { ...createdPlan, active: false }, 'test', requestDetails);

await expect(repository.checkExistsAndActive(createdPlan.id, requestDetails)).to.be.eventually.rejectedWith(
HbarSpendingPlanNotActiveError,
Expand Down Expand Up @@ -359,7 +360,7 @@ describe('HbarSpendingPlanRepository', function () {

// Manually set the plan to inactive
const key = `${repository['collectionKey']}:${inactivePlan.id}`;
await cacheServiceSpy.set(key, { ...inactivePlan, active: false }, 'test', requestDetails);
await cacheService.set(key, { ...inactivePlan, active: false }, 'test', requestDetails);

const activePlans = await repository.findAllActiveBySubscriptionTier([subscriptionTier], requestDetails);
expect(activePlans).to.deep.equal([activePlan]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ describe('IPAddressHbarSpendingPlanRepository', function () {
}

const result = await repository.findAllByPlanId(planId, 'findAllByPlanId', requestDetails);
expect(result).to.deep.equal(ipAddressPlans);
expect(result).to.have.deep.members(ipAddressPlans);
});

it('returns an empty array if no address plans are found for the plan ID', async () => {
Expand Down
32 changes: 16 additions & 16 deletions packages/relay/tests/lib/services/cacheService/cacheService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,17 +30,19 @@ import { useInMemoryRedisServer } from '../../../helpers';
import { RequestDetails } from '../../../../dist/lib/types';

dotenv.config({ path: path.resolve(__dirname, '../test.env') });
const logger = pino();
const registry = new Registry();
let cacheService: CacheService;

const callingMethod = 'CacheServiceTest';

chai.use(chaiAsPromised);

describe('CacheService Test Suite', async function () {
this.timeout(10000);

const logger = pino();
const registry = new Registry();
const callingMethod = 'CacheServiceTest';
const requestDetails = new RequestDetails({ requestId: 'cacheServiceTest', ipAddress: '0.0.0.0' });

let cacheService: CacheService;

const describeKeysTestSuite = () => {
describe('keys', async function () {
it('should retrieve all keys', async function () {
Expand Down Expand Up @@ -141,7 +143,10 @@ describe('CacheService Test Suite', async function () {
};

describe('Internal Cache Test Suite', async function () {
let redisEnabled: string | undefined;

this.beforeAll(() => {
redisEnabled = process.env.REDIS_ENABLED;
process.env.REDIS_ENABLED = 'false';
cacheService = new CacheService(logger.child({ name: 'cache-service' }), registry);
});
Expand All @@ -150,6 +155,10 @@ describe('CacheService Test Suite', async function () {
await cacheService.clear(requestDetails);
});

this.afterAll(() => {
process.env.REDIS_ENABLED = redisEnabled;
});

it('should be able to set and get from internal cache', async function () {
const key = 'string';
const value = 'value';
Expand Down Expand Up @@ -431,16 +440,6 @@ describe('CacheService Test Suite', async function () {
});

describe('incrBy', async function () {
it('should increment value in internal cache', async function () {
const key = 'counter';
const amount = 5;

await cacheService.set(key, 10, callingMethod, requestDetails);
const newValue = await cacheService.incrBy(key, amount, callingMethod, requestDetails);

expect(newValue).to.equal(15);
});

it('should increment value in shared cache', async function () {
const key = 'counter';
const amount = 5;
Expand All @@ -457,9 +456,10 @@ describe('CacheService Test Suite', async function () {

await cacheService.disconnectRedisClient();

await cacheService.set(key, 10, callingMethod, requestDetails);
const newValue = await cacheService.incrBy(key, amount, callingMethod, requestDetails);

expect(newValue).to.equal(5);
expect(newValue).to.equal(15);
});
});

Expand Down

0 comments on commit dea36d2

Please sign in to comment.