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

fix: test timeouts on simulator tests #11804

Merged
merged 1 commit into from
Jan 18, 2023
Merged
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
55 changes: 28 additions & 27 deletions packages/amplify-cli/src/__tests__/utils/encrypt-buffer.test.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,35 @@
import { encryptBuffer, encryptKey } from '../../commands/helpers/encryption-helpers'
import { encryptBuffer, encryptKey } from '../../commands/helpers/encryption-helpers';
import { v4 } from 'uuid';
import crypto from 'crypto'
describe("encryption helper", () => {
it("tests encryption helper", async() =>{
const originalKey = v4();
const plainText = crypto.randomBytes(10);
const encryptedText = await encryptBuffer(plainText, originalKey);
const bData = Buffer.from(encryptedText, 'base64');
import crypto from 'crypto';
describe('encryption helper', () => {
it('tests encryption helper', async () => {
const originalKey = v4();
const plainText = crypto.randomBytes(10);
const encryptedText = await encryptBuffer(plainText, originalKey);
const bData = Buffer.from(encryptedText, 'base64');

// convert data to buffers
const salt = bData.slice(0, 64);
const iv = bData.slice(64, 80);
const tag = bData.slice(80, 96);
const text = bData.slice(96);
// convert data to buffers
const salt = bData.slice(0, 64);
const iv = bData.slice(64, 80);
const tag = bData.slice(80, 96);
const text = bData.slice(96);

const masterkey = Buffer.from(originalKey, 'utf-8');
const masterkey = Buffer.from(originalKey, 'utf-8');

// derive key using; 32 byte key length
const key = crypto.pbkdf2Sync(masterkey, salt , 2145, 32, 'sha512');
// derive key using; 32 byte key length
const key = crypto.pbkdf2Sync(masterkey, salt, 2145, 32, 'sha512');

// AES 256 GCM Mode
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);
// AES 256 GCM Mode
const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(tag);

// encrypt the given text
const decrypted = decipher.update(text, 'binary', 'utf8') + decipher.final('utf8');
expect(decrypted).toEqual(plainText.toString('utf8'));
});
// encrypt the given text
const decrypted = decipher.update(text, 'binary', 'utf8') + decipher.final('utf8');
expect(decrypted).toEqual(plainText.toString('utf8'));
});

it("test encryption key", async () => {
expect(await encryptKey(v4())).toBeTruthy();
})
})
it('test encryption key', async () => {
jest.setTimeout(10000);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

this is the meaningful change

expect(await encryptKey(v4())).toBeTruthy();
});
});
4 changes: 2 additions & 2 deletions packages/amplify-dynamodb-simulator/__test__/index.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const ddbSimulator = require('..');
const fs = require('fs-extra');

jest.setTimeout(90 * 1000);
jest.mock('amplify-cli-core', () => ({
pathManager: {
getAmplifyPackageLibDirPath: jest.fn().mockReturnValue('./'),
Expand Down Expand Up @@ -41,8 +42,7 @@ describe('emulator operations', () => {
if (fs.existsSync(dbPath)) {
try {
fs.removeSync(dbPath);
}
catch(err) {
} catch (err) {
console.log(err);
}
}
Expand Down
71 changes: 38 additions & 33 deletions packages/amplify-opensearch-simulator/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,20 @@ import { v4 } from 'uuid';
import execa from 'execa';

jest.mock('execa');
jest.setTimeout(90 * 1000);
Copy link
Contributor Author

Choose a reason for hiding this comment

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

this is the meaningful change

const execaMock = execa as jest.MockedFunction<typeof execa>;
(execaMock as any).mockImplementation(async () => ({ stdout: 'mock-process-output' }));

jest.mock('amplify-cli-core', () => ({
...(jest.requireActual('amplify-cli-core') as {}),
pathManager: {
getAmplifyPackageLibDirPath: jest.fn().mockReturnValue('mock-path-to-lib'),
}
},
}));

describe('emulator operations', () => {
const getMockSearchableFolder = (): string => {
let pathToSearchableMockResources = join(__dirname, '..', '..', 'resources', );
let pathToSearchableMockResources = join(__dirname, '..', '..', 'resources');

Check warning

Code scanning / CodeQL

Useless assignment to local variable

The initial value of pathToSearchableMockResources is unused, since it is always overwritten.
do {
pathToSearchableMockResources = join('/tmp', `amplify-cli-opensearch-emulator-${v4()}`, 'mock-api-resources', 'searchable');
} while (fs.existsSync(pathToSearchableMockResources));
Expand All @@ -37,14 +38,14 @@ describe('emulator operations', () => {
nodeName: 'mock-opensearch-node-local',
port: 9600,
type: 'single-node',
version: '1.3.0'
version: '1.3.0',
};
const openSearchClusterDefaultOptions = {
clusterName: 'opensearch-cluster',
nodeName: 'opensearch-node-local',
port: 9200,
type: 'single-node',
version: '1.3.0'
version: '1.3.0',
};
const ensureMockSearchableResourcePath = () => {
fs.ensureDirSync(mockSearchableResourcePath);
Expand All @@ -58,9 +59,11 @@ describe('emulator operations', () => {
jest.setTimeout(5 * 60 * 1000);
jest.resetModules();
jest.spyOn(openpgp, 'verify').mockReturnValueOnce({
signatures: [{
verified: Promise.resolve(true)
}]
signatures: [
{
verified: Promise.resolve(true),
},
],
} as $TSAny);
});

Expand All @@ -76,16 +79,16 @@ describe('emulator operations', () => {
const fetchURL = async (url: string): Promise<string> => {
return new Promise((resolve, reject) => {
http
.get(url, (resp) => {
let data = "";
resp.on("data", (chunk) => {
.get(url, resp => {
let data = '';
resp.on('data', chunk => {
data += chunk;
});
resp.on("end", () => {
resp.on('end', () => {
resolve(data);
});
})
.on("error", (err) => {
.on('error', err => {
reject(err);
});
});
Expand All @@ -104,27 +107,27 @@ describe('emulator operations', () => {
it('correctly resolves the path to local opensearch binary', async () => {
const relativePathFromMockSearchableResourceDir = await openSearchEmulator.getPathToOpenSearchBinary();
expect(relativePathFromMockSearchableResourceDir).toEqual(join('opensearchLib', 'bin', 'opensearch'));

const fullPathToOpenSearchBinary = await openSearchEmulator.getPathToOpenSearchBinary(mockSearchableResourcePath);
expect(fullPathToOpenSearchBinary).toEqual(join(mockSearchableResourcePath, 'opensearchLib', 'bin', 'opensearch'));
});

it('skips downloading another opensearch binary when one is locally available', async () => {
const openSearchExists = await openSearchEmulator.openSearchLocalExists(mockSearchableResourcePath);
// returns false when there is no local binary
expect(openSearchExists).toEqual(false);

const nodeFetch = await import('node-fetch');
jest.mock('node-fetch', ()=>jest.fn());
jest.mock('node-fetch', () => jest.fn());
expect(nodeFetch).toBeCalledTimes(0);
});

it('correctly generates opensearch args from given options', async () => {
const resolvedBuildArgs = openSearchEmulator.buildArgs(openSearchClusterOptions, pathToSearchableData);
const expectedCall = `-Ecluster.name=${openSearchClusterOptions.clusterName} -Enode.name=${openSearchClusterOptions.nodeName} -Ehttp.port=${openSearchClusterOptions.port} -Ediscovery.type=${openSearchClusterOptions.type} -Epath.data=${pathToSearchableData}`;
expect(resolvedBuildArgs.join(' ')).toEqual(expectedCall);
});

it('throws error if max re-tries is breached', async () => {
try {
await openSearchEmulator.launch(mockSearchableResourcePath, {}, 5);
Expand All @@ -139,16 +142,17 @@ describe('emulator operations', () => {
jest.spyOn(openSearchEmulator, 'startOpensearchEmulator').mockReturnValueOnce(Promise.resolve(undefined));
try {
await openSearchEmulator.launch(pathToSearchableData);
} catch(err) {
} catch (err) {
expect(execaMock).toBeCalledWith(
"opensearchLib/bin/opensearch",
[ `-Ecluster.name=${openSearchClusterDefaultOptions.clusterName}`,
`-Enode.name=${openSearchClusterDefaultOptions.nodeName}`,
`-Ehttp.port=${openSearchClusterDefaultOptions.port}`,
'opensearchLib/bin/opensearch',
[
`-Ecluster.name=${openSearchClusterDefaultOptions.clusterName}`,
`-Enode.name=${openSearchClusterDefaultOptions.nodeName}`,
`-Ehttp.port=${openSearchClusterDefaultOptions.port}`,
`-Ediscovery.type=${openSearchClusterDefaultOptions.type}`,
`-Epath.data=${pathToSearchableData}`
],
{ "cwd": pathToSearchableLocal }
`-Epath.data=${pathToSearchableData}`,
],
{ cwd: pathToSearchableLocal },
);
expect(err?.message).toEqual(startupErrorMessage);
}
Expand All @@ -159,16 +163,17 @@ describe('emulator operations', () => {
jest.spyOn(openSearchEmulator, 'startOpensearchEmulator').mockReturnValueOnce(Promise.resolve(undefined));
try {
await openSearchEmulator.launch(pathToSearchableData, openSearchClusterOptions);
} catch(err) {
} catch (err) {
expect(execaMock).toBeCalledWith(
"opensearchLib/bin/opensearch",
[ `-Ecluster.name=${openSearchClusterOptions.clusterName}`,
`-Enode.name=${openSearchClusterOptions.nodeName}`,
`-Ehttp.port=${openSearchClusterOptions.port}`,
'opensearchLib/bin/opensearch',
[
`-Ecluster.name=${openSearchClusterOptions.clusterName}`,
`-Enode.name=${openSearchClusterOptions.nodeName}`,
`-Ehttp.port=${openSearchClusterOptions.port}`,
`-Ediscovery.type=${openSearchClusterDefaultOptions.type}`,
`-Epath.data=${pathToSearchableData}`
],
{ "cwd": pathToSearchableLocal }
`-Epath.data=${pathToSearchableData}`,
],
{ cwd: pathToSearchableLocal },
);
expect(err?.message).toEqual(startupErrorMessage);
}
Expand Down