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

Chore/report tests #1106

Merged
merged 3 commits into from
Dec 20, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
6 changes: 3 additions & 3 deletions api/src/modules/impact/impact-report.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ export class ImpactReportController {
})
@UseInterceptors(SetScenarioIdsInterceptor)
@Get('table/report')
async getImpactTable(
async getImpactReport(
@Query(ValidationPipe) impactTableDto: GetImpactTableDto,
@Res() res: Response,
): Promise<void> {
Expand Down Expand Up @@ -63,7 +63,7 @@ export class ImpactReportController {
})
@UseInterceptors(SetScenarioIdsInterceptor)
@Get('compare/scenario/vs/actual/report')
async getActualVsScenarioImpactTable(
async getActualVsScenarioImpactReport(
@Query(ValidationPipe)
actualVsScenarioImpactTableDto: GetActualVsScenarioImpactTableDto,
@Res() res: Response,
Expand Down Expand Up @@ -94,7 +94,7 @@ export class ImpactReportController {
})
@UseInterceptors(SetScenarioIdsInterceptor)
@Get('compare/scenario/vs/scenario/report')
async getTwoScenariosImpactTable(
async getTwoScenariosImpacReport(
@Query(ValidationPipe)
scenarioVsScenarioImpactTableDto: GetScenarioVsScenarioImpactTableDto,
@Res() res: Response,
Expand Down
19 changes: 12 additions & 7 deletions api/src/modules/impact/reports/impact.report.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,13 @@ export class ImpactReportService {
yearKey = yearKey.concat(' (projected)');
}
if ('baseScenarioValue' in nodeValue) {
resultObject[`${yearKey} (base Scenario)`] =
resultObject[`${yearKey} (Base Scenario)`] =
nodeValue.baseScenarioValue;
resultObject[`${yearKey} (compared Scenario)`] =
resultObject[`${yearKey} (Compared Scenario)`] =
nodeValue.comparedScenarioValue;
} else if ('comparedScenarioValue' in nodeValue) {
resultObject[yearKey] = nodeValue.value;
resultObject[`${yearKey} (compared Scenario)`] =
resultObject[`${yearKey} (Compared Scenario)`] =
nodeValue.comparedScenarioValue;
} else {
resultObject[yearKey] = nodeValue.value;
Expand All @@ -111,20 +111,25 @@ export class ImpactReportService {
const indicatorKey: string[] = [];
const groupByKey: string[] = [];
const yearKeys: string[] = [];
const differenceKeys: string[] = [];
const comparisonKeys: string[] = [];
Object.keys(dataSample).forEach((key: string) => {
if (key.includes(IndicatorColumnKey)) {
groupByKey.push(key);
} else if (key.includes(GroupByColumnKey)) {
groupByKey.push(key);
} else if (key.includes(AbsoluteDifferenceColumnKey)) {
differenceKeys.push(key);
comparisonKeys.push(key);
} else if (key.includes(PercentageDifferenceColumnKey)) {
differenceKeys.push(key);
comparisonKeys.push(key);
} else {
yearKeys.push(key);
}
});
return [...indicatorKey, ...groupByKey, ...yearKeys, ...differenceKeys];
return [
...indicatorKey,
...groupByKey,
...yearKeys.sort(),
...comparisonKeys,
];
}
}
43 changes: 36 additions & 7 deletions api/test/e2e/impact/impact-reports/impact-reports.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,7 @@ import ApplicationManager, {
} from '../../../utils/application-manager';
import { DataSource } from 'typeorm';
import { setupTestUser } from '../../../utils/userAuth';
import {
clearEntityTables,
clearTestDataFromDatabase,
} from '../../../utils/database-test-helper';
import { clearTestDataFromDatabase } from '../../../utils/database-test-helper';
import { Indicator } from '../../../../src/modules/indicators/indicator.entity';

describe('Impact Reports', () => {
Expand All @@ -20,16 +17,16 @@ describe('Impact Reports', () => {
testApplication = await ApplicationManager.init();

dataSource = testApplication.get<DataSource>(DataSource);

});
beforeEach(async () => {
({ jwtToken } = await setupTestUser(testApplication));
});

afterEach(async () => {
await clearEntityTables(dataSource, []);
await clearTestDataFromDatabase(dataSource);
});

afterAll(async () => {
await clearTestDataFromDatabase(dataSource);
await testApplication.close();
});
it('should create an impact report', async () => {
Expand All @@ -45,4 +42,36 @@ describe('Impact Reports', () => {
materials,
});
});
it('should create an actual vs scenario impact report', async () => {
const { indicator, scenarioIntervention } =
await fixtures.GivenAScenarioIntervention();
const response = await fixtures.WhenIRequestAnActualVsScenarioImpactReport({
app: testApplication,
jwtToken,
indicatorIds: [indicator.id],
comparedScenarioId: scenarioIntervention.scenarioId,
});

await fixtures.ThenIShouldGetAnImpactReportAboutProvidedFilters(response, {
indicators: [indicator],
isActualVsScenario: true,
});
});
it('should create a scenario vs scenario impact report', async () => {
const { baseScenario, comparedScenario, indicator } =
await fixtures.GivenTwoScenarios();
const response = await fixtures.WhenIRequestAScenarioVsScenarioImpactReport(
{
app: testApplication,
jwtToken,
baseScenarioId: baseScenario.id,
comparedScenarioId: comparedScenario.id,
indicatorIds: [indicator.id],
},
);
await fixtures.ThenIShouldGetAnImpactReportAboutProvidedFilters(response, {
indicators: [indicator],
isScenarioVsScenario: true,
});
});
});
81 changes: 81 additions & 0 deletions api/test/e2e/impact/impact-reports/impactReportFixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import * as request from 'supertest';
import { GROUP_BY_VALUES } from '../../../../src/modules/impact/dto/impact-table.dto';
import { range } from 'lodash';
import { Material } from '../../../../src/modules/materials/material.entity';
import { Scenario } from 'modules/scenarios/scenario.entity';
import { createNewCoefficientsInterventionPreconditions } from '../mocks/actual-vs-scenario-preconditions/new-coefficients-intervention.preconditions';
import { ScenarioIntervention } from '../../../../src/modules/scenario-interventions/scenario-intervention.entity';
import { createSameMaterialTwoScenariosPreconditions } from '../mocks/scenario-vs-scenario-preconditions/same-materials-scenarios.preconditions';

export const impactReportFixtures = () => ({
GivenSourcingLocationWithImpact: async () => {
Expand Down Expand Up @@ -89,6 +93,33 @@ export const impactReportFixtures = () => ({
sourcingRecords,
};
},
GivenAScenarioIntervention: async (
customScenario?: Scenario,
): Promise<{
indicator: Indicator;
scenarioIntervention: ScenarioIntervention;
}> => {
const { indicator, scenarioIntervention } =
await createNewCoefficientsInterventionPreconditions(customScenario);
return {
indicator,
scenarioIntervention,
};
},
GivenTwoScenarios: async (): Promise<any> => {
const {
newScenarioChangeSupplier: baseScenario,
newScenarioChangeMaterial: comparedScenario,
indicator,
} = await createSameMaterialTwoScenariosPreconditions();

return {
baseScenario,
comparedScenario,
indicator,
};
},

WhenIRequestAnImpactReport: (options: {
app: TestApplication;
jwtToken: string;
Expand All @@ -104,12 +135,51 @@ export const impactReportFixtures = () => ({
groupBy: 'material',
});
},
WhenIRequestAnActualVsScenarioImpactReport: (options: {
app: TestApplication;
jwtToken: string;
indicatorIds: string[];
comparedScenarioId: string;
}): Promise<request.Response> => {
return request(options.app.getHttpServer())
.get('/api/v1/impact/compare/scenario/vs/actual/report')
.set('Authorization', `Bearer ${options.jwtToken}`)
.query({
'indicatorIds[]': [...options.indicatorIds],
startYear: 2010,
endYear: 2027,
groupBy: 'material',
comparedScenarioId: options.comparedScenarioId,
});
},
WhenIRequestAScenarioVsScenarioImpactReport: (options: {
app: TestApplication;
jwtToken: string;
indicatorIds: string[];
baseScenarioId: string;
comparedScenarioId: string;
}) => {
return request(options.app.getHttpServer())
.get('/api/v1/impact/compare/scenario/vs/scenario/report')
.set('Authorization', `Bearer ${options.jwtToken}`)
.query({
'indicatorIds[]': [...options.indicatorIds],
startYear: 2010,
endYear: 2027,
groupBy: 'material',
baseScenarioId: options.baseScenarioId,
comparedScenarioId: options.comparedScenarioId,
});
},

ThenIShouldGetAnImpactReportAboutProvidedFilters: (
response: request.Response,
filters?: {
groupBy?: GROUP_BY_VALUES;
indicators?: Indicator[];
materials?: Material[];
isActualVsScenario?: boolean;
isScenarioVsScenario?: boolean;
},
) => {
expect(response.status).toBe(200);
Expand All @@ -126,6 +196,17 @@ export const impactReportFixtures = () => ({
expect(response.text).toContain(material.name);
}
}
if (filters?.isActualVsScenario) {
expect(response.text).toContain('Compared Scenario');
expect(response.text).toContain('Absolute Difference');
expect(response.text).toContain('Percentage Difference');
}
if (filters?.isScenarioVsScenario) {
expect(response.text).toContain('Base Scenario');
expect(response.text).toContain('Compared Scenario');
expect(response.text).toContain('Absolute Difference');
expect(response.text).toContain('Percentage Difference');
}
for (const year of range(2010, 2027)) {
expect(response.text).toContain(year.toString());
}
Expand Down
6 changes: 3 additions & 3 deletions api/test/e2e/impact/impact-table/scenario-vs-scenario.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import {
getSameMaterialScenarioComparisonResponse,
getScenarioComparisonResponseBySupplier,
} from '../mocks/scenario-vs-scenario-responses/same-materials-scenarios.reponse';
import { createSameMaterialScenariosPreconditions } from '../mocks/scenario-vs-scenario-preconditions/same-materials-scenarios.preconditions';
import { createSameMaterialTwoScenariosPreconditions } from '../mocks/scenario-vs-scenario-preconditions/same-materials-scenarios.preconditions';
import { DataSource } from 'typeorm';
import { createImpactTableSortingPreconditions } from '../mocks/sorting.preconditions';
import { ImpactTableRows } from 'modules/impact/dto/response-impact-table.dto';
Expand Down Expand Up @@ -75,7 +75,7 @@ describe('Scenario VS Scenario Impact Table test suite (e2e)', () => {
newScenarioChangeSupplier: Scenario;
newScenarioChangeMaterial: Scenario;
indicator: Indicator;
} = await createSameMaterialScenariosPreconditions();
} = await createSameMaterialTwoScenariosPreconditions();

const responseGroupByMaterial = await request(
testApplication.getHttpServer(),
Expand Down Expand Up @@ -147,7 +147,7 @@ describe('Scenario VS Scenario Impact Table test suite (e2e)', () => {
newScenarioChangeSupplier: Scenario;
newScenarioChangeMaterial: Scenario;
indicator: Indicator;
} = await createSameMaterialScenariosPreconditions();
} = await createSameMaterialTwoScenariosPreconditions();

const response = await request(testApplication.getHttpServer())
.get('/api/v1/impact/compare/scenario/vs/scenario')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ import {
import { INDICATOR_NAME_CODES } from 'modules/indicators/indicator.entity';
import { Scenario } from 'modules/scenarios/scenario.entity';

// TODO: Pending to start refactoring all precondition creation mess to follow the fixture approach

export async function createNewCoefficientsInterventionPreconditions(
customScenario?: Scenario,
): Promise<{
Expand All @@ -48,6 +50,7 @@ export async function createNewCoefficientsInterventionPreconditions(
name: 'Deforestation',
unit,
nameCode: INDICATOR_NAME_CODES.DF_SLUC,
shortName: 'Deforestation',
});

// Creating Materials
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import {
} from '../../../../entity-mocks';
import { INDICATOR_NAME_CODES } from 'modules/indicators/indicator.entity';

export async function createSameMaterialScenariosPreconditions(): Promise<{
export async function createSameMaterialTwoScenariosPreconditions(): Promise<{
indicator: Indicator;
newScenarioChangeSupplier: Scenario;
newScenarioChangeMaterial: Scenario;
Expand All @@ -43,6 +43,7 @@ export async function createSameMaterialScenariosPreconditions(): Promise<{
name: 'Deforestation',
unit,
nameCode: INDICATOR_NAME_CODES.DF_SLUC,
shortName: 'Deforestation',
});

const textile: Material = await createMaterial({ name: 'Textile' });
Expand Down
24 changes: 24 additions & 0 deletions api/test/utils/userAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import { User } from 'modules/users/user.entity';
import { EntityManager } from 'typeorm';
import { TestApplication } from './application-manager';
import { faker } from '@faker-js/faker';
import { Permission } from '../../src/modules/authorization/permissions/permissions.entity';
import { PERMISSIONS } from '../../src/modules/authorization/permissions/permissions.enum';

export type TestUser = { jwtToken: string; user: User; password: string };

Expand All @@ -25,6 +27,8 @@ export async function setupTestUser(

const password = extraDataPassword ?? faker.internet.password();

await setUpRolesAndPermissions(entityManager);

const user = await userRepository.save({
...E2E_CONFIG.users.signUp,
salt,
Expand All @@ -40,3 +44,23 @@ export async function setupTestUser(

return { jwtToken: response.body.accessToken, user, password };
}

async function setUpRolesAndPermissions(
entityManager: EntityManager,
): Promise<any> {
const permissions: Permission[] = Object.values(PERMISSIONS).map(
(permission: PERMISSIONS) =>
({
action: permission,
} as Permission),
);

const roles: Role[] = Object.values(ROLES).map(
(role: ROLES) =>
({
name: role,
} as Role),
);
await entityManager.getRepository(Permission).save(permissions);
await entityManager.getRepository(Role).save(roles);
}
Loading