Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

test: add helper method for overriding env variables #3022

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export class FilterService implements IFilterService {
address?: string,
topics?: any[],
requestIdPrefix?: string,
): Promise<string | JsonRpcError> {
): Promise<string> {
this.logger.trace(
`${requestIdPrefix} newFilter(fromBlock=${fromBlock}, toBlock=${toBlock}, address=${address}, topics=${topics})`,
);
Expand Down Expand Up @@ -147,7 +147,7 @@ export class FilterService implements IFilterService {
}
}

async newBlockFilter(requestIdPrefix?: string): Promise<string | JsonRpcError> {
async newBlockFilter(requestIdPrefix?: string): Promise<string> {
this.logger.trace(`${requestIdPrefix} newBlockFilter()`);
try {
FilterService.requireFiltersEnabled();
Expand Down Expand Up @@ -203,7 +203,7 @@ export class FilterService implements IFilterService {
);
}

public async getFilterChanges(filterId: string, requestIdPrefix?: string): Promise<string[] | Log[] | JsonRpcError> {
public async getFilterChanges(filterId: string, requestIdPrefix?: string): Promise<string[] | Log[]> {
this.logger.trace(`${requestIdPrefix} getFilterChanges(${filterId})`);
FilterService.requireFiltersEnabled();

Expand Down
46 changes: 46 additions & 0 deletions packages/relay/tests/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -921,6 +921,52 @@ export const stopRedisInMemoryServer = async (
process.env.REDIS_URL = envsToReset.REDIS_URL;
};

/**
* Overrides an environment variable in the provided {@link NodeJS.Dict} object.
*
* @param {NodeJS.Dict<string>} object - The object containing the environment variables.
* @param {string} key - The key of the environment variable to override.
* @param {string | undefined} value - The value to set the environment variable to.
*/
export const overrideEnv = (object: NodeJS.Dict<string>, key: string, value: string | undefined) => {
if (value === undefined) {
delete object[key];
} else {
object[key] = value;
}
};

/**
* Overrides environment variables for the duration of the provided tests.
*
* @param {NodeJS.Dict<string>} envs - An object containing key-value pairs of environment variables to set.
* @param {Function} tests - A function containing the tests to run with the overridden environment variables.
*/
export const withOverriddenEnvs = (envs: NodeJS.Dict<string>, tests: () => void) => {
const overriddenEnvs = Object.entries(envs)
.map(([key, value]) => `${key}=${value}`)
.join(', ');

describe(`given ${overriddenEnvs} are set`, () => {
let envsToReset: NodeJS.Dict<string> = {};

before(() => {
for (const key in envs) {
envsToReset[key] = process.env[key];
overrideEnv(process.env, key, envs[key]);
}
});

tests();

after(() => {
Comment on lines +953 to +962
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe mocha allows the user to have multiple before and after. Maybe we could use a smaller wrapper that only invokes before and after to set only 1 env variable. I guess this way might be more composable. What do you think?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's true and the tests() method that is passed can also include before, beforeEach, afterEach, and after in addition to it and describe declarations, I don't see a problem with there being other before and after called inside.

I am not sure what you mean, could you maybe give some examples?

for (const key in envsToReset) {
overrideEnv(process.env, key, envsToReset[key]);
}
});
});
};
Comment on lines +924 to +968
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking something like this (and for each env var you want to modify you need to call this method in the test)

Suggested change
/**
* Overrides an environment variable in the provided {@link NodeJS.Dict} object.
*
* @param {NodeJS.Dict<string>} object - The object containing the environment variables.
* @param {string} key - The key of the environment variable to override.
* @param {string | undefined} value - The value to set the environment variable to.
*/
export const overrideEnv = (object: NodeJS.Dict<string>, key: string, value: string | undefined) => {
if (value === undefined) {
delete object[key];
} else {
object[key] = value;
}
};
/**
* Overrides environment variables for the duration of the provided tests.
*
* @param {NodeJS.Dict<string>} envs - An object containing key-value pairs of environment variables to set.
* @param {Function} tests - A function containing the tests to run with the overridden environment variables.
*/
export const withOverriddenEnvs = (envs: NodeJS.Dict<string>, tests: () => void) => {
const overriddenEnvs = Object.entries(envs)
.map(([key, value]) => `${key}=${value}`)
.join(', ');
describe(`given ${overriddenEnvs} are set`, () => {
let envsToReset: NodeJS.Dict<string> = {};
before(() => {
for (const key in envs) {
envsToReset[key] = process.env[key];
overrideEnv(process.env, key, envs[key]);
}
});
tests();
after(() => {
for (const key in envsToReset) {
overrideEnv(process.env, key, envsToReset[key]);
}
});
});
};
export const overriddeEnv = (key: string, value: string | undefined) => {
let prevValue: string | undefined;
before(() => {
prevValue = process.env[key];
process.env[key] = value;
});
after(() => {
if (prevValue === undefined) {
delete process.env[key];
} else {
process.env[key] = prevValue;
}
});
};


export const estimateFileTransactionsFee = (
callDataSize: number,
fileChunkSize: number,
Expand Down
77 changes: 39 additions & 38 deletions packages/relay/tests/lib/eth/eth_call.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ import {
defaultErrorMessageText,
ethCallFailing,
mockData,
withOverriddenEnvs,
} from '../../helpers';
import { generateEthTestEnv } from './eth-helpers';
import { IContractCallRequest, IContractCallResponse } from '../../../src/lib/types/IMirrorNode';
Expand Down Expand Up @@ -138,54 +139,54 @@ describe('@ethCall Eth Call spec', async function () {
);
});

it('should execute "eth_call" against mirror node with a false ETH_CALL_DEFAULT_TO_CONSENSUS_NODE', async function () {
web3Mock.onPost('contracts/call').reply(200);
const initialEthCallConesneusFF = process.env.ETH_CALL_DEFAULT_TO_CONSENSUS_NODE;
withOverriddenEnvs({ ETH_CALL_DEFAULT_TO_CONSENSUS_NODE: 'false' }, () => {
it('should execute "eth_call" against mirror node with a false ETH_CALL_DEFAULT_TO_CONSENSUS_NODE', async function () {
web3Mock.onPost('contracts/call').reply(200);
restMock.onGet(`contracts/${defaultCallData.from}`).reply(404);
restMock.onGet(`accounts/${defaultCallData.from}${NO_TRANSACTIONS}`).reply(200, {
account: '0.0.1723',
evm_address: defaultCallData.from,
});
restMock.onGet(`contracts/${defaultCallData.to}`).reply(200, DEFAULT_CONTRACT);

process.env.ETH_CALL_DEFAULT_TO_CONSENSUS_NODE = 'false';
restMock.onGet(`contracts/${defaultCallData.from}`).reply(404);
restMock.onGet(`accounts/${defaultCallData.from}${NO_TRANSACTIONS}`).reply(200, {
account: '0.0.1723',
evm_address: defaultCallData.from,
});
restMock.onGet(`contracts/${defaultCallData.to}`).reply(200, DEFAULT_CONTRACT);
await ethImpl.call({ ...defaultCallData, gas: `0x${defaultCallData.gas.toString(16)}` }, 'latest');
await ethImpl.call({ ...defaultCallData, gas: `0x${defaultCallData.gas.toString(16)}` }, 'latest');

assert(callMirrorNodeSpy.calledOnce);
process.env.ETH_CALL_DEFAULT_TO_CONSENSUS_NODE = initialEthCallConesneusFF;
assert(callMirrorNodeSpy.calledOnce);
assert(callConsensusNodeSpy.notCalled);
});
});

it('should execute "eth_call" against mirror node with an undefined ETH_CALL_DEFAULT_TO_CONSENSUS_NODE', async function () {
web3Mock.onPost('contracts/call').reply(200);
const initialEthCallConesneusFF = process.env.ETH_CALL_DEFAULT_TO_CONSENSUS_NODE;
withOverriddenEnvs({ ETH_CALL_DEFAULT_TO_CONSENSUS_NODE: undefined }, () => {
it('should execute "eth_call" against mirror node with an undefined ETH_CALL_DEFAULT_TO_CONSENSUS_NODE', async function () {
web3Mock.onPost('contracts/call').reply(200);
restMock.onGet(`contracts/${defaultCallData.from}`).reply(404);
restMock.onGet(`accounts/${defaultCallData.from}${NO_TRANSACTIONS}`).reply(200, {
account: '0.0.1723',
evm_address: defaultCallData.from,
});
restMock.onGet(`contracts/${defaultCallData.to}`).reply(200, DEFAULT_CONTRACT);

delete process.env.ETH_CALL_DEFAULT_TO_CONSENSUS_NODE;
restMock.onGet(`contracts/${defaultCallData.from}`).reply(404);
restMock.onGet(`accounts/${defaultCallData.from}${NO_TRANSACTIONS}`).reply(200, {
account: '0.0.1723',
evm_address: defaultCallData.from,
});
restMock.onGet(`contracts/${defaultCallData.to}`).reply(200, DEFAULT_CONTRACT);
await ethImpl.call({ ...defaultCallData, gas: `0x${defaultCallData.gas.toString(16)}` }, 'latest');
await ethImpl.call({ ...defaultCallData, gas: `0x${defaultCallData.gas.toString(16)}` }, 'latest');

assert(callMirrorNodeSpy.calledOnce);
process.env.ETH_CALL_DEFAULT_TO_CONSENSUS_NODE = initialEthCallConesneusFF;
assert(callMirrorNodeSpy.calledOnce);
assert(callConsensusNodeSpy.notCalled);
});
});

it('should execute "eth_call" against mirror node with a ETH_CALL_DEFAULT_TO_CONSENSUS_NODE set to true', async function () {
const initialEthCallConesneusFF = process.env.ETH_CALL_DEFAULT_TO_CONSENSUS_NODE;
withOverriddenEnvs({ ETH_CALL_DEFAULT_TO_CONSENSUS_NODE: 'true' }, () => {
it('should execute "eth_call" against consensus node with a ETH_CALL_DEFAULT_TO_CONSENSUS_NODE set to true', async function () {
restMock.onGet(`contracts/${defaultCallData.from}`).reply(404);
restMock.onGet(`accounts/${defaultCallData.from}${NO_TRANSACTIONS}`).reply(200, {
account: '0.0.1723',
evm_address: defaultCallData.from,
});
restMock.onGet(`contracts/${defaultCallData.to}`).reply(200, DEFAULT_CONTRACT);

process.env.ETH_CALL_DEFAULT_TO_CONSENSUS_NODE = 'true';
restMock.onGet(`contracts/${defaultCallData.from}`).reply(404);
restMock.onGet(`accounts/${defaultCallData.from}${NO_TRANSACTIONS}`).reply(200, {
account: '0.0.1723',
evm_address: defaultCallData.from,
});
restMock.onGet(`contracts/${defaultCallData.to}`).reply(200, DEFAULT_CONTRACT);
await ethImpl.call({ ...defaultCallData, gas: `0x${defaultCallData.gas.toString(16)}` }, 'latest');
await ethImpl.call({ ...defaultCallData, gas: `0x${defaultCallData.gas.toString(16)}` }, 'latest');

assert(callConsensusNodeSpy.calledOnce);
process.env.ETH_CALL_DEFAULT_TO_CONSENSUS_NODE = initialEthCallConesneusFF;
assert(callMirrorNodeSpy.notCalled);
assert(callConsensusNodeSpy.calledOnce);
});
});

it('to field is not a contract or token', async function () {
Expand Down
Loading
Loading