docker-utils: Test network gateway determination logic

Change-type: patch
Signed-off-by: Rich Bayliss <rich@balena.io>
This commit is contained in:
Rich Bayliss 2020-07-22 10:53:50 +01:00
parent 3b3babfd62
commit 6ef3bd2362
No known key found for this signature in database
GPG Key ID: E53C4B4D18499E1A
2 changed files with 112 additions and 0 deletions

View File

@ -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');
});
});
});
});

View File

@ -0,0 +1,56 @@
import * as dockerode from 'dockerode';
export interface TestData {
networks: Dictionary<any>;
images: Dictionary<any>;
}
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<TestData>,
test: () => Promise<any>,
) {
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;
}
}