diff --git a/test/31-docker-utils.spec.ts b/test/31-docker-utils.spec.ts new file mode 100644 index 00000000..adc155f9 --- /dev/null +++ b/test/31-docker-utils.spec.ts @@ -0,0 +1,56 @@ +import { expect } from 'chai'; +import { testWithData } from './lib/mocked-dockerode'; + +import * as dockerUtils from '../src/lib/docker-utils'; + +describe('Docker Utils', () => { + describe('Supervisor Address', () => { + // setup some fake data... + const networks = { + supervisor0: { + IPAM: { + Config: [ + { + Gateway: '10.0.105.1', + Subnet: '10.0.105.0/16', + }, + ], + }, + }, + }; + + // test using existing data... + it('should return the correct gateway address for supervisor0', async () => { + await testWithData({ networks }, async () => { + const gateway = await dockerUtils.getNetworkGateway('supervisor0'); + expect(gateway).to.equal('10.0.105.1'); + }); + }); + + it('should return the correct gateway address for host', async () => { + await testWithData({ networks }, async () => { + const gateway = await dockerUtils.getNetworkGateway('host'); + expect(gateway).to.equal('127.0.0.1'); + }); + }); + }); + + describe('Image Environment', () => { + const images = { + ['test-image']: { + Config: { + Env: ['TEST_VAR_1=1234', 'TEST_VAR_2=5678'], + }, + }, + }; + + // test using existing data... + it('should return the correct image environment', async () => { + await testWithData({ images }, async () => { + const obj = await dockerUtils.getImageEnv('test-image'); + expect(obj).to.have.property('TEST_VAR_1').equal('1234'); + expect(obj).to.have.property('TEST_VAR_2').equal('5678'); + }); + }); + }); +}); diff --git a/test/lib/mocked-dockerode.ts b/test/lib/mocked-dockerode.ts new file mode 100644 index 00000000..8f31ea74 --- /dev/null +++ b/test/lib/mocked-dockerode.ts @@ -0,0 +1,56 @@ +import * as dockerode from 'dockerode'; + +export interface TestData { + networks: Dictionary; + images: Dictionary; +} + +function createMockedDockerode(data: TestData) { + const mockedDockerode = dockerode.prototype; + mockedDockerode.getNetwork = (id: string) => { + return { + inspect: async () => { + return data.networks[id]; + }, + } as dockerode.Network; + }; + + mockedDockerode.getImage = (name: string) => { + return { + inspect: async () => { + return data.images[name]; + }, + } as dockerode.Image; + }; + + return mockedDockerode; +} + +export async function testWithData( + data: Partial, + test: () => Promise, +) { + const mockedData: TestData = { + ...{ + networks: {}, + images: {}, + containers: {}, + }, + ...data, + }; + + // grab the original prototype... + const basePrototype = dockerode.prototype; + + // @ts-expect-error setting a RO property + dockerode.prototype = createMockedDockerode(mockedData); + + try { + // run the test... + await test(); + } finally { + // reset the original prototype... + // @ts-expect-error setting a RO property + dockerode.prototype = basePrototype; + } +}