Skip to content

Commit

Permalink
feat(1415): Add tests for other events and fix queries
Browse files Browse the repository at this point in the history
  • Loading branch information
supra08 committed Aug 27, 2020
1 parent 0581a92 commit 15eebfe
Show file tree
Hide file tree
Showing 2 changed files with 153 additions and 23 deletions.
59 changes: 42 additions & 17 deletions plugins/webhooks/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,14 @@ function getSkipMessageAndChainPR({ pipeline, prSource, restrictPR, chainPR }) {
return result;
}

const uriTrimmer = uri => {
const uriToArray = uri.split(':');

while (uriToArray.length > 2) uriToArray.pop();

return uriToArray.join(':');
};

/**
* Get all pipelines which has triggered job
* @method triggeredPipelines
Expand Down Expand Up @@ -282,11 +290,11 @@ async function triggeredPipelines(
const scmBranch = `${splitUri[0]}:${splitUri[1]}:${splitUri[2]}`;
const scmRepoId = `${splitUri[0]}:${splitUri[1]}`;
const listConfig = { search: { field: 'scmUri', keyword: `${scmRepoId}:%` } };
const externalRepoSearchConfig = { params: { contains: { subscribedScmUrls: scmUri } } };
const externalRepoSearchConfig = { search: { field: 'subscribedScmUrls', keyword: `%${scmRepoId}:%` } };

const pipelines = await pipelineFactory.list(listConfig);

const pipelinesWithSubscribedExtRepos = await pipelineFactory.list(externalRepoSearchConfig);
const pipelinesWithSubscribedRepos = await pipelineFactory.list(externalRepoSearchConfig);

let pipelinesOnCommitBranch = [];
let pipelinesOnOtherBranch = [];
Expand Down Expand Up @@ -323,7 +331,7 @@ async function triggeredPipelines(

const currentRepoPipelines = pipelinesOnCommitBranch.concat(pipelinesOnOtherBranch);

return currentRepoPipelines.concat(pipelinesWithSubscribedExtRepos);
return currentRepoPipelines.concat(pipelinesWithSubscribedRepos);
}

/**
Expand Down Expand Up @@ -394,15 +402,6 @@ async function createPREvents(options, request) {
chainPR
});

let subscribedEvent = false;
let subscribedScmConfig = {};

// Check is the webhook event is from a subscribed repo
if (scmConfig.scmUri !== p.scmUri) {
subscribedEvent = true;
subscribedScmConfig = scmConfig;
}

const eventConfig = {
pipelineId: p.id,
type: 'pr',
Expand All @@ -420,11 +419,15 @@ async function createPREvents(options, request) {
prTitle,
prInfo: await eventFactory.scm.getPrInfo(scmConfig),
prSource,
baseBranch: branch,
subscribedEvent,
subscribedScmConfig
baseBranch: branch
};

// Check is the webhook event is from a subscribed repo
if (uriTrimmer(scmConfig.scmUri) !== uriTrimmer(p.scmUri)) {
eventConfig.subscribedEvent = true;
eventConfig.subscribedScmConfig = scmConfig;
}

if (skipMessage) {
eventConfig.skipMessage = skipMessage;
}
Expand Down Expand Up @@ -749,7 +752,15 @@ function createMeta(parsed) {
* @param {String} [skipMessage] Message to skip starting builds
* @returns {Promise} Promise that resolves into events
*/
async function createEvents(eventFactory, userFactory, pipelineFactory, pipelines, parsed, skipMessage) {
async function createEvents(
eventFactory,
userFactory,
pipelineFactory,
pipelines,
parsed,
skipMessage,
scmConfigFromHook
) {
const { action, branch, sha, username, scmContext, changedFiles, type, releaseName, ref } = parsed;
const events = [];
const meta = createMeta(parsed);
Expand Down Expand Up @@ -841,6 +852,12 @@ async function createEvents(eventFactory, userFactory, pipelineFactory, pipeline
ref
};

// Check is the webhook event is from a subscribed repo
if (uriTrimmer(scmConfigFromHook.scmUri) !== uriTrimmer(pTuple.pipeline.scmUri)) {
eventConfig.subscribedEvent = true;
eventConfig.subscribedScmConfig = scmConfigFromHook;
}

if (skipMessage) {
eventConfig.skipMessage = skipMessage;
}
Expand Down Expand Up @@ -914,7 +931,15 @@ async function pushEvent(pluginOptions, request, reply, parsed, skipMessage, tok
if (!pipelines || pipelines.length === 0) {
request.log(['webhook', hookId], `Skipping since Pipeline ${fullCheckoutUrl} does not exist`);
} else {
events = await createEvents(eventFactory, userFactory, pipelineFactory, pipelines, parsed, skipMessage);
events = await createEvents(
eventFactory,
userFactory,
pipelineFactory,
pipelines,
parsed,
skipMessage,
scmConfig
);
}

const hasBuildEvents = events.filter(e => e.builds !== null);
Expand Down
117 changes: 111 additions & 6 deletions test/plugins/webhooks.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ describe('webhooks plugin test', () => {
const checkoutUrl = '[email protected]:baxterthehacker/public-repo.git';
const fullCheckoutUrl = '[email protected]:baxterthehacker/public-repo.git#master';
const scmUri = 'github.com:123456:master';
const scmRepoId = `github.com:123456`;
const pipelineId = 'pipelineHash';
const jobId = 2;
const buildId = 'buildHash';
Expand Down Expand Up @@ -588,6 +589,9 @@ describe('webhooks plugin test', () => {
pipelineMock.workflowGraph = workflowGraph;
pipelineMock.jobs = Promise.resolve([mainJobMock, jobMock]);
pipelineFactoryMock.scm.parseHook.withArgs(reqHeaders, payload).resolves(parsed);
pipelineFactoryMock.list
.withArgs({ search: { field: 'subscribedScmUrls', keyword: `%${scmRepoId}:%` } })
.resolves([pipelineMock]);
pipelineFactoryMock.list.resolves([pipelineMock]);
});

Expand Down Expand Up @@ -1148,6 +1152,9 @@ describe('webhooks plugin test', () => {
});

pipelineFactoryMock.list.resolves([pipelineMock, pMock1, pMock2, pMock3]);
pipelineFactoryMock.list
.withArgs({ search: { field: 'subscribedScmUrls', keyword: `%${scmRepoId}:%` } })
.resolves([]);

return server.inject(options).then(reply => {
assert.equal(reply.statusCode, 201);
Expand Down Expand Up @@ -1245,6 +1252,9 @@ describe('webhooks plugin test', () => {

pipelineFactoryMock.scm.getChangedFiles.resolves(['lib/test.js']);
pipelineFactoryMock.list.resolves([pipelineMock, pMock1, pMock2]);
pipelineFactoryMock.list
.withArgs({ search: { field: 'subscribedScmUrls', keyword: `%${scmRepoId}:%` } })
.resolves([]);

return server.inject(options).then(reply => {
assert.equal(reply.statusCode, 201);
Expand Down Expand Up @@ -1337,6 +1347,43 @@ describe('webhooks plugin test', () => {
});
});

it('returns 201 when the hook source triggers subscribed event', () => {
pipelineFactoryMock.scm.parseUrl
.withArgs({ checkoutUrl: fullCheckoutUrl, token, scmContext })
.resolves('github.com:789123:master');
pipelineFactoryMock.list.resolves([]);
pipelineFactoryMock.list
.withArgs({ search: { field: 'subscribedScmUrls', keyword: '%github.com:789123:%' } })
.resolves([pipelineMock]);
const scmConfigSubscribe = {
scmUri: 'github.com:789123:master',
token,
scmContext
};

return server.inject(options).then(reply => {
assert.equal(reply.statusCode, 201);
assert.calledWith(eventFactoryMock.create, {
pipelineId,
type: 'pipeline',
webhooks: true,
username,
scmContext,
sha,
configPipelineSha: latestSha,
startFrom: '~commit',
baseBranch: 'master',
causeMessage: `Merged by ${username}`,
changedFiles,
releaseName: undefined,
ref: undefined,
meta: {},
subscribedEvent: true,
subscribedScmConfig: scmConfigSubscribe
});
});
});

it('returns 204 when no pipeline', () => {
pipelineFactoryMock.get.resolves(null);
pipelineFactoryMock.list.resolves([]);
Expand Down Expand Up @@ -1821,6 +1868,47 @@ describe('webhooks plugin test', () => {
});
});

it('returns 201 when the hook source triggers subscribed event', () => {
pipelineFactoryMock.scm.parseUrl
.withArgs({ checkoutUrl: fullCheckoutUrl, token, scmContext })
.resolves('github.com:789123:master');
pipelineFactoryMock.list.resolves([]);
pipelineFactoryMock.list
.withArgs({ search: { field: 'subscribedScmUrls', keyword: '%github.com:789123:%' } })
.resolves([pipelineMock]);
const scmConfigSubscribe = {
scmUri: 'github.com:789123:master',
token,
scmContext,
prNum: 2
};

return server.inject(options).then(reply => {
assert.equal(reply.statusCode, 201);
assert.calledWith(eventFactoryMock.create, {
prInfo,
pipelineId,
type: 'pr',
webhooks: true,
username,
scmContext,
sha,
configPipelineSha: latestSha,
startFrom: '~pr',
prNum: 2,
prTitle: 'Update the README with new information',
prRef,
prSource: 'branch',
changedFiles,
causeMessage: `Opened by ${scmDisplayName}:${username}`,
chainPR: false,
baseBranch: 'master',
subscribedEvent: true,
subscribedScmConfig: scmConfigSubscribe
});
});
});

it('returns 201 when getCommitSha() is rejected', () => {
pipelineFactoryMock.scm.getCommitSha.rejects(new Error('some error'));

Expand Down Expand Up @@ -2227,6 +2315,10 @@ describe('webhooks plugin test', () => {
it('has the workflow for stopping builds before starting a new one', () => {
const abortMsg = 'Aborted because new commit was pushed to PR#1';

pipelineFactoryMock.list
.withArgs({ search: { field: 'subscribedScmUrls', keyword: `%${scmRepoId}:%` } })
.resolves([]);

return server.inject(options).then(reply => {
assert.calledOnce(model1.update);
assert.calledOnce(model2.update);
Expand Down Expand Up @@ -2459,13 +2551,18 @@ describe('webhooks plugin test', () => {
pipelineFactoryMock.scm.parseHook.withArgs(reqHeaders, options.payload).resolves(parsed);
});

it('returns 200 on success', () =>
server.inject(options).then(reply => {
it('returns 200 on success', () => {
pipelineFactoryMock.list
.withArgs({ search: { field: 'subscribedScmUrls', keyword: `%${scmRepoId}:%` } })
.resolves([]);

return server.inject(options).then(reply => {
assert.equal(reply.statusCode, 200);
assert.calledOnce(jobMock.update);
assert.strictEqual(jobMock.state, 'ENABLED');
assert.isTrue(jobMock.archived);
}));
});
});

it('returns 204 when pipeline to be closed does not exist', () => {
pipelineFactoryMock.list.resolves([]);
Expand All @@ -2475,18 +2572,26 @@ describe('webhooks plugin test', () => {
});
});

it('stops running builds', () =>
server.inject(options).then(() => {
it('stops running builds', () => {
pipelineFactoryMock.list
.withArgs({ search: { field: 'subscribedScmUrls', keyword: `%${scmRepoId}:%` } })
.resolves([]);

return server.inject(options).then(() => {
assert.calledOnce(model1.update);
assert.calledOnce(model2.update);
assert.strictEqual(model1.status, 'ABORTED');
assert.strictEqual(model1.statusMessage, 'Aborted because PR#1 was closed');
assert.strictEqual(model2.status, 'ABORTED');
assert.strictEqual(model2.statusMessage, 'Aborted because PR#1 was closed');
}));
});
});

it('returns 500 when failed', () => {
jobMock.update.rejects(new Error('Failed to update'));
pipelineFactoryMock.list
.withArgs({ search: { field: 'subscribedScmUrls', keyword: `%${scmRepoId}:%` } })
.resolves([]);

return server.inject(options).then(reply => {
assert.equal(reply.statusCode, 500);
Expand Down

0 comments on commit 15eebfe

Please sign in to comment.