From 9bfda32f6cd4c22df83570f6aa1db440d2d12a79 Mon Sep 17 00:00:00 2001 From: GrantBirki Date: Mon, 21 Oct 2024 14:42:32 -0700 Subject: [PATCH] add unit tests --- .../functions/commit-safety-checks.test.js | 57 +++++++++++++++++++ __tests__/main.test.js | 15 +++-- 2 files changed, 66 insertions(+), 6 deletions(-) create mode 100644 __tests__/functions/commit-safety-checks.test.js diff --git a/__tests__/functions/commit-safety-checks.test.js b/__tests__/functions/commit-safety-checks.test.js new file mode 100644 index 00000000..23c78fa9 --- /dev/null +++ b/__tests__/functions/commit-safety-checks.test.js @@ -0,0 +1,57 @@ +import {commitSafetyChecks} from '../../src/functions/commit-safety-checks' +import * as core from '@actions/core' + +const debugMock = jest.spyOn(core, 'debug').mockImplementation(() => {}) + +var data +var context +beforeEach(() => { + jest.clearAllMocks() + jest.spyOn(core, 'debug').mockImplementation(() => {}) + + context = { + payload: { + comment: { + created_at: '2024-10-15T12:00:00Z' + } + } + } + + data = { + commit: { + author: { + date: '2024-10-15T11:00:00Z' + } + } + } +}) + +test('checks a commit and finds that it is safe (date)', async () => { + expect(await commitSafetyChecks(context, data)).toStrictEqual({ + message: 'success', + status: true + }) + expect(debugMock).toHaveBeenCalledWith( + '2024-10-15T12:00:00Z is not older than 2024-10-15T11:00:00Z' + ) +}) + +test('checks a commit and finds that it is not safe (date)', async () => { + data.commit.author.date = '2024-10-15T12:00:01Z' + + expect(await commitSafetyChecks(context, data)).toStrictEqual({ + message: + '### ⚠️ Cannot proceed with deployment\n\nThe latest commit is not safe for deployment. It was authored after the trigger comment was created.', + status: false + }) + expect(debugMock).toHaveBeenCalledWith( + '2024-10-15T12:00:00Z is older than 2024-10-15T12:00:01Z' + ) +}) + +test('raises an error if the date format is invalid', async () => { + data.commit.author.date = '2024-10-15T12:00:uhoh' + await expect(commitSafetyChecks(context, data)).rejects.toThrow( + 'Invalid date format. Please ensure the dates are valid UTC timestamps.' + ) +}) diff --git a/__tests__/main.test.js b/__tests__/main.test.js index 95f23106..014bdd75 100644 --- a/__tests__/main.test.js +++ b/__tests__/main.test.js @@ -910,12 +910,15 @@ test('fails prechecks', async () => { }) test('fails commitSafetyChecks', async () => { - jest.spyOn(commitSafetyChecks, 'commitSafetyChecks').mockImplementation(() => { - return { - status: false, - message: '### ⚠️ Cannot proceed with deployment... a scary commit was found', - } - }) + jest + .spyOn(commitSafetyChecks, 'commitSafetyChecks') + .mockImplementation(() => { + return { + status: false, + message: + '### ⚠️ Cannot proceed with deployment... a scary commit was found' + } + }) jest.spyOn(actionStatus, 'actionStatus').mockImplementation(() => { return undefined })