From 2cde44ab22dfc3d7423d994159baa0ff54b01483 Mon Sep 17 00:00:00 2001 From: Andy Pfister Date: Thu, 7 Dec 2023 15:02:00 +0100 Subject: [PATCH] Add couple more tests --- __tests__/main.test.ts | 61 +++++++++++++++++++++++- action.yml | 1 + badges/coverage.svg | 2 +- dist/index.js | 31 +++++++++++-- docker-compose.test.yml | 2 +- docker-compose.yml | 1 + package-lock.json | 100 ++++++++++++++++++++++++++++++++++++++++ package.json | 1 + src/main.ts | 29 +++++++++++- 9 files changed, 219 insertions(+), 9 deletions(-) diff --git a/__tests__/main.test.ts b/__tests__/main.test.ts index 2cdcbe4..6f3e0c7 100644 --- a/__tests__/main.test.ts +++ b/__tests__/main.test.ts @@ -8,21 +8,74 @@ import * as core from '@actions/core' import * as main from '../src/main' +import axios from 'axios' // Mock the action's main function const runMock = jest.spyOn(main, 'run') // Mock the GitHub Actions core library +let infoMock: jest.SpyInstance let getInputMock: jest.SpyInstance +let setFailedMock: jest.SpyInstance describe('action', () => { beforeEach(() => { jest.clearAllMocks() + infoMock = jest.spyOn(core, 'info').mockImplementation() getInputMock = jest.spyOn(core, 'getInput').mockImplementation() + setFailedMock = jest.spyOn(core, 'setFailed').mockImplementation() }) - it('deploys Hashicorp', async () => { + afterEach(() => { + main.cleanup() + }) + + it('fails if compose file does not exist', async () => { + getInputMock.mockImplementation((name: string): string => { + switch (name) { + case 'compose-file': + return 'nada.yml' + case 'stack-name': + return 'david' + case 'ssh-user-at-host': + return 'david@notexisting' + case 'ssh-port': + return '22' + default: + return '' + } + }) + + await main.run() + expect(runMock).toHaveReturned() + expect(setFailedMock).toHaveBeenCalledWith( + 'Compose file nada.yml does not exist' + ) + }) + + it('fails if SSH is not reachable', async () => { + getInputMock.mockImplementation((name: string): string => { + switch (name) { + case 'compose-file': + return 'docker-compose.test.yml' + case 'stack-name': + return 'david' + case 'ssh-user-at-host': + return 'david@notexisting' + case 'ssh-port': + return '22' + default: + return '' + } + }) + + await main.run() + expect(runMock).toHaveReturned() + expect(setFailedMock).toHaveBeenCalled() + }) + + it('deploys Hashicorp Echo HTTP server', async () => { // Set the action's inputs as return values from core.getInput() getInputMock.mockImplementation((name: string): string => { switch (name) { @@ -41,5 +94,9 @@ describe('action', () => { await main.run() expect(runMock).toHaveReturned() - }) + expect(infoMock).toHaveBeenCalledWith('Cleaning up ...') + + const response = await axios.get('http://127.0.0.1:8888') + expect(response.data).toMatch(/Hello World/) + }, 30000) }) diff --git a/action.yml b/action.yml index 7e19656..6e62659 100644 --- a/action.yml +++ b/action.yml @@ -29,3 +29,4 @@ inputs: runs: using: node20 main: dist/index.js + post: dist/index.js diff --git a/badges/coverage.svg b/badges/coverage.svg index 22367b9..4392d26 100644 --- a/badges/coverage.svg +++ b/badges/coverage.svg @@ -1 +1 @@ -Coverage: 56.52%Coverage56.52% \ No newline at end of file +Coverage: 97.22%Coverage97.22% \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index 10352ce..148cd61 100644 --- a/dist/index.js +++ b/dist/index.js @@ -2751,9 +2751,10 @@ var __importStar = (this && this.__importStar) || function (mod) { return result; }; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.run = void 0; +exports.cleanup = exports.run = void 0; const core = __importStar(__nccwpck_require__(186)); const child_process_1 = __nccwpck_require__(81); +const fs_1 = __nccwpck_require__(147); /** * The main function for the action. * @returns {Promise} Resolves when the action is complete. @@ -2764,15 +2765,29 @@ async function run() { const stackName = core.getInput('stack-name'); const sshUserAtHost = core.getInput('ssh-user-at-host'); const sshPort = core.getInput('ssh-port'); + if (!(0, fs_1.existsSync)(composeFile)) { + core.setFailed(`Compose file ${composeFile} does not exist`); + } + core.info('Check if system is reachable over SSH ...'); + try { + (0, child_process_1.execSync)(`ssh -o ConnectTimeout=5 -p ${sshPort} ${sshUserAtHost} exit`, { + stdio: [] + }); + } + catch (error) { + core.setFailed(`SSH connection failed: ${error}`); + } core.info('Creating docker context ...'); (0, child_process_1.execSync)(`docker context create target --docker "host=ssh://${sshUserAtHost}:${sshPort}"`, { stdio: [] }); - (0, child_process_1.execSync)(`docker context use target`); + (0, child_process_1.execSync)(`docker context use target`, { stdio: [] }); core.info('Initialising Swarm if required ...'); (0, child_process_1.execSync)('docker node ls || docker swarm init', { stdio: [] }); + const dockerStackAwaitImage = 'sudobmitch/docker-stack-wait:v0.2.5'; + (0, child_process_1.execSync)(`docker pull ${dockerStackAwaitImage}`, { stdio: [] }); core.info('Deploying stack ...'); (0, child_process_1.execSync)(`docker stack deploy --compose-file ${composeFile} --prune --with-registry-auth ${stackName}`, { stdio: [] }); core.info('Waiting for deployment to complete ...'); - (0, child_process_1.execSync)(`docker run --rm -i -v $(pwd)/${composeFile}:/docker-compose.yml -v /var/run/docker.sock:/var/run/docker.sock sudobmitch/docker-stack-wait:v0.2.5 -l "--since 2m" -t 120 ${stackName}`, { stdio: [] }); + (0, child_process_1.execSync)(`docker run --rm -i -v $(pwd)/${composeFile}:/docker-compose.yml -v /var/run/docker.sock:/var/run/docker.sock ${dockerStackAwaitImage} -l "--since 2m" -t 120 ${stackName}`); core.info('Cleaning up ...'); (0, child_process_1.execSync)('docker system prune -af', { stdio: [] }); } @@ -2783,6 +2798,16 @@ async function run() { } } exports.run = run; +async function cleanup() { + core.info('Removing docker context ...'); + try { + (0, child_process_1.execSync)('docker context remove --force target', { stdio: [] }); + } + catch { + // Ignore + } +} +exports.cleanup = cleanup; /***/ }), diff --git a/docker-compose.test.yml b/docker-compose.test.yml index 4ce3d58..8bec3fb 100644 --- a/docker-compose.test.yml +++ b/docker-compose.test.yml @@ -3,6 +3,6 @@ version: "3.9" services: web: image: "hashicorp/http-echo" - command: ["-text", "Hello World"] + command: ["-listen", ":8080", "-text", "Hello World"] ports: - 8080:8080 diff --git a/docker-compose.yml b/docker-compose.yml index dfaca1a..c9c6d37 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,5 +9,6 @@ services: cgroup: host ports: - 127.0.0.1:2222:22 + - 127.0.0.1:8888:8080 volumes: - /sys/fs/cgroup:/sys/fs/cgroup:rw diff --git a/package-lock.json b/package-lock.json index 213c672..48ef826 100644 --- a/package-lock.json +++ b/package-lock.json @@ -17,6 +17,7 @@ "@typescript-eslint/eslint-plugin": "^6.13.1", "@typescript-eslint/parser": "^6.13.1", "@vercel/ncc": "^0.38.1", + "axios": "^1.6.2", "eslint": "^8.55.0", "eslint-plugin-github": "^4.10.1", "eslint-plugin-jest": "^27.6.0", @@ -1941,6 +1942,12 @@ "integrity": "sha512-eBvWn1lvIApYMhzQMsu9ciLfkBY499mFZlNqG+/9WR7PVlroQw0vG30cOQQbaKz3sCEc44TAOu2ykzqXSNnwag==", "dev": true }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true + }, "node_modules/available-typed-arrays": { "version": "1.0.5", "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz", @@ -1962,6 +1969,17 @@ "node": ">=4" } }, + "node_modules/axios": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.2.tgz", + "integrity": "sha512-7i24Ri4pmDRfJTR7LDBhsOTtcm+9kjX5WiY1X3wIisx6G9So3pfMkEiU7emUBe46oceVImccTEM3k6C5dbVW8A==", + "dev": true, + "dependencies": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/axobject-query": { "version": "3.2.1", "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-3.2.1.tgz", @@ -2355,6 +2373,18 @@ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", "dev": true }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/common-tags": { "version": "1.8.2", "resolved": "https://registry.npmjs.org/common-tags/-/common-tags-1.8.2.tgz", @@ -2635,6 +2665,15 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/dequal": { "version": "2.0.3", "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", @@ -3652,6 +3691,26 @@ "integrity": "sha512-5nqDSxl8nn5BSNxyR3n4I6eDmbolI6WT+QqR547RwxQapgjQBmtktdP+HTBb/a/zLsbzERTONyUB5pefh5TtjQ==", "dev": true }, + "node_modules/follow-redirects": { + "version": "1.15.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz", + "integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/for-each": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.3.tgz", @@ -3661,6 +3720,20 @@ "is-callable": "^1.1.3" } }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dev": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -5447,6 +5520,27 @@ "node": ">=8.6" } }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/mimic-fn": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", @@ -5986,6 +6080,12 @@ "node": ">= 6" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "dev": true + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/package.json b/package.json index 4885fd8..24b4f91 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "@typescript-eslint/eslint-plugin": "^6.13.1", "@typescript-eslint/parser": "^6.13.1", "@vercel/ncc": "^0.38.1", + "axios": "^1.6.2", "eslint": "^8.55.0", "eslint-plugin-github": "^4.10.1", "eslint-plugin-jest": "^27.6.0", diff --git a/src/main.ts b/src/main.ts index 8cae717..634bc10 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,5 +1,6 @@ import * as core from '@actions/core' import { execSync } from 'child_process' +import { existsSync } from 'fs' /** * The main function for the action. @@ -12,6 +13,19 @@ export async function run(): Promise { const sshUserAtHost = core.getInput('ssh-user-at-host') const sshPort = core.getInput('ssh-port') + if (!existsSync(composeFile)) { + core.setFailed(`Compose file ${composeFile} does not exist`) + } + + core.info('Check if system is reachable over SSH ...') + try { + execSync(`ssh -o ConnectTimeout=5 -p ${sshPort} ${sshUserAtHost} exit`, { + stdio: [] + }) + } catch (error: unknown) { + core.setFailed(`SSH connection failed: ${error}`) + } + core.info('Creating docker context ...') execSync( `docker context create target --docker "host=ssh://${sshUserAtHost}:${sshPort}"`, @@ -22,6 +36,9 @@ export async function run(): Promise { core.info('Initialising Swarm if required ...') execSync('docker node ls || docker swarm init', { stdio: [] }) + const dockerStackAwaitImage = 'sudobmitch/docker-stack-wait:v0.2.5' + execSync(`docker pull ${dockerStackAwaitImage}`, { stdio: [] }) + core.info('Deploying stack ...') execSync( `docker stack deploy --compose-file ${composeFile} --prune --with-registry-auth ${stackName}`, @@ -30,8 +47,7 @@ export async function run(): Promise { core.info('Waiting for deployment to complete ...') execSync( - `docker run --rm -i -v $(pwd)/${composeFile}:/docker-compose.yml -v /var/run/docker.sock:/var/run/docker.sock sudobmitch/docker-stack-wait:v0.2.5 -l "--since 2m" -t 120 ${stackName}`, - { stdio: [] } + `docker run --rm -i -v $(pwd)/${composeFile}:/docker-compose.yml -v /var/run/docker.sock:/var/run/docker.sock ${dockerStackAwaitImage} -l "--since 2m" -t 120 ${stackName}` ) core.info('Cleaning up ...') @@ -41,3 +57,12 @@ export async function run(): Promise { if (error instanceof Error) core.setFailed(error.message) } } + +export async function cleanup(): Promise { + core.info('Removing docker context ...') + try { + execSync('docker context remove --force target', { stdio: [] }) + } catch { + // Ignore + } +}