Skip to content

Commit

Permalink
Merge pull request elastic#34 from Elastic-AWP-Platform/test-stubs
Browse files Browse the repository at this point in the history
More tests + jest coverage tool
  • Loading branch information
mitodrummer authored Jan 26, 2022
2 parents 19fe25d + 72e580c commit 929838f
Show file tree
Hide file tree
Showing 20 changed files with 386 additions and 166 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -884,4 +884,4 @@
"yargs": "^15.4.1",
"zlib": "^1.0.5"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,9 @@ import {
EventAction,
EventKind,
ProcessMap,
User,
} from '../../types/process_tree';

const mockEvents = [
export const mockEvents = [
{
'@timestamp': new Date('2021-11-23T15:25:04.210Z'),
process: {
Expand Down Expand Up @@ -435,13 +434,76 @@ export const mockData: ProcessEventsPage[] = [
},
];

export const childProcessMock: Process = {
id: '3d0192c6-7c54-5ee6-a110-3539a7cf42bd',
events: [],
children: [],
autoExpand: false,
searchMatched: null,
parent: undefined,
orphans: [],
getChildren: () => [],
hasOutput: () => false,
hasAlerts: () => false,
getAlerts: () => [],
hasExec: () => false,
getOutput: () => '',
getDetails: () =>
({
'@timestamp': new Date('2021-11-23T15:25:05.210Z'),
event: {
kind: EventKind.event,
category: 'process',
action: EventAction.exec,
},
process: {
args: ['ls', '-l'],
args_count: 2,
entity_id: '3d0192c6-7c54-5ee6-a110-3539a7cf42bd',
executable: '/bin/ls',
interactive: true,
name: 'ls',
working_directory: '/home/vagrant',
start: new Date('2021-11-23T15:25:05.210Z'),
pid: 2,
pgid: 1,
user: {
id: '1',
name: 'vagrant',
},
parent: {
args: ['bash'],
args_count: 1,
entity_id: '3d0192c6-7c54-5ee6-a110-3539a7cf42bc',
executable: '/bin/bash',
interactive: false,
name: '',
working_directory: '/home/vagrant',
start: new Date('2021-11-23T15:25:04.210Z'),
pid: 1,
pgid: 1,
user: {
id: '1',
name: 'vagrant',
},
},
session: {} as ProcessFields,
entry: {} as ProcessFields,
},
} as ProcessEvent),
isUserEntered: () => false,
getMaxAlertLevel: () => null,
};

export const processMock: Process = {
id: '3d0192c6-7c54-5ee6-a110-3539a7cf42bc',
events: [],
children: [],
autoExpand: false,
searchMatched: null,
parent: undefined,
orphans: [],
getChildren: () => [],
hasOutput: () => false,
hasAlerts: () => false,
getAlerts: () => [],
Expand All @@ -456,17 +518,20 @@ export const processMock: Process = {
action: EventAction.exec,
},
process: {
args: [],
args_count: 0,
args: ['bash'],
args_count: 1,
entity_id: '3d0192c6-7c54-5ee6-a110-3539a7cf42bc',
executable: '',
executable: '/bin/bash',
interactive: false,
name: '',
working_directory: '/home/vagrant',
start: new Date('2021-11-23T15:25:04.210Z'),
pid: 1,
pgid: 1,
user: {} as User,
user: {
id: '1',
name: 'vagrant',
},
parent: {} as ProcessFields,
session: {} as ProcessFields,
entry: {} as ProcessFields,
Expand Down Expand Up @@ -501,6 +566,8 @@ export const mockProcessMap = mockEvents.reduce(
parent: undefined,
autoExpand: false,
searchMatched: null,
orphans: [],
getChildren: () => [],
hasOutput: () => false,
hasAlerts: () => false,
getAlerts: () => [],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export const sessionViewProcessEventsMock = {
user: { name: 'vagrant', id: 1000 },
executable: '/usr/bin/cat',
interactive: true,
entity_id: 'bb5efe42-54a6-597c-bd0e-33a1a3fc372e',
entity_id: 'bb5efe42-54a6-597c-bd0e-33a1a3fc372f',
parent: {
pid: 51547,
pgid: 51547,
Expand Down Expand Up @@ -117,7 +117,7 @@ export const sessionViewProcessEventsMock = {
user: { name: 'vagrant', id: 1000 },
executable: '/usr/bin/cat',
interactive: true,
entity_id: '628f412a-172c-5cf4-b452-a070e1e9cbeb',
entity_id: '628f412a-172c-5cf4-b452-a070e1e9cbeg',
parent: {
pid: 51547,
pgid: 51547,
Expand Down Expand Up @@ -166,7 +166,7 @@ export const sessionViewProcessEventsMock = {
user: { name: 'vagrant', id: -1 },
executable: '/bin/bash',
interactive: false,
entity_id: '628f412a-172c-5cf4-b452-a070e1e9cbeb',
entity_id: '628f412a-172c-5cf4-b452-a070e1e9cbej',
parent: {
pid: 51547,
pgid: 51547,
Expand Down Expand Up @@ -215,7 +215,7 @@ export const sessionViewProcessEventsMock = {
user: { name: 'vagrant', id: 1000 },
executable: '/usr/bin/cat',
interactive: true,
entity_id: '628f412a-172c-5cf4-b452-a070e1e9cbeb',
entity_id: '628f412a-172c-5cf4-b452-a070e1e9cbei',
parent: {
pid: 51547,
pgid: 51547,
Expand Down Expand Up @@ -313,7 +313,7 @@ export const sessionViewProcessEventsMock = {
user: { name: 'vagrant', id: 1000 },
executable: '/usr/bin/ls',
interactive: true,
entity_id: 'a459679d-a1d5-56ae-9ebb-23f82edf40aa',
entity_id: 'a459679d-a1d5-56ae-9ebb-23f82edf40ab',
parent: {
pid: 51547,
pgid: 51547,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ export interface Process {
id: string; // the process entity_id
events: ProcessEvent[];
children: Process[];
orphans: Process[]; // currently, orphans are rendered inline with the entry session leaders children
parent: Process | undefined;
autoExpand: boolean;
searchMatched: string | null; // either false, or set to searchQuery
Expand All @@ -133,6 +134,7 @@ export interface Process {
getDetails(): ProcessEvent;
isUserEntered(): boolean;
getMaxAlertLevel(): number | null;
getChildren(hideSameGroup?: boolean): Process[];
}

export type ProcessMap = {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { expandDottedObject } from './expand_dotted_object';

const testFlattenedObj = {
'flattened.property.a': 'valueA',
'flattened.property.b': 'valueB',
regularProp: {
nestedProp: 'nestedValue',
},
'nested.array': [
{
arrayProp: 'arrayValue',
},
],
emptyArray: [],
};
describe('expandDottedObject(obj)', () => {
it('works', () => {
const expanded: any = expandDottedObject(testFlattenedObj);

expect(expanded.flattened.property.a).toEqual('valueA');
expect(expanded.flattened.property.b).toEqual('valueB');
expect(expanded.regularProp.nestedProp).toEqual('nestedValue');
expect(Array.isArray(expanded.nested.array)).toBeTruthy();
expect(expanded.nested.array[0].arrayProp).toEqual('arrayValue');
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,6 @@ const expandDottedField = (dottedFieldName: string, val: unknown): object => {
* }
*/
export const expandDottedObject = (dottedObj: object) => {
if (Array.isArray(dottedObj)) {
return dottedObj;
}
return Object.entries(dottedObj).reduce(
(acc, [key, val]) => merge(acc, expandDottedField(key, val)),
{}
Expand Down
34 changes: 34 additions & 0 deletions x-pack/plugins/session_view/common/utils/sort_processes.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import { sortProcesses } from './sort_processes';
import { Process } from '../types/process_tree';
import { mockProcessMap } from '../mocks/constants/session_view_process.mock';

describe('sortProcesses(a, b)', () => {
it('works', () => {
const processes = Object.values(mockProcessMap);

// shuffle some things to ensure all sort lines are hit
const c = processes[0];
processes[0] = processes[processes.length - 1];
processes[processes.length - 1] = c;

const sorted = processes.sort(sortProcesses);

let lastProcess: Process;

sorted.forEach((process) => {
if (
lastProcess &&
lastProcess.getDetails().process.start > process.getDetails().process.start
) {
throw new Error('processes not sorted by process.start');
}
});
});
});
1 change: 1 addition & 0 deletions x-pack/plugins/session_view/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"license": "Elastic-License",
"scripts": {
"test:jest": "node ../../scripts/jest",
"test:coverage": "node ../../scripts/jest --coverage",
"cypress": "../../../node_modules/.bin/cypress",
"cypress:run": "yarn cypress:run:reporter --browser chrome --spec './cypress/integration/**/*.spec.ts'; status=$?; yarn junit:merge && exit $status",
"cypress:run:firefox": "yarn cypress:run:reporter --browser firefox --spec './cypress/integration/**/*.spec.ts'; status=$?; yarn junit:merge && exit $status",
Expand Down
34 changes: 32 additions & 2 deletions x-pack/plugins/session_view/public/components/ProcessTree/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
ProcessEventsPage,
} from '../../../common/types/process_tree';
import { processNewEvents, searchProcessTree, autoExpandProcessTree } from './helpers';
import { sortProcesses } from '../../../common/utils/sort_processes';

interface UseProcessTreeDeps {
sessionEntityId: string;
Expand All @@ -30,15 +31,40 @@ export class ProcessImpl implements Process {
parent: Process | undefined;
autoExpand: boolean;
searchMatched: string | null;
orphans: Process[];

constructor(id: string) {
this.id = id;
this.events = [];
this.children = [];
this.orphans = [];
this.autoExpand = false;
this.searchMatched = null;
}

// hideSameGroup will filter out any processes which have the same pgid as this process
getChildren(hideSameGroup: boolean = false) {
let children = this.children;

// if there are orphans, we just render them inline with the other child processes (currently only session leader does this)
if (this.orphans.length) {
children = [...children, ...this.orphans].sort(sortProcesses);
}

if (hideSameGroup) {
const { pid } = this.getDetails().process;

return children.filter((process) => {
const { pgid } = process.getDetails().process;

// TODO: needs update after field rename to match ECS
return pgid !== pid || process.searchMatched;
});
}

return children;
}

hasOutput() {
// TODO: schema undecided
return !!this.events.find(({ event }) => event.action === EventAction.output);
Expand Down Expand Up @@ -166,6 +192,10 @@ export const useProcessTree = ({ sessionEntityId, data, searchQuery }: UseProces
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [searchQuery]);

// return the root session leader process, and a list of orphans
return { sessionLeader: processMap[sessionEntityId], processMap, orphans, searchResults };
// set new orphans array on the session leader
const sessionLeader = processMap[sessionEntityId];

sessionLeader.orphans = orphans;

return { sessionLeader: processMap[sessionEntityId], processMap, searchResults };
};
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,10 @@ describe('ProcessTree component', () => {
});

describe('When ProcessTree is mounted', () => {
it('should render given a valid sessionEntityId and Forward data', () => {
it('should render given a valid sessionEntityId and data', () => {
renderResult = mockedContext.render(
<ProcessTree
sessionEntityId="1"
sessionEntityId="3d0192c6-7c54-5ee6-a110-3539a7cf42bc"
data={mockData}
isFetching={false}
fetchNextPage={() => true}
Expand All @@ -33,7 +33,7 @@ describe('ProcessTree component', () => {
/>
);
expect(renderResult.queryByTestId('sessionViewProcessTree')).toBeTruthy();
expect(renderResult.queryByTestId('processTreeNode')).toBeTruthy();
expect(renderResult.queryAllByTestId('processTreeNode')).toBeTruthy();
});
describe('Orphaned childrens', () => {
const mockEvents = mockData[0].events;
Expand All @@ -45,10 +45,10 @@ describe('ProcessTree component', () => {
entity_id: 'orphaned-id',
args: ['orphaned'],
executable: 'orphaned',
working_directory: 'orphaned',
pid: 123,
pgid: 123,
parent: {
...mockEvents[0].process.parent,
entity_id: 'orphaned-parent-id',
},
},
} as unknown as typeof mockEvents[0];
Expand All @@ -58,7 +58,7 @@ describe('ProcessTree component', () => {

renderResult = mockedContext.render(
<ProcessTree
sessionEntityId="1"
sessionEntityId="3d0192c6-7c54-5ee6-a110-3539a7cf42bc"
data={mockData}
isFetching={false}
fetchNextPage={() => true}
Expand Down
Loading

0 comments on commit 929838f

Please sign in to comment.