Skip to content

Commit

Permalink
Merge pull request #2180 from snyk/test/migrate-is-docker
Browse files Browse the repository at this point in the history
test: migrate is-docker to jest
  • Loading branch information
Avishagp authored Aug 23, 2021
2 parents dd46c19 + 95631e7 commit 418e6ad
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 45 deletions.
45 changes: 0 additions & 45 deletions test/is-docker.test.ts

This file was deleted.

56 changes: 56 additions & 0 deletions test/jest/unit/is-docker.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import * as fs from 'fs';
import * as path from 'path';

import { isDocker } from '../../../src/lib/is-docker';

describe('isDocker', () => {
afterEach(() => {
jest.restoreAllMocks();
});

it('inside a Docker container (.dockerenv test)', async () => {
delete require.cache[path.join(__dirname, 'index.js')];
const statSyncSpy = jest.spyOn(fs, 'statSync').mockReturnValue({} as any);
expect(isDocker()).toBeTruthy();
expect(statSyncSpy).toHaveBeenCalledTimes(1);
expect(statSyncSpy).toHaveBeenLastCalledWith('/.dockerenv');
});

it('inside a Docker container (cgroup test)', async () => {
delete require.cache[path.join(__dirname, 'index.js')];

const statSyncSpy = jest.spyOn(fs, 'statSync');
const readFileSyncSpy = jest.spyOn(fs, 'readFileSync');

statSyncSpy.mockImplementationOnce((path): any => {
if (path === '/.dockerenv') {
throw new Error("ENOENT, no such file or directory '/.dockerinit'");
}
});

readFileSyncSpy.mockImplementationOnce((path, options): any => {
if (path === '/proc/self/cgroup' && options === 'utf8') {
return 'xxx docker yyyy';
}
});

expect(isDocker()).toEqual(true);
});

it('not inside a Docker container', async () => {
const statSyncSpy = jest.spyOn(fs, 'statSync');
const readFileSync = jest.spyOn(fs, 'readFileSync');

statSyncSpy.mockImplementationOnce((path): any => {
if (path === '/.dockerenv') {
throw new Error("ENOENT, no such file or directory '/.dockerinit'");
}
});

readFileSync.mockImplementationOnce((): any => {
throw new Error("ENOENT, no such file or directory '/.dockerinit'");
});

expect(isDocker()).toEqual(false);
});
});

0 comments on commit 418e6ad

Please sign in to comment.