Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Snapshot & Restore] Remove axios dependency in tests #128614

Merged
merged 9 commits into from
Apr 4, 2022
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,6 @@ export const REPOSITORY_EDIT = getRepository({ name: REPOSITORY_NAME });

export const POLICY_NAME = 'my-test-policy';

export const SNAPSHOT_NAME = 'my-test-snapshot';

export const POLICY_EDIT = getPolicy({ name: POLICY_NAME, retention: { minCount: 1 } });
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
AsyncTestBedConfig,
delay,
} from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { SnapshotRestoreHome } from '../../../public/application/sections/home/home';
import { BASE_PATH } from '../../../public/application/constants';
import { WithAppDependencies } from './setup_environment';
Expand All @@ -26,8 +27,6 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed(WithAppDependencies(SnapshotRestoreHome), testBedConfig);

export interface HomeTestBed extends TestBed {
actions: {
clickReloadButton: () => void;
Expand All @@ -40,7 +39,11 @@ export interface HomeTestBed extends TestBed {
};
}

export const setup = async (): Promise<HomeTestBed> => {
export const setup = async (httpSetup: HttpSetup): Promise<HomeTestBed> => {
const initTestBed = registerTestBed(
WithAppDependencies(SnapshotRestoreHome, httpSetup),
testBedConfig
);
const testBed = await initTestBed();
const REPOSITORY_TABLE = 'repositoryTable';
const SNAPSHOT_TABLE = 'snapshotTable';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,117 +5,119 @@
* 2.0.
*/

import sinon, { SinonFakeServer } from 'sinon';
import { httpServiceMock } from '../../../../../../src/core/public/mocks';
import { API_BASE_PATH } from '../../../common';

type HttpMethod = 'GET' | 'PUT' | 'POST';
type HttpResponse = Record<string, any> | any[];

const mockResponse = (defaultResponse: HttpResponse, response?: HttpResponse) => [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify({ ...defaultResponse, ...response }),
];
export interface ResponseError {
statusCode: number;
message: string | Error;
}

// Register helpers to mock HTTP Requests
const registerHttpRequestMockHelpers = (server: SinonFakeServer) => {
const setLoadRepositoriesResponse = (response: HttpResponse = {}) => {
const defaultResponse = { repositories: [] };

server.respondWith(
'GET',
`${API_BASE_PATH}repositories`,
mockResponse(defaultResponse, response)
);
const registerHttpRequestMockHelpers = (
httpSetup: ReturnType<typeof httpServiceMock.createStartContract>
) => {
const mockResponses = new Map<HttpMethod, Map<string, Promise<unknown>>>(
['GET', 'PUT', 'POST'].map(
(method) => [method, new Map()] as [HttpMethod, Map<string, Promise<unknown>>]
)
);

const mockMethodImplementation = (method: HttpMethod, path: string) =>
mockResponses.get(method)?.get(path) ?? Promise.resolve({});

httpSetup.get.mockImplementation((path) =>
mockMethodImplementation('GET', path as unknown as string)
);
httpSetup.post.mockImplementation((path) =>
mockMethodImplementation('POST', path as unknown as string)
);
httpSetup.put.mockImplementation((path) =>
mockMethodImplementation('PUT', path as unknown as string)
);

const mockResponse = (method: HttpMethod, path: string, response?: unknown, error?: unknown) => {
const defuse = (promise: Promise<unknown>) => {
promise.catch(() => {});
return promise;
};

return mockResponses
.get(method)!
.set(path, error ? defuse(Promise.reject({ body: error })) : Promise.resolve(response));
};

const setLoadRepositoryTypesResponse = (response: HttpResponse = []) => {
server.respondWith('GET', `${API_BASE_PATH}repository_types`, JSON.stringify(response));
};
const setLoadRepositoriesResponse = (
response: HttpResponse = { repositories: [] },
error?: ResponseError
) => mockResponse('GET', `${API_BASE_PATH}repositories`, response, error);

const setGetRepositoryResponse = (response?: HttpResponse, delay = 0) => {
const defaultResponse = {};

server.respondWith(
'GET',
/api\/snapshot_restore\/repositories\/.+/,
mockResponse(defaultResponse, response)
);
};
const setLoadRepositoryTypesResponse = (response: HttpResponse = [], error?: ResponseError) =>
mockResponse('GET', `${API_BASE_PATH}repository_types`, response, error);

const setSaveRepositoryResponse = (response?: HttpResponse, error?: any) => {
const status = error ? error.status || 400 : 200;
const body = error ? JSON.stringify(error.body) : JSON.stringify(response);
const setGetRepositoryResponse = (
repositoryName: string,
response?: HttpResponse,
error?: ResponseError
) => mockResponse('GET', `${API_BASE_PATH}repositories/${repositoryName}`, response, error);

server.respondWith('PUT', `${API_BASE_PATH}repositories`, [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};
const setSaveRepositoryResponse = (response?: HttpResponse, error?: ResponseError) =>
mockResponse('PUT', `${API_BASE_PATH}repositories`, response, error);

const setLoadSnapshotsResponse = (response: HttpResponse = {}) => {
const setLoadSnapshotsResponse = (response?: HttpResponse, error?: ResponseError) => {
const defaultResponse = { errors: {}, snapshots: [], repositories: [], total: 0 };

server.respondWith('GET', `${API_BASE_PATH}snapshots`, mockResponse(defaultResponse, response));
return mockResponse('GET', `${API_BASE_PATH}snapshots`, response ?? defaultResponse, error);
};

const setGetSnapshotResponse = (response?: HttpResponse) => {
const defaultResponse = {};

server.respondWith(
const setGetSnapshotResponse = (
repositoryName: string,
snapshotName: string,
response?: HttpResponse,
error?: ResponseError
) =>
mockResponse(
'GET',
/\/api\/snapshot_restore\/snapshots\/.+/,
mockResponse(defaultResponse, response)
`${API_BASE_PATH}snapshots/${repositoryName}/${snapshotName}`,
response,
error
);
};

const setLoadIndicesResponse = (response: HttpResponse = {}) => {
const defaultResponse = { indices: [] };

server.respondWith(
'GET',
`${API_BASE_PATH}policies/indices`,
mockResponse(defaultResponse, response)
const setLoadIndicesResponse = (
response: HttpResponse = { indices: [] },
error?: ResponseError
) => mockResponse('GET', `${API_BASE_PATH}policies/indices`, response, error);

const setAddPolicyResponse = (response?: HttpResponse, error?: ResponseError) =>
mockResponse('POST', `${API_BASE_PATH}policies`, response, error);

const setCleanupRepositoryResponse = (
repositoryName: string,
response?: HttpResponse,
error?: ResponseError
) =>
mockResponse('POST', `${API_BASE_PATH}repositories/${repositoryName}/cleanup`, response, error);

const setGetPolicyResponse = (
policyName: string,
response?: HttpResponse,
error?: ResponseError
) => mockResponse('GET', `${API_BASE_PATH}policy/${policyName}`, response, error);

const setRestoreSnapshotResponse = (
repositoryName: string,
snapshotId: string,
response?: HttpResponse,
error?: ResponseError
) =>
mockResponse(
'POST',
`${API_BASE_PATH}restore/${repositoryName}/${snapshotId}`,
response,
error
);
};

const setAddPolicyResponse = (response?: HttpResponse, error?: any) => {
const status = error ? error.status || 400 : 200;
const body = error ? JSON.stringify(error.body) : JSON.stringify(response);

server.respondWith('POST', `${API_BASE_PATH}policies`, [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};

const setCleanupRepositoryResponse = (response?: HttpResponse, error?: any) => {
const status = error ? error.status || 503 : 200;
const body = error ? JSON.stringify(error) : JSON.stringify(response);

server.respondWith('POST', `${API_BASE_PATH}repositories/:name/cleanup`, [
status,
{ 'Content-Type': 'application/json' },
body,
]);
};

const setGetPolicyResponse = (response?: HttpResponse) => {
server.respondWith('GET', `${API_BASE_PATH}policy/:name`, [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(response),
]);
};

const setRestoreSnapshotResponse = (response?: HttpResponse) => {
server.respondWith('POST', `${API_BASE_PATH}restore/:repository/:snapshot`, [
200,
{ 'Content-Type': 'application/json' },
JSON.stringify(response),
]);
};

return {
setLoadRepositoriesResponse,
Expand All @@ -133,18 +135,11 @@ const registerHttpRequestMockHelpers = (server: SinonFakeServer) => {
};

export const init = () => {
const server = sinon.fakeServer.create();
server.respondImmediately = true;

// Define default response for unhandled requests.
// We make requests to APIs which don't impact the component under test, e.g. UI metric telemetry,
// and we can mock them all with a 200 instead of mocking each one individually.
server.respondWith([200, {}, 'DefaultResponse']);

const httpRequestsMockHelpers = registerHttpRequestMockHelpers(server);
const httpSetup = httpServiceMock.createSetupContract();
const httpRequestsMockHelpers = registerHttpRequestMockHelpers(httpSetup);

return {
server,
httpSetup,
httpRequestsMockHelpers,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { registerTestBed, AsyncTestBedConfig } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { PolicyAdd } from '../../../public/application/sections/policy_add';
import { formSetup, PolicyFormTestSubjects } from './policy_form.helpers';
import { WithAppDependencies } from './setup_environment';
Expand All @@ -18,9 +19,11 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed<PolicyFormTestSubjects>(
WithAppDependencies(PolicyAdd),
testBedConfig
);
export const setup = async (httpSetup: HttpSetup) => {
const initTestBed = registerTestBed<PolicyFormTestSubjects>(
WithAppDependencies(PolicyAdd, httpSetup),
testBedConfig
);

export const setup = formSetup.bind(null, initTestBed);
return formSetup(initTestBed);
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { registerTestBed, AsyncTestBedConfig } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { PolicyEdit } from '../../../public/application/sections/policy_edit';
import { WithAppDependencies } from './setup_environment';
import { POLICY_NAME } from './constant';
Expand All @@ -19,9 +20,11 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

const initTestBed = registerTestBed<PolicyFormTestSubjects>(
WithAppDependencies(PolicyEdit),
testBedConfig
);
export const setup = async (httpSetup: HttpSetup) => {
const initTestBed = registerTestBed<PolicyFormTestSubjects>(
WithAppDependencies(PolicyEdit, httpSetup),
testBedConfig
);

export const setup = formSetup.bind(null, initTestBed);
return formSetup(initTestBed);
};
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,11 @@
*/

import { registerTestBed, TestBed } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { RepositoryType } from '../../../common/types';
import { RepositoryAdd } from '../../../public/application/sections/repository_add';
import { WithAppDependencies } from './setup_environment';

const initTestBed = registerTestBed<RepositoryAddTestSubjects>(WithAppDependencies(RepositoryAdd), {
doMountAsync: true,
});

export interface RepositoryAddTestBed extends TestBed<RepositoryAddTestSubjects> {
actions: {
clickNextButton: () => void;
Expand All @@ -23,7 +20,13 @@ export interface RepositoryAddTestBed extends TestBed<RepositoryAddTestSubjects>
};
}

export const setup = async (): Promise<RepositoryAddTestBed> => {
export const setup = async (httpSetup: HttpSetup): Promise<RepositoryAddTestBed> => {
const initTestBed = registerTestBed<RepositoryAddTestSubjects>(
WithAppDependencies(RepositoryAdd, httpSetup),
{
doMountAsync: true,
}
);
const testBed = await initTestBed();

// User actions
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
*/

import { registerTestBed, AsyncTestBedConfig } from '@kbn/test-jest-helpers';
import { HttpSetup } from 'src/core/public';
import { RepositoryEdit } from '../../../public/application/sections/repository_edit';
import { WithAppDependencies } from './setup_environment';
import { REPOSITORY_NAME } from './constant';
Expand All @@ -18,10 +19,14 @@ const testBedConfig: AsyncTestBedConfig = {
doMountAsync: true,
};

export const setup = registerTestBed<RepositoryEditTestSubjects>(
WithAppDependencies(RepositoryEdit),
testBedConfig
);
export const setup = async (httpSetup: HttpSetup) => {
const initTestBed = registerTestBed<RepositoryEditTestSubjects>(
WithAppDependencies(RepositoryEdit, httpSetup),
testBedConfig
);

return await initTestBed();
};

export type RepositoryEditTestSubjects = TestSubjects | ThreeLevelDepth | NonVisibleTestSubjects;

Expand Down
Loading