Skip to content

Commit

Permalink
fix: unit tests
Browse files Browse the repository at this point in the history
Signed-off-by: Victor Yanev <victor.yanev@limechain.tech>
  • Loading branch information
victor-yanev committed Dec 19, 2024
1 parent 529bad8 commit 8b3d4bf
Show file tree
Hide file tree
Showing 29 changed files with 150 additions and 162 deletions.
8 changes: 0 additions & 8 deletions packages/relay/src/lib/services/hbarLimitService/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -281,14 +281,6 @@ export class HbarLimitService implements IHbarLimitService {
const remainingBudget = await this.getRemainingBudget(requestDetails);
this.hbarLimitRemainingGauge.set(remainingBudget.toTinybars().toNumber());

const ipAddress = requestDetails.ipAddress;
if (!evmAddress && !ipAddress) {
if (this.logger.isLevelEnabled('trace')) {
this.logger.trace('Cannot add expense to a spending plan without an evm address or ip address');
}
return;
}

let spendingPlan = await this.getSpendingPlan(evmAddress, requestDetails);
if (!spendingPlan) {
if (evmAddress) {
Expand Down
9 changes: 5 additions & 4 deletions packages/relay/tests/lib/clients/localLRUCache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,20 @@

import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import { Registry } from 'prom-client';
import pino from 'pino';
import { Registry } from 'prom-client';
import sinon from 'sinon';

import { LocalLRUCache } from '../../../src/lib/clients';
import { overrideEnvsInMochaDescribe, withOverriddenEnvsInMochaTest } from '../../helpers';
import { RequestDetails } from '../../../src/lib/types';
import sinon from 'sinon';
import { overrideEnvsInMochaDescribe, withOverriddenEnvsInMochaTest } from '../../helpers';

chai.use(chaiAsPromised);

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

const logger = pino();
const logger = pino({ level: 'silent' });
const registry = new Registry();
const callingMethod = 'localLRUCacheTest';
const requestDetails = new RequestDetails({ requestId: 'localLRUCacheTest', ipAddress: '0.0.0.0' });
Expand Down
13 changes: 7 additions & 6 deletions packages/relay/tests/lib/clients/redisCache.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,23 @@
*
*/

import { pino } from 'pino';
import chai, { expect } from 'chai';
import chaiAsPromised from 'chai-as-promised';
import { RedisCache } from '../../../src/lib/clients';
import { pino } from 'pino';
import { Registry } from 'prom-client';
import { useInMemoryRedisServer } from '../../helpers';
import { RequestDetails } from '../../../dist/lib/types';
import sinon from 'sinon';
import { RedisClientType } from 'redis';
import sinon from 'sinon';

import { RequestDetails } from '../../../dist/lib/types';
import { RedisCache } from '../../../src/lib/clients';
import { useInMemoryRedisServer } from '../../helpers';

chai.use(chaiAsPromised);

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

const logger = pino();
const logger = pino({ level: 'silent' });
const registry = new Registry();
const callingMethod = 'RedisCacheTest';
const requestDetails = new RequestDetails({ requestId: 'localLRUCacheTest', ipAddress: '0.0.0.0' });
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
/*
/*-
*
* Hedera JSON RPC Relay
*
* Copyright (C) 2022-2024 Hedera Hashgraph, LLC
* Copyright (C) 2024 Hedera Hashgraph, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -53,14 +53,7 @@ chai.use(chaiAsPromised);
describe('HbarSpendingPlanConfigService', function () {
const logger = pino({
name: 'hbar-spending-plan-config-service',
transport: {
target: 'pino-pretty',
options: {
colorize: true,
translateTime: true,
ignore: 'pid,hostname',
},
},
level: 'silent',
});
const registry = new Registry();
const neverExpireTtl = -1;
Expand Down
2 changes: 1 addition & 1 deletion packages/relay/tests/lib/eth/eth-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function balancesByAccountIdByTimestampURL(id: string, timestamp?: string

export function generateEthTestEnv(fixedFeeHistory = false) {
ConfigServiceTestHelper.dynamicOverride('ETH_FEE_HISTORY_FIXED', fixedFeeHistory);
const logger = pino();
const logger = pino({ level: 'silent' });
const registry = new Registry();
const cacheService = new CacheService(logger.child({ name: `cache` }), registry);
// @ts-ignore
Expand Down
7 changes: 4 additions & 3 deletions packages/relay/tests/lib/eth/eth_common.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@

import { ConfigService } from '@hashgraph/json-rpc-config-service/dist/services';
import { expect, use } from 'chai';
import { Registry } from 'prom-client';
import pino from 'pino';
import chaiAsPromised from 'chai-as-promised';
import pino from 'pino';
import { Registry } from 'prom-client';

import { RelayImpl } from '../../../src';
import { RequestDetails } from '../../../src/lib/types';

Expand All @@ -35,7 +36,7 @@ describe('@ethCommon', async function () {
const requestDetails = new RequestDetails({ requestId: 'eth_commonTest', ipAddress: '0.0.0.0' });

this.beforeAll(() => {
Relay = new RelayImpl(pino(), new Registry());
Relay = new RelayImpl(pino({ level: 'silent' }), new Registry());
});

describe('@ethCommon', async function () {
Expand Down
2 changes: 0 additions & 2 deletions packages/relay/tests/lib/eth/eth_estimateGas.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,6 @@ use(chaiAsPromised);
let sdkClientStub: SinonStubbedInstance<SDKClient>;
let getSdkClientStub: SinonStub<[], SDKClient>;
let ethImplOverridden: Eth;
let currentMaxBlockRange: number;
const defaultGasOverride = constants.TX_DEFAULT_GAS_DEFAULT + 1;

describe('@ethEstimateGas Estimate Gas spec', async function () {
this.timeout(10000);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ describe('@ethSendRawTransaction eth_sendRawTransaction spec', async function ()
sinon.stub(txResponseMock, 'getReceipt').onFirstCall().resolves({ fileId: FILE_ID });
txResponseMock.transactionId = TransactionId.fromString(transactionIdServicesFormat);

sdkClientStub.logger = pino();
sdkClientStub.logger = pino({ level: 'silent' });
sdkClientStub.deleteFile.resolves();

restMock.onGet(contractResultEndpoint).reply(200, { hash: expectedTxHash });
Expand Down
2 changes: 1 addition & 1 deletion packages/relay/tests/lib/ethGetBlockBy.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import { defaultDetailedContractResults, overrideEnvsInMochaDescribe, useInMemor

use(chaiAsPromised);

const logger = pino();
const logger = pino({ level: 'silent' });
const registry = new Registry();

let restMock: MockAdapter;
Expand Down
41 changes: 22 additions & 19 deletions packages/relay/tests/lib/hapiService.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import { ConfigService } from '@hashgraph/json-rpc-config-service/dist/services';
import { Client } from '@hashgraph/sdk';
import { expect } from 'chai';
import EventEmitter from 'events';
import { EventEmitter } from 'events';
import pino from 'pino';
import { register, Registry } from 'prom-client';

Expand All @@ -37,7 +37,7 @@ import { RequestDetails } from '../../src/lib/types';
import { overrideEnvsInMochaDescribe, withOverriddenEnvsInMochaTest } from '../helpers';

const registry = new Registry();
const logger = pino();
const logger = pino({ level: 'silent' });

describe('HAPI Service', async function () {
this.timeout(20000);
Expand Down Expand Up @@ -84,45 +84,49 @@ describe('HAPI Service', async function () {

withOverriddenEnvsInMochaTest({ HAPI_CLIENT_TRANSACTION_RESET: 2 }, () => {
it('should be able to reinitialise SDK instance upon reaching transaction limit', async function () {
const hapiClientTransactionReset = Number(ConfigService.get('HAPI_CLIENT_TRANSACTION_RESET'));

hapiService = new HAPIService(logger, registry, cacheService, eventEmitter, hbarLimitService);
expect(hapiService.getTransactionCount()).to.eq(parseInt(ConfigService.get('HAPI_CLIENT_TRANSACTION_RESET')!));
expect(hapiService.getTransactionCount()).to.eq(hapiClientTransactionReset);

const oldClientInstance = hapiService.getMainClientInstance();
let oldSDKInstance = hapiService.getSDKClient(); // decrease transaction limit by taking the instance
oldSDKInstance = hapiService.getSDKClient(); // decrease transaction limit by taking the instance
hapiService.getSDKClient(); // decrease transaction limit by taking the instance
const oldSDKInstance = hapiService.getSDKClient(); // decrease transaction limit by taking the instance
expect(hapiService.getTransactionCount()).to.eq(0);
const newSDKInstance = hapiService.getSDKClient();
const newClientInstance = hapiService.getMainClientInstance();

expect(oldSDKInstance).to.not.be.equal(newSDKInstance);
expect(oldClientInstance).to.not.be.equal(newClientInstance);
expect(hapiService.getTransactionCount()).to.eq(
parseInt(ConfigService.get('HAPI_CLIENT_TRANSACTION_RESET')!) - 1,
); // one less because we took the instance once and decreased the counter
expect(hapiService.getTransactionCount()).to.eq(hapiClientTransactionReset - 1); // one less because we took the instance once and decreased the counter
});
});

withOverriddenEnvsInMochaTest({ HAPI_CLIENT_DURATION_RESET: 100 }, () => {
it('should be able to reinitialise SDK instance upon reaching time limit', async function () {
const hapiClientDurationReset = Number(ConfigService.get('HAPI_CLIENT_DURATION_RESET'));

hapiService = new HAPIService(logger, registry, cacheService, eventEmitter, hbarLimitService);
expect(hapiService.getTimeUntilReset()).to.eq(parseInt(ConfigService.get('HAPI_CLIENT_DURATION_RESET')!));
expect(hapiService.getTimeUntilReset()).to.be.approximately(hapiClientDurationReset, 10); // 10 ms tolerance

const oldClientInstance = hapiService.getMainClientInstance();
await new Promise((r) => setTimeout(r, 200)); // await to reach time limit
const oldSDKInstance = hapiService.getSDKClient();
const newSDKInstance = hapiService.getSDKClient();
const newClientInstance = hapiService.getMainClientInstance();

expect(hapiService.getTimeUntilReset()).to.eq(parseInt(ConfigService.get('HAPI_CLIENT_DURATION_RESET')!));
expect(hapiService.getTimeUntilReset()).to.be.approximately(hapiClientDurationReset, 10); // 10 ms tolerance
expect(oldSDKInstance).to.not.be.equal(newSDKInstance);
expect(oldClientInstance).to.not.be.equal(newClientInstance);
});
});

withOverriddenEnvsInMochaTest({ HAPI_CLIENT_ERROR_RESET: '[50]' }, () => {
it('should be able to reinitialise SDK instance upon error status code encounter', async function () {
const hapiClientErrorReset: Array<number> = JSON.parse(ConfigService.get('HAPI_CLIENT_ERROR_RESET') as string);

hapiService = new HAPIService(logger, registry, cacheService, eventEmitter, hbarLimitService);
expect(hapiService.getErrorCodes()[0]).to.eq(JSON.parse(ConfigService.get('HAPI_CLIENT_ERROR_RESET')!)[0]);
expect(hapiService.getErrorCodes()[0]).to.eq(hapiClientErrorReset[0]);

const oldClientInstance = hapiService.getMainClientInstance();
const oldSDKInstance = hapiService.getSDKClient();
Expand All @@ -132,7 +136,7 @@ describe('HAPI Service', async function () {

expect(oldSDKInstance).to.not.be.equal(newSDKInstance);
expect(oldClientInstance).to.not.be.equal(newClientInstance);
expect(hapiService.getErrorCodes()[0]).to.eq(JSON.parse(ConfigService.get('HAPI_CLIENT_ERROR_RESET')!)[0]);
expect(hapiService.getErrorCodes()[0]).to.eq(hapiClientErrorReset[0]);
});
});

Expand All @@ -144,20 +148,19 @@ describe('HAPI Service', async function () {
},
() => {
it('should be able to reset all counter upon reinitialization of the SDK Client', async function () {
const hapiClientTransactionReset = Number(ConfigService.get('HAPI_CLIENT_TRANSACTION_RESET'));
const hapiClientDurationReset = Number(ConfigService.get('HAPI_CLIENT_DURATION_RESET'));

hapiService = new HAPIService(logger, registry, cacheService, eventEmitter, hbarLimitService);

expect(hapiService.getErrorCodes()[0]).to.eq(JSON.parse(ConfigService.get('HAPI_CLIENT_ERROR_RESET')!)[0]);
const oldClientInstance = hapiService.getMainClientInstance();
const oldSDKInstance = hapiService.getSDKClient();
hapiService.decrementErrorCounter(errorStatus);
const newSDKInstance = hapiService.getSDKClient();
const newClientInstance = hapiService.getMainClientInstance();

expect(hapiService.getTimeUntilReset()).to.eq(parseInt(ConfigService.get('HAPI_CLIENT_DURATION_RESET')!));
expect(hapiService.getErrorCodes()[0]).to.eq(JSON.parse(ConfigService.get('HAPI_CLIENT_ERROR_RESET')!)[0]);
expect(hapiService.getTransactionCount()).to.eq(
parseInt(ConfigService.get('HAPI_CLIENT_TRANSACTION_RESET')!) - 1,
); // one less because we took the instance once and decreased the counter
expect(hapiService.getTimeUntilReset()).to.be.approximately(hapiClientDurationReset, 10); // 10 ms tolerance
expect(hapiService.getTransactionCount()).to.eq(hapiClientTransactionReset - 1); // one less because we took the instance once and decreased the counter
expect(oldSDKInstance).to.not.be.equal(newSDKInstance);
expect(oldClientInstance).to.not.be.equal(newClientInstance);
});
Expand Down Expand Up @@ -204,7 +207,7 @@ describe('HAPI Service', async function () {
() => {
it('should not be able to reinitialise and decrement counters, if it is disabled', async function () {
hapiService = new HAPIService(logger, registry, cacheService, eventEmitter, hbarLimitService);
expect(hapiService.getTransactionCount()).to.eq(parseInt(ConfigService.get('HAPI_CLIENT_TRANSACTION_RESET')!));
expect(hapiService.getTransactionCount()).to.eq(Number(ConfigService.get('HAPI_CLIENT_TRANSACTION_RESET')));

const oldClientInstance = hapiService.getMainClientInstance();
const oldSDKInstance = hapiService.getSDKClient();
Expand Down
31 changes: 13 additions & 18 deletions packages/relay/tests/lib/mirrorNodeClient.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,27 @@
*/

import { ConfigService } from '@hashgraph/json-rpc-config-service/dist/services';
import { expect } from 'chai';
import { Registry } from 'prom-client';
import { MirrorNodeClient } from '../../src/lib/clients';
import constants from '../../src/lib/constants';
import axios, { AxiosInstance } from 'axios';
import MockAdapter from 'axios-mock-adapter';
import { getRequestId, mockData, random20BytesAddress, withOverriddenEnvsInMochaTest } from '../helpers';
import pino from 'pino';
import { BigNumber } from 'bignumber.js';
import { expect } from 'chai';
import { ethers } from 'ethers';
import pino from 'pino';
import { Registry } from 'prom-client';

import { MirrorNodeClientError, predefined } from '../../src';
import { MirrorNodeClient } from '../../src/lib/clients';
import constants from '../../src/lib/constants';
import { SDKClientError } from '../../src/lib/errors/SDKClientError';
import { CacheService } from '../../src/lib/services/cacheService/cacheService';

const registry = new Registry();
import { MirrorNodeTransactionRecord, RequestDetails } from '../../src/lib/types';
import { SDKClientError } from '../../src/lib/errors/SDKClientError';
import { BigNumber } from 'bignumber.js';

const logger = pino();
const noTransactions = '?transactions=false';
const requestDetails = new RequestDetails({ requestId: getRequestId(), ipAddress: '0.0.0.0' });
import { mockData, random20BytesAddress, withOverriddenEnvsInMochaTest } from '../helpers';

describe('MirrorNodeClient', async function () {
this.timeout(20000);

const registry = new Registry();
const logger = pino();
const logger = pino({ level: 'silent' });
const noTransactions = '?transactions=false';
const requestDetails = new RequestDetails({ requestId: 'mirrorNodeClientTest', ipAddress: '0.0.0.0' });

Expand Down Expand Up @@ -83,7 +78,7 @@ describe('MirrorNodeClient', async function () {

for (const code of nullResponseCodes) {
it(`returns null when ${code} is returned`, async () => {
let error = new Error('test error');
const error = new Error('test error');
error['response'] = 'test error';

const result = mirrorNodeInstance.handleError(
Expand All @@ -101,7 +96,7 @@ describe('MirrorNodeClient', async function () {
for (const code of errorRepsonseCodes) {
it(`throws an error when ${code} is returned`, async () => {
try {
let error = new Error('test error');
const error = new Error('test error');
error['response'] = 'test error';
mirrorNodeInstance.handleError(
error,
Expand Down Expand Up @@ -1558,7 +1553,7 @@ describe('MirrorNodeClient', async function () {

it('should fetch contract for existing contract from cache on additional calls', async () => {
mock.onGet(contractPath).reply(200, mockData.contract);
let id = await mirrorNodeInstance.getContractId(evmAddress, requestDetails);
const id = await mirrorNodeInstance.getContractId(evmAddress, requestDetails);
expect(id).to.exist;
expect(id).to.be.equal(mockData.contract.contract_id);

Expand Down
7 changes: 4 additions & 3 deletions packages/relay/tests/lib/net.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,15 @@
*/

import { ConfigService } from '@hashgraph/json-rpc-config-service/dist/services';
import pino from 'pino';
import { expect } from 'chai';
import pino from 'pino';
import { Registry } from 'prom-client';
import { RelayImpl } from '../../src/lib/relay';

import constants from '../../src/lib/constants';
import { RelayImpl } from '../../src/lib/relay';
import { withOverriddenEnvsInMochaTest } from '../helpers';

const logger = pino();
const logger = pino({ level: 'silent' });
let Relay;

describe('Net', async function () {
Expand Down
2 changes: 1 addition & 1 deletion packages/relay/tests/lib/openrpc.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ import {
} from '../helpers';
import { CONTRACT_RESULT_MOCK, NOT_FOUND_RES } from './eth/eth-config';

const logger = pino();
const logger = pino({ level: 'silent' });
const registry = new Registry();
const Relay = new RelayImpl(logger, registry);

Expand Down
2 changes: 1 addition & 1 deletion packages/relay/tests/lib/precheck.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ import { ONE_TINYBAR_IN_WEI_HEX } from './eth/eth-config';
const registry = new Registry();
import { RequestDetails } from '../../src/lib/types';

const logger = pino();
const logger = pino({ level: 'silent' });
const limitOrderPostFix = '?order=desc&limit=1';
const transactionsPostFix = '?transactions=false';

Expand Down
Loading

0 comments on commit 8b3d4bf

Please sign in to comment.