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

Merge Prod Release into Master #57

Open
wants to merge 3 commits into
base: master
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
3,068 changes: 3,045 additions & 23 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,9 +44,10 @@
"tools-setup": "echo 'nothing to do for now'"
},
"dependencies": {
"@aws-sdk/client-eventbridge": "3.556.0",
"@aws-sdk/client-secrets-manager": "3.556.0",
"@azure/msal-node": "1.14.6",
"aws-lambda": "1.0.6",
"aws-sdk": "2.1354.0",
"axios": "0.25.0",
"axios-observable": "1.3.0",
"dateformat": "4.6.3",
Expand All @@ -73,6 +74,8 @@
"@types/supertest": "2.0.10",
"@typescript-eslint/eslint-plugin": "5.3.1",
"@typescript-eslint/parser": "5.3.1",
"aws-sdk-client-mock": "4.0.0",
"aws-sdk-client-mock-jest": "4.0.0",
"commitlint-plugin-function-rules": "1.1.20",
"concurrently": "6.3.0",
"cross-env": "7.0.3",
Expand Down
1 change: 1 addition & 0 deletions src/crm/DynamicsTestStation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ interface DynamicsTestStation {
address1_postalcode: string;
dvsa_accountstatus: number;
address1_city: string;
address1_country: string;
dvsa_testfacilitytype: number;
modifiedon: string;
}
Expand Down
1 change: 1 addition & 0 deletions src/crm/DynamoTestStation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ interface DynamoTestStation {
testStationPostcode: string;
testStationStatus: string;
testStationTown: string;
testStationCountry: string;
testStationType: string;
}

Expand Down
4 changes: 3 additions & 1 deletion src/crm/getTestStation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ const TestStationType = new Map<number, string>([
[147160001, 'gvts'],
[147160002, 'potf'],
[147160003, 'hq'],
[147160004, 'vef'],
]);

const TestStationStatus = new Map<number, string>([
Expand Down Expand Up @@ -53,6 +54,7 @@ export function mapToDynamoTestStation(obj: DynamicsTestStation): DynamoTestStat
testStationPostcode: obj.address1_postalcode,
testStationStatus: TestStationStatus.get(obj.dvsa_accountstatus),
testStationTown: obj.address1_city,
testStationCountry: obj.address1_country,
testStationType: TestStationType.get(obj.dvsa_testfacilitytype),
};
}
Expand All @@ -62,7 +64,7 @@ export const getTestStations = async (date: Date): Promise<DynamoTestStation[]>

const modifiedOnDate: string = dateFormat(date, 'yyyy-mm-dd');

const filteredUrl = `${ceUrl}/accounts/?$select=accountid,address1_line1,address1_line2,telephone1,dvsa_openingtimes,address1_longitude,address1_latitude,name,dvsa_premisecodes,address1_postalcode,dvsa_accountstatus,address1_city,dvsa_testfacilitytype,modifiedon&$filter=modifiedon%20ge%20${modifiedOnDate}%20and%20dvsa_accounttype%20eq%20100000000`;
const filteredUrl = `${ceUrl}/accounts/?$select=accountid,address1_line1,address1_line2,telephone1,dvsa_openingtimes,address1_longitude,address1_latitude,name,dvsa_premisecodes,address1_postalcode,dvsa_accountstatus,address1_city,address1_country,dvsa_testfacilitytype,modifiedon&$filter=modifiedon%20ge%20${modifiedOnDate}%20and%20dvsa_accounttype%20eq%20100000000`;

const runAccounts = async (): Promise<DynamicsTestStation[]> => {
logger.info(`Trying to get test stations informations modified since: ${modifiedOnDate}`);
Expand Down
7 changes: 4 additions & 3 deletions src/eventbridge/send.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { EventBridge } from 'aws-sdk';
import { EventBridgeClient, PutEventsCommand } from '@aws-sdk/client-eventbridge';
import { EventEntry } from './EventEntry';
import { Entries } from './Entries';
import { SendResponse } from './SendResponse';
import logger from '../observability/logger';
import { DynamoTestStation } from '../crm/DynamoTestStation';
import config from '../config';

const eventbridge = new EventBridge();
const eventBridge = new EventBridgeClient();
const sendModifiedTestStations = async (testStations: DynamoTestStation[]): Promise<SendResponse> => {
logger.info('sendModifiedTestStations starting');
logger.info(
Expand Down Expand Up @@ -37,8 +37,9 @@ const sendModifiedTestStations = async (testStations: DynamoTestStation[]): Prom
};

logger.debug(`test station event about to be sent: ${JSON.stringify(params)}`);
const command = new PutEventsCommand(params);
// eslint-disable-next-line no-await-in-loop
await eventbridge.putEvents(params).promise();
await eventBridge.send(command);
sendResponse.SuccessCount++;
} catch (error) {
logger.error('', error);
Expand Down
10 changes: 7 additions & 3 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { SecretsManager } from 'aws-sdk';
import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager';
import logger from '../observability/logger';

const getSecret = async (secretName: string): Promise<string> => {
logger.debug('getSecret starting.');
const secretsManager = new SecretsManager();
const secretValue = await secretsManager.getSecretValue({ SecretId: secretName }).promise();
const secretsManager = new SecretsManagerClient();
const secretValue = await secretsManager.send(
new GetSecretValueCommand({
SecretId: secretName,
}),
);
logger.debug('getSecret finishing.');
return secretValue.SecretString;
};
Expand Down
37 changes: 14 additions & 23 deletions tests/integration/handler.intTest.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,19 @@
import axios from 'axios-observable';
import { of } from 'rxjs';
import MockDate from 'mockdate';
import { mockClient } from 'aws-sdk-client-mock';
import { GetSecretValueCommand, SecretsManagerClient } from '@aws-sdk/client-secrets-manager';
import { EventBridgeClient, PutEventsCommand } from '@aws-sdk/client-eventbridge';
import 'aws-sdk-client-mock-jest';
import { handler } from '../../src/handler';
import { MOCK_DYNAMICS_ACCOUNTS_RESPONSE } from './data/mockDynamicsAccountsResponse';
import { MOCK_DYNAMICS_CONNECTIONS_RESPONSE } from './data/mockDynamicsConnectionsResponse';
import { GetExpectedEvent } from './data/mockEventBridgeEvents';

// mock the external resources
// AWS
const putEventsFn = jest.fn();
jest.mock('aws-sdk', () => ({
SecretsManager: jest.fn().mockImplementation(() => ({
getSecretValue: jest.fn().mockImplementation(() => ({
promise: jest.fn().mockResolvedValue({}),
})),
})),
EventBridge: jest.fn().mockImplementation(() => ({
putEvents: jest.fn().mockImplementation((params: unknown) => {
putEventsFn(params); // allows us to test the event payload
return {
promise: jest.fn(),
};
}),
})),
}));
const mockSecretManager = mockClient(SecretsManagerClient);
const mockEventBridge = mockClient(EventBridgeClient);
mockSecretManager.on(GetSecretValueCommand).resolves({ SecretString: '123' });
mockEventBridge.on(PutEventsCommand).resolves({});

// MSAL (Azure AD) Token Authentication Request
jest.mock('@azure/msal-node', () => ({
Expand Down Expand Up @@ -56,11 +46,12 @@ describe('Handler integration test', () => {
// eslint-disable-next-line @typescript-eslint/unbound-method
await new Promise(process.nextTick);

expect(callback).toHaveBeenCalledWith(null, 'Data processed successfully; good: 3, bad: 0');
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
expect(callback.mock.calls[0][1]).toBe('Data processed successfully; good: 3, bad: 0');

expect(putEventsFn).toHaveBeenCalledTimes(3);
expect(putEventsFn).toHaveBeenNthCalledWith(1, GetExpectedEvent(1));
expect(putEventsFn).toHaveBeenNthCalledWith(2, GetExpectedEvent(2));
expect(putEventsFn).toHaveBeenNthCalledWith(3, GetExpectedEvent(3));
expect(mockEventBridge).toHaveReceivedCommandTimes(PutEventsCommand, 3);
expect(mockEventBridge).toHaveReceivedNthCommandWith(1, PutEventsCommand, GetExpectedEvent(1));
expect(mockEventBridge).toHaveReceivedNthCommandWith(2, PutEventsCommand, GetExpectedEvent(2));
expect(mockEventBridge).toHaveReceivedNthCommandWith(3, PutEventsCommand, GetExpectedEvent(3));
});
});
4 changes: 4 additions & 0 deletions tests/unit/dynamicsWebApi.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ describe('dynamicsWebApi', () => {
address1_postalcode: 'string',
dvsa_accountstatus: 147160001,
address1_city: 'string',
address1_country: 'string',
dvsa_testfacilitytype: 147160000,
modifiedon: '',
},
Expand All @@ -47,6 +48,7 @@ describe('dynamicsWebApi', () => {
address1_postalcode: 'string',
dvsa_accountstatus: 147160001,
address1_city: 'string',
address1_country: 'string',
dvsa_testfacilitytype: 147160000,
modifiedon: '',
},
Expand Down Expand Up @@ -126,6 +128,7 @@ describe('dynamicsWebApi', () => {
address1_postalcode: 'string',
dvsa_accountstatus: 147160001,
address1_city: 'string',
address1_country: 'string',
dvsa_testfacilitytype: 147160000,
modifiedon: '',
},
Expand All @@ -145,6 +148,7 @@ describe('dynamicsWebApi', () => {
address1_postalcode: 'string',
dvsa_accountstatus: 147160001,
address1_city: 'string',
address1_country: 'string',
dvsa_testfacilitytype: 147160000,
modifiedon: '',
},
Expand Down
3 changes: 2 additions & 1 deletion tests/unit/getTestStation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,7 @@ const MOCK_BAD_ACCOUNTS_DATA: DynamicsTestStation = {
address1_postalcode: 'string',
dvsa_accountstatus: 147160001,
address1_city: 'string',
address1_country: 'string',
dvsa_testfacilitytype: 1471600,
modifiedon: '',
};
Expand Down Expand Up @@ -265,7 +266,7 @@ describe('getTestStation', () => {
config.crm.ceBaseUrl = 'http://testapi';
await getTestStations(new Date('2020-10-21'));
expect(spy).toHaveBeenCalledWith(
'http://testapi/accounts/?$select=accountid,address1_line1,address1_line2,telephone1,dvsa_openingtimes,address1_longitude,address1_latitude,name,dvsa_premisecodes,address1_postalcode,dvsa_accountstatus,address1_city,dvsa_testfacilitytype,modifiedon&$filter=modifiedon%20ge%202020-10-21%20and%20dvsa_accounttype%20eq%20100000000',
'http://testapi/accounts/?$select=accountid,address1_line1,address1_line2,telephone1,dvsa_openingtimes,address1_longitude,address1_latitude,name,dvsa_premisecodes,address1_postalcode,dvsa_accountstatus,address1_city,address1_country,dvsa_testfacilitytype,modifiedon&$filter=modifiedon%20ge%202020-10-21%20and%20dvsa_accounttype%20eq%20100000000',
);
});

Expand Down
39 changes: 11 additions & 28 deletions tests/unit/send.test.ts
Original file line number Diff line number Diff line change
@@ -1,43 +1,26 @@
import { EventBridge, Request } from 'aws-sdk';
import { mocked } from 'ts-jest/utils';
import { PutEventsResponse, PutEventsRequest, PutEventsResultEntry } from 'aws-sdk/clients/eventbridge';
import {
EventBridgeClient, PutEventsCommand, PutEventsCommandInput, PutEventsCommandOutput, PutEventsResultEntry,
} from '@aws-sdk/client-eventbridge';
import { mockClient } from 'aws-sdk-client-mock';
import { sendModifiedTestStations } from '../../src/eventbridge/send';
import { SendResponse } from '../../src/eventbridge/SendResponse';
import { DynamoTestStation } from '../../src/crm/DynamoTestStation';

jest.mock('aws-sdk', () => {
const mEventBridgeInstance = {
putEvents: jest.fn(),
};
const mRequestInstance = {
promise: jest.fn(),
};
const mEventBridge = jest.fn(() => mEventBridgeInstance);
const mRequest = jest.fn(() => mRequestInstance);

return { EventBridge: mEventBridge, Request: mRequest };
});

type PutEventsWithParams = (params: PutEventsRequest) => AWS.Request<PutEventsResponse, AWS.AWSError>;

const mEventBridgeInstance = new EventBridge();
const mResultInstance = new Request<PutEventsResponse, AWS.AWSError>(null, null);
// eslint-disable-next-line @typescript-eslint/unbound-method
mocked(mEventBridgeInstance.putEvents as PutEventsWithParams).mockImplementation(
(params: PutEventsRequest): AWS.Request<PutEventsResponse, AWS.AWSError> => {
const mPutEventsResponse: PutEventsResponse = {
const mockEventBridge = mockClient(EventBridgeClient);
mockEventBridge.on(PutEventsCommand).callsFake(
(params: PutEventsCommandInput): PutEventsCommandOutput => {
const mPutEventsResponse: PutEventsCommandOutput = {
FailedEntryCount: 0,
Entries: Array<PutEventsResultEntry>(params.Entries.length),
$metadata: undefined,
};
if (params.Entries[0].Detail === JSON.stringify({ testStationId: 'Error', testStationName: 'Error' })) {
mResultInstance.promise = jest.fn().mockReturnValue(Promise.reject(new Error('Oh no!')));
throw new Error('Oh no!');
} else {
mResultInstance.promise = jest.fn().mockReturnValue(Promise.resolve(mPutEventsResponse));
return mPutEventsResponse;
}
return mResultInstance;
},
);

describe('Send events', () => {
describe('Events sent', () => {
it('GIVEN one event to send WHEN sent THEN one event is returned.', async () => {
Expand Down
Loading