Skip to content

Commit

Permalink
chore: test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
solaris007 committed Dec 2, 2023
1 parent a6e2eb5 commit 31731ca
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 18 deletions.
30 changes: 16 additions & 14 deletions src/lhs/handler.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,15 @@ const validateContext = (config) => {
* @returns {Object} - Returns an object containing the audit data.
*/
const createAuditData = (site, psiData, psiApiBaseUrl, fullAuditRef, strategy) => {
const { categories } = psiData.lighthouseResult;
const { categories, finalUrl } = psiData.lighthouseResult;
return {
siteId: site.getId(),
auditType: `lhs-${strategy}`,
auditedAt: new Date().toISOString(),
fullAuditRef,
auditResult: {
// TODO: add content and github diff here
finalUrl,
scores: {
performance: categories.performance.score,
seo: categories.seo.score,
Expand All @@ -96,16 +97,17 @@ const createAuditData = (site, psiData, psiApiBaseUrl, fullAuditRef, strategy) =
*
* @param {Object} site - The site object containing information about the site.
* @param {Object} auditData - The audit data to be included in the message.
* @param {Object} originalMessage - The original message received for auditing.
* @returns {Object} - Returns a message object formatted for SQS.
*/
const createSQSMessage = (site, auditData, originalMessage) => ({
type: originalMessage.type,
url: originalMessage.url,
auditContext: originalMessage.auditContext,
const createSQSMessage = (site, auditData) => ({
type: auditData.auditType,
url: site.getBaseURL(),
auditContext: {
finalUrl: auditData.auditResult.finalUrl,
},
auditResult: {
siteId: site.getId(),
scores: auditData.auditResult,
scores: auditData.auditResult.scores,
},
});

Expand Down Expand Up @@ -170,13 +172,14 @@ const retrieveSite = async (dataAccess, url, log) => {
* @returns {Response} - Returns a response object with status 500.
*/
const respondWithError = (message, log, e) => {
const finalMessage = `LHS Audit Error: ${message}`;
let finalMessage = `LHS Audit Error: ${message}`;
if (e) {
finalMessage += `: ${e.message}`;
log.error(finalMessage, e);
} else {
log.error(finalMessage);
}
return new Response(message, { status: 500 });
return new Response('Internal Server Error', { status: 500, statusText: finalMessage });
};

/**
Expand Down Expand Up @@ -230,9 +233,8 @@ async function processAudit(
const auditData = createAuditData(site, psiData, psiApiBaseUrl, fullAuditRef, strategy);
await dataAccess.addAudit(auditData);

// TODO: Uncomment this once the audit result queue is ready.
// const message = createSQSMessage(site, auditData, context.message);
// await sendMessageToSQS(sqs, queueUrl, message, log);
const message = createSQSMessage(site, auditData);
await sendMessageToSQS(sqs, queueUrl, message, log);
}

/**
Expand Down Expand Up @@ -272,9 +274,9 @@ export default async function audit(message, context) {
AUDIT_RESULTS_QUEUE_URL: queueUrl,
} = context.env;

const strategy = typeToPSIStrategy(type);

try {
const strategy = typeToPSIStrategy(type);

if (!validateContext({
dataAccess, psiApiBaseUrl, queueUrl, sqs,
})) {
Expand Down
9 changes: 9 additions & 0 deletions test/audits/cwv.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,4 +94,13 @@ describe('Index Tests', () => {
const finalUrl = await getRUMUrl('http://space.cat');
expect(finalUrl).to.eql('space.cat');
});

it('getRUMUrl adds scheme to urls without a scheme', async () => {
nock('http://space.cat')
.get('/')
.reply(200);

const finalUrl = await getRUMUrl('space.cat');
expect(finalUrl).to.eql('space.cat');
});
});
94 changes: 90 additions & 4 deletions test/audits/lhs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import { createSite } from '@adobe/spacecat-shared-data-access/src/models/site.js';

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
import sinon from 'sinon';
import sinonChai from 'sinon-chai';
import nock from 'nock';
Expand All @@ -23,6 +24,7 @@ import audit from '../../src/lhs/handler.js';

const { expect } = chai;
chai.use(sinonChai);
chai.use(chaiAsPromised);

describe('audit', () => {
let context;
Expand Down Expand Up @@ -96,21 +98,105 @@ describe('audit', () => {
sendMessage: sandbox.stub().resolves(),
},
};
});

afterEach(() => {
nock.cleanAll();
sinon.restore();
});

it('should successfully perform an audit for mobile strategy', async () => {
nock('https://psi-audit-service.com', { encodedQueryParams: true })
.get('/?url=https://adobe.com&strategy=mobile')
.reply(200, psiResult);

const response = await audit(auditQueueMessage, context);

expect(response.status).to.equal(204);
expect(mockDataAccess.addAudit).to.have.been.calledOnce;
});

afterEach(() => {
nock.cleanAll();
sinon.restore();
it('should successfully perform an audit for mobile strategy with valid URL', async () => {
nock('https://psi-audit-service.com', { encodedQueryParams: true })
.get('/?url=https://adobe.com&strategy=mobile')
.reply(200, psiResult);

auditQueueMessage.url = 'https://adobe.com';

const response = await audit(auditQueueMessage, context);

expect(response.status).to.equal(204);
expect(mockDataAccess.addAudit).to.have.been.calledOnce;
});

it('should successfully perform an audit', async () => {
it('successfully performs an audit for desktop strategy', async () => {
nock('https://psi-audit-service.com', { encodedQueryParams: true })
.get('/?url=https://adobe.com&strategy=desktop')
.reply(200, psiResult);

auditQueueMessage.type = 'lhs-desktop';
const response = await audit(auditQueueMessage, context);

expect(response.status).to.equal(204);
expect(mockDataAccess.addAudit).to.have.been.calledOnce;
});

it('throws error for an audit of unknown type', async () => {
auditQueueMessage.type = 'unknown-type';

const response = await audit(auditQueueMessage, context);

expect(response.status).to.equal(500);
expect(response.statusText).to.equal('LHS Audit Error: Unexpected error occurred: Unsupported type. Supported types are lhs-mobile and lhs-desktop.');
});

it('throws error when psi api fetch fails', async () => {
nock('https://psi-audit-service.com', { encodedQueryParams: true })
.get('/?url=https://adobe.com&strategy=mobile')
.reply(405, 'Method Not Allowed');

const response = await audit(auditQueueMessage, context);

expect(response.status).to.equal(500);
expect(response.statusText).to.equal('LHS Audit Error: Unexpected error occurred: Expected a 200 status from PSI API');
});

it('throws error when site does not exist', async () => {
mockDataAccess.getSiteByBaseURL.resolves(null);

const response = await audit(auditQueueMessage, context);

expect(response.status).to.equal(500);
expect(response.statusText).to.equal('LHS Audit Error: Unexpected error occurred: Site not found');
});

it('throws error when data access fails', async () => {
mockDataAccess.getSiteByBaseURL.rejects(new Error('Data Error'));

const response = await audit(auditQueueMessage, context);

expect(response.status).to.equal(500);
expect(response.statusText).to.equal('LHS Audit Error: Unexpected error occurred: Error getting site with baseURL adobe.com');
});

it('throws error when context is incomplete', async () => {
delete context.dataAccess;

const response = await audit(auditQueueMessage, context);

expect(response.status).to.equal(500);
expect(response.statusText).to.equal('LHS Audit Error: Invalid configuration');
});

it('performs audit even when sqs message send fails', async () => {
nock('https://psi-audit-service.com', { encodedQueryParams: true })
.get('/?url=https://adobe.com&strategy=mobile')
.reply(200, psiResult);

context.sqs.sendMessage.rejects(new Error('SQS Error'));

await audit(auditQueueMessage, context);

expect(mockLog.error).to.have.been.calledOnceWith('Error while sending audit result to queue', sinon.match.instanceOf(Error));
});
});

0 comments on commit 31731ca

Please sign in to comment.