Skip to content

Commit

Permalink
Improve testing framework, add tests for eudr admin-regions
Browse files Browse the repository at this point in the history
  • Loading branch information
alexeh committed Feb 29, 2024
1 parent 6867a97 commit 596d9a6
Show file tree
Hide file tree
Showing 7 changed files with 196 additions and 136 deletions.
1 change: 0 additions & 1 deletion api/src/modules/import-data/eudr/eudr.import.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ export class EudrImportService {
const fakedCartoOutput: any[] = data.map((row: any) =>
this.generateFakeAlerts(row),
);
console.log(fakedCartoOutput);

const parsed: any = await new AsyncParser({
fields: [
Expand Down
84 changes: 26 additions & 58 deletions api/test/e2e/admin-regions/admin-regions-eudr-smart-filters.spec.ts
Original file line number Diff line number Diff line change
@@ -1,82 +1,50 @@
import { DataSource } from 'typeorm';
import { createMaterial, createSupplier } from '../../entity-mocks';
import ApplicationManager from '../../utils/application-manager';
import { TestApplication } from '../../utils/application-manager';
import { clearTestDataFromDatabase } from '../../utils/database-test-helper';
import { setupTestUser } from '../../utils/userAuth';
import { adminRegionsFixtures } from './fixtures';
import { AdminRegionTestManager } from './fixtures';

describe('GeoRegions Filters (e2e)', () => {
const fixtures = adminRegionsFixtures();
let testApplication: TestApplication;
let jwtToken: string;
let dataSource: DataSource;
describe('Admin Regions EUDR Filters (e2e)', () => {
let testManager: AdminRegionTestManager;

beforeAll(async () => {
testApplication = await ApplicationManager.init();

dataSource = testApplication.get<DataSource>(DataSource);
testManager = await AdminRegionTestManager.load();
});

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

afterEach(async () => {
await clearTestDataFromDatabase(dataSource);
await testManager.clearDatabase();
});

afterAll(async () => {
await testApplication.close();
await testManager.close();
});
describe('EUDR Admin Regions Filters', () => {
it('should only get geo-regions that are part of EUDR data', async () => {
await fixtures.GivenAdminRegionsOfSourcingLocations();
const { eudrAdminRegions } = await fixtures.GivenEUDRAdminRegions();
const response = await fixtures.WhenIRequestEUDRAdminRegions({
app: testApplication,
jwtToken,
});
fixtures.ThenIShouldOnlyReceiveEUDRAdminRegions(
response,
it('should only get admin-regions that are part of EUDR data', async () => {
await testManager.GivenAdminRegionsOfSourcingLocations();
const { eudrAdminRegions } = await testManager.GivenEUDRAdminRegions();
await testManager.WhenIRequestEUDRAdminRegions();
testManager.ThenIShouldOnlyReceiveCorrespondingAdminRegions(
eudrAdminRegions,
);
});
it('should only get geo-regions that are part of EUDR data and are filtered', async () => {
it('should only get admin-regions that are part of EUDR data and are filtered', async () => {
const { sourcingLocations } =
await fixtures.GivenAdminRegionsOfSourcingLocations();
const regularMaterial = await createMaterial({
name: 'Regular Material',
});
await fixtures.AndAssociatedMaterials(
[regularMaterial],
sourcingLocations,
);
const regularSupplier = await createSupplier({
name: 'Regular Supplier',
});
await fixtures.AndAssociatedSuppliers(
[regularSupplier],
sourcingLocations,
);
await testManager.GivenAdminRegionsOfSourcingLocations();
await testManager.AndAssociatedMaterials(sourcingLocations);
await testManager.AndAssociatedSuppliers([sourcingLocations[0]]);
const { eudrAdminRegions, eudrSourcingLocations } =
await fixtures.GivenEUDRAdminRegions();
const eudrMaterial = await createMaterial({ name: 'EUDR Material' });
await fixtures.AndAssociatedMaterials(
[eudrMaterial],
[eudrSourcingLocations[0]],
);
const eudrSupplier = await createSupplier({ name: 'EUDR Supplier' });
await fixtures.AndAssociatedSuppliers(
[eudrSupplier],
await testManager.GivenEUDRAdminRegions();
const eudrMaterials = await testManager.AndAssociatedMaterials([
eudrSourcingLocations[0],
]);
const eudrSuppliers = await testManager.AndAssociatedSuppliers(
eudrSourcingLocations,
);
const response = await fixtures.WhenIRequestEUDRAdminRegionWithFilters({
app: testApplication,
jwtToken,
materialIds: [eudrMaterial.id],
supplierIds: [eudrSupplier.id],
await testManager.WhenIRequestEUDRAdminRegions({
'materialIds[]': [eudrMaterials[0].id],
'producerIds[]': eudrSuppliers.map((s) => s.id),
});
fixtures.ThenIShouldOnlyReceiveFilteredEUDRAdminRegions(response, [
testManager.ThenIShouldOnlyReceiveCorrespondingAdminRegions([
eudrAdminRegions[0],
]);
});
Expand Down
100 changes: 40 additions & 60 deletions api/test/e2e/admin-regions/fixtures.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,25 @@
import * as request from 'supertest';
import {
LOCATION_TYPES,
SourcingLocation,
} from 'modules/sourcing-locations/sourcing-location.entity';
import { createAdminRegion, createSourcingLocation } from '../../entity-mocks';
import { TestApplication } from '../../utils/application-manager';
import { AdminRegion } from 'modules/admin-regions/admin-region.entity';
import { AndAssociatedMaterials } from '../../common-steps/and-associated-materials';
import { AndAssociatedSuppliers } from '../../common-steps/and-associated-suppliers';
import { Material } from 'modules/materials/material.entity';
import { Supplier } from '../../../src/modules/suppliers/supplier.entity';
import { TestManager } from '../../utils/test-manager';

export const adminRegionsFixtures = () => ({
GivenAdminRegionsOfSourcingLocations: async () => {
export class AdminRegionTestManager extends TestManager {
url = '/api/v1/admin-regions/';

constructor(manager: TestManager) {
super(manager.testApp, manager.jwtToken, manager.dataSource);
}

static async load() {
return new AdminRegionTestManager(await this.createManager());
}

GivenAdminRegionsOfSourcingLocations = async () => {
const adminRegion = await createAdminRegion({
name: 'Regular AdminRegion',
});
Expand All @@ -29,20 +36,24 @@ export const adminRegionsFixtures = () => ({
adminRegions: [adminRegion, adminRegion2],
sourcingLocations: [sourcingLocation1, sourcingLocation2],
};
},
AndAssociatedMaterials: async (
materials: Material[],
};
AndAssociatedMaterials = async (
sourcingLocations: SourcingLocation[],
materialNames?: string[],
) => {
return AndAssociatedMaterials(materials, sourcingLocations);
},
AndAssociatedSuppliers: async (
suppliers: Supplier[],
const materials = await this.createMaterials(materialNames);
await AndAssociatedMaterials(materials, sourcingLocations);
return materials;
};
AndAssociatedSuppliers = async (
sourcingLocations: SourcingLocation[],
supplierNames?: string[],
) => {
return AndAssociatedSuppliers(suppliers, sourcingLocations);
},
GivenEUDRAdminRegions: async () => {
const suppliers = await this.createSuppliers(supplierNames);
await AndAssociatedSuppliers(suppliers, sourcingLocations);
return suppliers;
};
GivenEUDRAdminRegions = async () => {
const adminRegion = await createAdminRegion({
name: 'EUDR AdminRegion',
});
Expand All @@ -61,57 +72,26 @@ export const adminRegionsFixtures = () => ({
eudrAdminRegions: [adminRegion, adminRegion2],
eudrSourcingLocations: [eudrSourcingLocation1, eudrSourcingLocation2],
};
},
WhenIRequestEUDRAdminRegions: async (options: {
app: TestApplication;
jwtToken: string;
}) => {
return request(options.app.getHttpServer())
.get(`/api/v1/admin-regions/trees/eudr`)
.set('Authorization', `Bearer ${options.jwtToken}`);
},
WhenIRequestEUDRAdminRegionWithFilters: async (options: {
app: TestApplication;
jwtToken: string;
supplierIds?: string[];
materialIds?: string[];
};
WhenIRequestEUDRAdminRegions = async (filters?: {
'producerIds[]'?: string[];
'materialIds[]'?: string[];
}) => {
return request(options.app.getHttpServer())
.get(`/api/v1/admin-regions/trees/eudr`)
.set('Authorization', `Bearer ${options.jwtToken}`)
.query({
'producerIds[]': options.supplierIds,
'materialIds[]': options.materialIds,
});
},
ThenIShouldOnlyReceiveFilteredEUDRAdminRegions: (
response: request.Response,
eudrAdminRegions: AdminRegion[],
) => {
expect(response.status).toBe(200);
expect(response.body.data.length).toBe(eudrAdminRegions.length);
for (const adminRegion of eudrAdminRegions) {
expect(
response.body.data.find(
(adminRegionResponse: AdminRegion) =>
adminRegionResponse.id === adminRegion.id,
),
).toBeDefined();
}
},
ThenIShouldOnlyReceiveEUDRAdminRegions: (
response: request.Response,
return this.GET({ url: `${this.url}trees/eudr`, query: filters });
};

ThenIShouldOnlyReceiveCorrespondingAdminRegions = (
eudrAdminRegions: AdminRegion[],
) => {
expect(response.status).toBe(200);
expect(response.body.data.length).toBe(eudrAdminRegions.length);
expect(this.response!.status).toBe(200);
expect(this.response!.body.data.length).toBe(eudrAdminRegions.length);
for (const adminRegion of eudrAdminRegions) {
expect(
response.body.data.find(
this.response!.body.data.find(
(adminRegionResponse: AdminRegion) =>
adminRegionResponse.id === adminRegion.id,
),
).toBeDefined();
}
},
});
};
}
4 changes: 2 additions & 2 deletions api/test/utils/application-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ export default class ApplicationManager {

const testingModuleBuilder: TestingModuleBuilder =
initTestingModuleBuilder ||
(await Test.createTestingModule({
Test.createTestingModule({
imports: [AppModule],
})
.overrideProvider('IEmailService')
.useClass(MockEmailService));
.useClass(MockEmailService);

ApplicationManager.testApplication.moduleFixture =
await testingModuleBuilder.compile();
Expand Down
8 changes: 8 additions & 0 deletions api/test/utils/random-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
export const randomName = (length = 10): string => {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
let result = '';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
};
99 changes: 99 additions & 0 deletions api/test/utils/test-manager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { DataSource } from 'typeorm';
import ApplicationManager, { TestApplication } from './application-manager';
import { clearTestDataFromDatabase } from './database-test-helper';
import { setupTestUser } from './userAuth';
import * as request from 'supertest';
import {
createGeoRegion,
createMaterial,
createSupplier,
} from '../entity-mocks';
import { Material } from 'modules/materials/material.entity';
import { Supplier } from 'modules/suppliers/supplier.entity';
import { GeoRegion } from 'modules/geo-regions/geo-region.entity';
import { randomName } from './random-name';

export class TestManager {
testApp: TestApplication;
jwtToken: string;
dataSource: DataSource;
response?: request.Response;
materials?: Material[];
suppliers?: Supplier[];
geoRegions?: GeoRegion[];

constructor(app: TestApplication, jwtToken: string, dataSource: DataSource) {
this.testApp = app;
this.jwtToken = jwtToken;
this.dataSource = dataSource;
}

static async createManager() {
const testApplication = await ApplicationManager.init();
const dataSource = testApplication.get<DataSource>(DataSource);
const { jwtToken } = await setupTestUser(testApplication);
return new TestManager(testApplication, jwtToken, dataSource);
}

async refreshState() {
const { jwtToken } = await setupTestUser(this.testApp);
this.jwtToken = jwtToken;
this.materials = undefined;
this.suppliers = undefined;
this.geoRegions = undefined;
this.response = undefined;
}

async clearDatabase() {
await clearTestDataFromDatabase(this.dataSource);
}

async GET(options: { url: string; query?: object | string }) {
this.response = await request(this.testApp.getHttpServer())
.get(options.url)
.query(options?.query || '')
.set('Authorization', `Bearer ${this.token}`);
return this.response;
}

get token() {
if (!this.jwtToken) {
throw new Error('TestManager has no token available!');
}
return this.jwtToken;
}

async close() {
await this.testApp.close();
}

async createMaterials(names?: string[]) {
const namesToCreate = names || [randomName()];
const createdMaterials: Material[] = [];
for (let i = 0; i < namesToCreate.length; i++) {
createdMaterials.push(await createMaterial({ name: namesToCreate[i] }));
}
this.materials?.push(...createdMaterials);
return createdMaterials;
}

async createSuppliers(names?: string[]) {
const namesToCreate = names || [randomName()];
const createdSuppliers: Supplier[] = [];
for (let i = 0; i < namesToCreate.length; i++) {
createdSuppliers.push(await createSupplier({ name: namesToCreate[i] }));
}
this.suppliers?.push(...createdSuppliers);
return createdSuppliers;
}

async createGeoRegion(names?: string[]) {
const namesToCreate = names || [randomName()];
const createdGeoRegions: GeoRegion[] = [];
for (let i = 0; i < namesToCreate.length; i++) {
createdGeoRegions.push(await createGeoRegion({ name: namesToCreate[i] }));
}
this.geoRegions?.push(...createdGeoRegions);
return createdGeoRegions;
}
}
Loading

0 comments on commit 596d9a6

Please sign in to comment.