Skip to content

Commit

Permalink
Fixing tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonrhodes committed Jun 5, 2023
1 parent 2bbb11e commit 157db38
Show file tree
Hide file tree
Showing 7 changed files with 103 additions and 24 deletions.
2 changes: 1 addition & 1 deletion x-pack/plugins/asset_manager/server/lib/get_assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export async function getAssets({

if (filters.kind) {
must.push({
term: {
terms: {
['asset.kind']: Array.isArray(filters.kind) ? filters.kind : [filters.kind],
},
});
Expand Down
7 changes: 6 additions & 1 deletion x-pack/plugins/asset_manager/server/routes/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,17 @@ export function assetsRoutes<T extends RequestHandlerContext>({ router }: SetupR

const esClient = await getEsClientFromContext(context);

console.log('IN ASSETS ENDPOINT', JSON.stringify({ filters, size }));

try {
const results = await getAssets({ esClient, size, filters });
return res.ok({ body: { results } });
} catch (error: unknown) {
debug('error looking up asset records', error);
return res.customError({ statusCode: 500 });
return res.customError({
statusCode: 500,
body: { message: 'Error while looking up asset records - ' + `${error}` },
});
}
}
);
Expand Down
32 changes: 18 additions & 14 deletions x-pack/plugins/asset_manager/server/routes/sample_assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,38 +103,42 @@ export function sampleAssetsRoutes<T extends RequestHandlerContext>({
async (context, req, res) => {
const esClient = await getEsClientFromContext(context);

const sampleDataIndices = await esClient.indices.get({
index: 'assets-*-sample_data',
const sampleDataStreams = await esClient.indices.getDataStream({
name: 'assets-*-sample_data',
expand_wildcards: 'all',
});

const deletedIndices: string[] = [];
const deletedDataStreams: string[] = [];
let errorWhileDeleting: string | null = null;
const indicesToDelete = Object.keys(sampleDataIndices);
const dataStreamsToDelete = sampleDataStreams.data_streams.map((ds) => ds.name);

for (let i = 0; i < indicesToDelete.length; i++) {
const index = indicesToDelete[i];
for (let i = 0; i < dataStreamsToDelete.length; i++) {
const dsName = dataStreamsToDelete[i];
try {
await esClient.indices.delete({ index });
deletedIndices.push(index);
await esClient.indices.deleteDataStream({ name: dsName });
deletedDataStreams.push(dsName);
} catch (error: any) {
errorWhileDeleting =
typeof error.message === 'string'
? error.message
: `Unknown error occurred while deleting indices, at index ${index}`;
: `Unknown error occurred while deleting sample data streams, at data stream name: ${dsName}`;
break;
}
}

if (deletedIndices.length === indicesToDelete.length) {
return res.ok({ body: { deleted: deletedIndices } });
if (!errorWhileDeleting && deletedDataStreams.length === dataStreamsToDelete.length) {
return res.ok({ body: { deleted: deletedDataStreams } });
} else {
console.log('\n\n\n500 500 500 500 500\n\n\n');
return res.custom({
statusCode: 500,
body: {
message: ['Not all matching indices were deleted', errorWhileDeleting].join(' - '),
deleted: deletedIndices,
matching: indicesToDelete,
message: [
'TEST change - Not all found data streams were deleted',
errorWhileDeleting,
].join(' - '),
deleted: deletedDataStreams,
matching: dataStreamsToDelete,
},
});
}
Expand Down
6 changes: 5 additions & 1 deletion x-pack/test/api_integration/apis/asset_manager/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,11 @@ export async function createSampleAssets(
}

export async function deleteSampleAssets(supertest: KibanaSupertest) {
return await supertest.delete(SAMPLE_ASSETS_ENDPOINT).set('kbn-xsrf', 'xxx').expect(200);
const result = await supertest.delete(SAMPLE_ASSETS_ENDPOINT).set('kbn-xsrf', 'xxx');
// console.log('DELETE RESULT STATUS', result.status);
// console.log('DELETE RESULT BODY', JSON.stringify(result.body));
expect(result.status).to.be(200);
return result;
}

export async function viewSampleAssetDocs(supertest: KibanaSupertest) {
Expand Down
66 changes: 66 additions & 0 deletions x-pack/test/api_integration/apis/asset_manager/tests/assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,72 @@ export default function ({ getService }: FtrProviderContext) {
);
});

it('should return assets filtered by a single asset.kind value', async () => {
await createSampleAssets(supertest);

const singleSampleKind = sampleAssetDocs[0]['asset.kind'];
const samplesForKind = sampleAssetDocs.filter(
(doc) => doc['asset.kind'] === singleSampleKind
);

const getResponse = await supertest
.get(ASSETS_ENDPOINT)
.query({ size: sampleAssetDocs.length, from: 'now-1d', kind: singleSampleKind })
.expect(200);

expect(getResponse.body).to.have.property('results');
expect(getResponse.body.results.length).to.equal(samplesForKind.length);
});

it('should return assets filtered by multiple asset.kind values (OR)', async () => {
await createSampleAssets(supertest);

// Dynamically grab all asset.kind values from the sample asset data set
const sampleKindSet: Set<string> = new Set();
for (let i = 0; i < sampleAssetDocs.length; i++) {
sampleKindSet.add(sampleAssetDocs[i]['asset.kind']!);
}
const sampleKinds = Array.from(sampleKindSet);
if (sampleKinds.length <= 2) {
throw new Error(
'Not enough asset kind values in sample asset documents, need more than two to test filtering by multiple kinds'
);
}

// Pick the first two unique kinds from the sample data set
const filterByKinds = sampleKinds.slice(0, 2);

// Track a reference to how many docs should be returned for these two kinds
const samplesForFilteredKinds = sampleAssetDocs.filter((doc) =>
filterByKinds.includes(doc['asset.kind']!)
);

expect(samplesForFilteredKinds.length).to.be.lessThan(sampleAssetDocs.length);

// Request assets for multiple types (with a size matching the number of total sample asset docs)
const getResponse = await supertest
.get(ASSETS_ENDPOINT)
.query({ size: sampleAssetDocs.length, from: 'now-1d', kind: filterByKinds })
.expect(200);

expect(getResponse.body).to.have.property('results');
expect(getResponse.body.results.length).to.equal(samplesForFilteredKinds.length);
});

it('should reject requests that try to filter by both kind and ean', async () => {
const sampleKind = sampleAssetDocs[0]['asset.kind'];
const sampleEan = sampleAssetDocs[0]['asset.ean'];

const getResponse = await supertest
.get(ASSETS_ENDPOINT)
.query({ kind: sampleKind, ean: sampleEan })
.expect(400);

expect(getResponse.body.message).to.equal(
'Filters "kind" and "ean" are mutually exclusive but found both.'
);
});

it('should return the asset matching a single ean', async () => {
await createSampleAssets(supertest);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export default function ({ getService }: FtrProviderContext) {
'[request query]: Failed to validate: \n in /0/bTo: undefined does not match expected type Date\n in /0/bTo: undefined does not match expected type datemath'
);

await supertest
return await supertest
.get(DIFF_ENDPOINT)
.query({ aFrom: timestamp, aTo: timestamp, bFrom: timestamp, bTo: timestamp })
.expect(200);
Expand Down Expand Up @@ -95,7 +95,7 @@ export default function ({ getService }: FtrProviderContext) {
`Time range cannot move backwards in time. "bTo" (${oneHourAgo}) is before "bFrom" (${isoNow}).`
);

await supertest
return await supertest
.get(DIFF_ENDPOINT)
.query({
aFrom: oneHourAgo,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -317,8 +317,8 @@ export default function ({ getService }: FtrProviderContext) {
});
});

describe('with asset.type filters', () => {
it('should filter by the provided asset type', async () => {
describe('with asset.kind filters', () => {
it('should filter by the provided asset kind', async () => {
await createSampleAssets(supertest);

const sampleCluster = sampleAssetDocs.find(
Expand All @@ -333,7 +333,7 @@ export default function ({ getService }: FtrProviderContext) {
from: 'now-1d',
ean: sampleCluster!['asset.ean'],
maxDistance: 1,
type: ['k8s.pod'],
kind: ['pod'],
})
.expect(200);

Expand All @@ -358,7 +358,7 @@ export default function ({ getService }: FtrProviderContext) {
from: 'now-1d',
ean: sampleCluster!['asset.ean'],
maxDistance: 2,
type: ['k8s.pod'],
kind: ['pod'],
})
.expect(200);

Expand All @@ -367,7 +367,7 @@ export default function ({ getService }: FtrProviderContext) {
} = getResponse;
expect(results.descendants).to.have.length(9);
expect(results.descendants.every((asset: { distance: number }) => asset.distance === 2));
expect(results.descendants.every((asset: Asset) => asset['asset.type'] === 'k8s.pod'));
expect(results.descendants.every((asset: Asset) => asset['asset.kind'] === 'pod'));
});
});
});
Expand Down

0 comments on commit 157db38

Please sign in to comment.