diff --git a/apps/server/src/core/error/loggable/axios-error.loggable.spec.ts b/apps/server/src/core/error/loggable/axios-error.loggable.spec.ts index 201bf90c600..6cad4f36288 100644 --- a/apps/server/src/core/error/loggable/axios-error.loggable.spec.ts +++ b/apps/server/src/core/error/loggable/axios-error.loggable.spec.ts @@ -1,4 +1,4 @@ -import { axiosErrorFactory } from '@shared/testing/factory'; +import { axiosErrorFactory } from '@testing/factory/axios-error.factory'; import { AxiosError } from 'axios'; import { AxiosErrorLoggable } from './axios-error.loggable'; diff --git a/apps/server/src/infra/auth-guard/decorator/jwt-auth.decorator.spec.ts b/apps/server/src/infra/auth-guard/decorator/jwt-auth.decorator.spec.ts index 4f39b8b52c0..ec36bdc2df6 100644 --- a/apps/server/src/infra/auth-guard/decorator/jwt-auth.decorator.spec.ts +++ b/apps/server/src/infra/auth-guard/decorator/jwt-auth.decorator.spec.ts @@ -1,57 +1,49 @@ /* eslint-disable @typescript-eslint/no-unused-vars */ -import { ServerTestModule } from '@modules/server/server.module'; -import { Controller, ExecutionContext, Get, INestApplication } from '@nestjs/common'; +import { EntityManager } from '@mikro-orm/mongodb'; +import { ServerTestModule } from '@modules/server'; +import { Controller, Get, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import request from 'supertest'; -import { JwtAuthGuard } from '../guard'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { ICurrentUser } from '../interface'; import { CurrentUser, JWT, JwtAuthentication } from './jwt-auth.decorator'; +const baseRouteName = '/test-decorator'; @JwtAuthentication() -@Controller('test_decorator_currentUser') +@Controller(baseRouteName) export class TestDecoratorCurrentUserController { - @Get('test') - async test(@CurrentUser() currentUser: ICurrentUser): Promise { - await Promise.resolve(currentUser); + @Get('currentUser') + test(@CurrentUser() currentUser: ICurrentUser): ICurrentUser { + return currentUser; } } @JwtAuthentication() -@Controller('test_decorator_JWT') +@Controller(baseRouteName) export class TestDecoratorJWTController { - @Get('test') - async test(@JWT() jwt: string): Promise { - await Promise.resolve(jwt); + @Get('jwt') + test(@JWT() jwt: string): string { + return jwt; } } -describe('Jwt auth decorator', () => { +describe('Decorators', () => { let app: INestApplication; - let currentUser: ICurrentUser; let module: TestingModule; + let em: EntityManager; + let apiClient: TestApiClient; beforeAll(async () => { module = await Test.createTestingModule({ imports: [ServerTestModule], - controllers: [ - TestDecoratorCurrentUserController, - TestDecoratorJWTController, - // TestDecoratorAuthenticateController, - ], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - // @ts-expect-error Testcase - req.user = currentUser; - return true; - }, - }) - .compile(); + controllers: [TestDecoratorCurrentUserController, TestDecoratorJWTController], + }).compile(); app = module.createNestApplication(); await app.init(); + + em = module.get(EntityManager); + apiClient = new TestApiClient(app, baseRouteName); }); afterAll(async () => { @@ -60,30 +52,88 @@ describe('Jwt auth decorator', () => { }); describe('JwtAuthentication', () => { - it('should throw with UnauthorizedException if no jwt can be extracted from request context', async () => { - const response = await request(app.getHttpServer()).get('/test_decorator_JWT/test'); + describe('when user is not logged in', () => { + it('should throw with UnauthorizedException', async () => { + const response = await apiClient.get('/jwt'); - expect(response.statusCode).toEqual(401); + expect(response.statusCode).toEqual(401); + }); }); - it('should succeed if it can get the jwt', async () => { - const jwt = 'example-jwt'; - const response = await request(app.getHttpServer()) - .get('/test_decorator_JWT/test') - .set('Authorization', `Bearer ${jwt}`); + describe('when user is logged in', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + + await em.persistAndFlush([teacherAccount, teacherUser]); + em.clear(); + + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, teacherUser }; + }; + + it('should return status 200 for successful request.', async () => { + const { loggedInClient } = await setup(); - expect(response.statusCode).toEqual(200); + const response = await loggedInClient.get('/jwt'); + + expect(response.statusCode).toEqual(200); + }); + + it('should return jwt token.', async () => { + const { loggedInClient } = await setup(); + + const response = await loggedInClient.get('/jwt'); + // @ts-expect-error Testcase + expect(`Bearer ${response.text}`).toEqual(loggedInClient.authHeader); + }); }); }); describe('CurrentUser', () => { - it('should throw with UnauthorizedException if no jwt user data can be extracted from request context', async () => { - // @ts-expect-error Testcase - currentUser = undefined; + describe('when user is not logged in', () => { + it('should throw with UnauthorizedException', async () => { + const response = await apiClient.get('/currentUser'); + expect(response.statusCode).toEqual(401); + }); + }); + + describe('when user is logged in', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + + await em.persistAndFlush([teacherAccount, teacherUser]); + em.clear(); + + const loggedInClient = await apiClient.login(teacherAccount); + + const expectedCurrentUser = { + accountId: teacherAccount.id, + isExternalUser: teacherUser.externalId !== undefined, + roles: [teacherUser.roles[0].id], + schoolId: teacherUser.school.id, + support: false, + userId: teacherUser.id, + }; + + return { loggedInClient, expectedCurrentUser }; + }; + + it('should return status 200 for successful request.', async () => { + const { loggedInClient } = await setup(); + + const response = await loggedInClient.get('/currentUser'); + + expect(response.statusCode).toEqual(200); + }); + + it('should return currentUser.', async () => { + const { loggedInClient, expectedCurrentUser } = await setup(); - const response = await request(app.getHttpServer()).get('/test_decorator_currentUser/test'); + const response = await loggedInClient.get('/currentUser'); - expect(response.statusCode).toEqual(401); + expect(response.body).toEqual(expectedCurrentUser); + }); }); }); }); diff --git a/apps/server/src/infra/auth-guard/mapper/current-user.factory.spec.ts b/apps/server/src/infra/auth-guard/mapper/current-user.factory.spec.ts index 7f744447a07..1b6daaa5628 100644 --- a/apps/server/src/infra/auth-guard/mapper/current-user.factory.spec.ts +++ b/apps/server/src/infra/auth-guard/mapper/current-user.factory.spec.ts @@ -1,4 +1,4 @@ -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { ICurrentUser } from '../interface'; import { CurrentUserBuilder } from './current-user.factory'; diff --git a/apps/server/src/infra/auth-guard/mapper/jwt.factory.spec.ts b/apps/server/src/infra/auth-guard/mapper/jwt.factory.spec.ts index 3239d691389..408c15c7a38 100644 --- a/apps/server/src/infra/auth-guard/mapper/jwt.factory.spec.ts +++ b/apps/server/src/infra/auth-guard/mapper/jwt.factory.spec.ts @@ -1,4 +1,5 @@ -import { currentUserFactory, setupEntities } from '@shared/testing'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { CreateJwtPayload } from '../interface'; import { JwtPayloadFactory } from './jwt.factory'; diff --git a/apps/server/src/infra/auth-guard/strategy/jwt.strategy.spec.ts b/apps/server/src/infra/auth-guard/strategy/jwt.strategy.spec.ts index 3b142b3e0cd..6ae8d2c96a3 100644 --- a/apps/server/src/infra/auth-guard/strategy/jwt.strategy.spec.ts +++ b/apps/server/src/infra/auth-guard/strategy/jwt.strategy.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { UnauthorizedException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { jwtPayloadFactory } from '@shared/testing'; +import { jwtPayloadFactory } from '@testing/factory/jwtpayload.factory'; import { JwtValidationAdapter } from '../adapter/jwt-validation.adapter'; import { JwtStrategy } from './jwt.strategy'; diff --git a/apps/server/src/infra/auth-guard/strategy/ws-jwt.strategy.spec.ts b/apps/server/src/infra/auth-guard/strategy/ws-jwt.strategy.spec.ts index 5b5ecf068a1..5a65bedab67 100644 --- a/apps/server/src/infra/auth-guard/strategy/ws-jwt.strategy.spec.ts +++ b/apps/server/src/infra/auth-guard/strategy/ws-jwt.strategy.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { WsException } from '@nestjs/websockets'; -import { jwtPayloadFactory } from '@shared/testing'; +import { jwtPayloadFactory } from '@testing/factory/jwtpayload.factory'; import { JwtValidationAdapter } from '../adapter'; import { WsJwtStrategy } from './ws-jwt.strategy'; diff --git a/apps/server/src/infra/calendar/service/calendar.service.spec.ts b/apps/server/src/infra/calendar/service/calendar.service.spec.ts index bfbf5e0396b..74780d5059d 100644 --- a/apps/server/src/infra/calendar/service/calendar.service.spec.ts +++ b/apps/server/src/infra/calendar/service/calendar.service.spec.ts @@ -1,23 +1,23 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Configuration } from '@hpi-schul-cloud/commons/lib'; import { CalendarEventDto, CalendarService } from '@infra/calendar'; -import { HttpService } from '@nestjs/axios'; -import { HttpStatus, InternalServerErrorException } from '@nestjs/common'; -import { Test, TestingModule } from '@nestjs/testing'; -import { axiosResponseFactory } from '@shared/testing'; -import { AxiosResponse } from 'axios'; -import { of, throwError } from 'rxjs'; -import { Logger } from '@src/core/logger'; -import { EntityId } from '@shared/domain/types'; import { DomainDeletionReportBuilder, DomainName, DomainOperationReportBuilder, OperationType, } from '@modules/deletion'; +import { HttpService } from '@nestjs/axios'; +import { HttpStatus, InternalServerErrorException } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { EntityId } from '@shared/domain/types'; +import { Logger } from '@src/core/logger'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; +import { AxiosResponse } from 'axios'; +import { of, throwError } from 'rxjs'; +import { CalendarEventId } from '../interface/calendar-event-id.interface'; import { CalendarEvent } from '../interface/calendar-event.interface'; import { CalendarMapper } from '../mapper/calendar.mapper'; -import { CalendarEventId } from '../interface/calendar-event-id.interface'; describe('CalendarServiceSpec', () => { let module: TestingModule; diff --git a/apps/server/src/infra/collaborative-storage/strategy/nextcloud/nextcloud.client.spec.ts b/apps/server/src/infra/collaborative-storage/strategy/nextcloud/nextcloud.client.spec.ts index 225ddac258d..b6bf832332a 100644 --- a/apps/server/src/infra/collaborative-storage/strategy/nextcloud/nextcloud.client.spec.ts +++ b/apps/server/src/infra/collaborative-storage/strategy/nextcloud/nextcloud.client.spec.ts @@ -3,8 +3,8 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { HttpService } from '@nestjs/axios'; import { NotFoundException, NotImplementedException, UnprocessableEntityException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { axiosResponseFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { AxiosResponse } from 'axios'; import { Observable, of } from 'rxjs'; import { NextcloudClient } from './nextcloud.client'; diff --git a/apps/server/src/infra/collaborative-storage/strategy/nextcloud/nextcloud.strategy.spec.ts b/apps/server/src/infra/collaborative-storage/strategy/nextcloud/nextcloud.strategy.spec.ts index ec68c9a3968..9b0ee9a5d95 100644 --- a/apps/server/src/infra/collaborative-storage/strategy/nextcloud/nextcloud.strategy.spec.ts +++ b/apps/server/src/infra/collaborative-storage/strategy/nextcloud/nextcloud.strategy.spec.ts @@ -10,8 +10,11 @@ import { LtiToolDO } from '@shared/domain/domainobject/ltitool.do'; import { LtiPrivacyPermission, LtiRoleType, User } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; import { LtiToolRepo } from '@shared/repo'; -import { ltiToolDOFactory, pseudonymFactory, setupEntities, userDoFactory, userFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { ltiToolDOFactory, pseudonymFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { TeamRolePermissionsDto } from '../../dto/team-role-permissions.dto'; import { NextcloudClient } from './nextcloud.client'; import { NextcloudStrategy } from './nextcloud.strategy'; diff --git a/apps/server/src/infra/database/management/database-management.service.spec.ts b/apps/server/src/infra/database/management/database-management.service.spec.ts index 5ac485c9222..7fb9d7c599c 100644 --- a/apps/server/src/infra/database/management/database-management.service.spec.ts +++ b/apps/server/src/infra/database/management/database-management.service.spec.ts @@ -2,7 +2,7 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { MikroORM } from '@mikro-orm/core'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { createCollections } from '@shared/testing'; +import { createCollections } from '@testing/create-collections'; import { DatabaseManagementService } from './database-management.service'; const randomChars = () => new ObjectId().toHexString(); diff --git a/apps/server/src/infra/identity-management/keycloak-configuration/service/keycloak-configuration.service.integration.spec.ts b/apps/server/src/infra/identity-management/keycloak-configuration/service/keycloak-configuration.service.integration.spec.ts index 01d7f066ca3..f1f0b3ab11c 100644 --- a/apps/server/src/infra/identity-management/keycloak-configuration/service/keycloak-configuration.service.integration.spec.ts +++ b/apps/server/src/infra/identity-management/keycloak-configuration/service/keycloak-configuration.service.integration.spec.ts @@ -5,8 +5,8 @@ import AuthenticationFlowRepresentation from '@keycloak/keycloak-admin-client/li import { EntityManager } from '@mikro-orm/mongodb'; import { ConfigModule } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { systemEntityFactory } from '@shared/testing/factory'; import { LoggerModule } from '@src/core/logger'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; import { v1 } from 'uuid'; import { KeycloakAdministrationService } from '../../keycloak-administration/service/keycloak-administration.service'; import { KeycloakConfigurationModule } from '../keycloak-configuration.module'; diff --git a/apps/server/src/infra/identity-management/keycloak-configuration/service/keycloak-migration.service.integration.spec.ts b/apps/server/src/infra/identity-management/keycloak-configuration/service/keycloak-migration.service.integration.spec.ts index 10b36b7197a..e235b1906e1 100644 --- a/apps/server/src/infra/identity-management/keycloak-configuration/service/keycloak-migration.service.integration.spec.ts +++ b/apps/server/src/infra/identity-management/keycloak-configuration/service/keycloak-migration.service.integration.spec.ts @@ -3,10 +3,10 @@ import KeycloakAdminClient from '@keycloak/keycloak-admin-client'; import { EntityManager } from '@mikro-orm/mongodb'; import { ConfigModule } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections } from '@shared/testing'; import { LoggerModule } from '@src/core/logger'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { accountFactory } from '@src/modules/account/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { v1 } from 'uuid'; import { KeycloakAdministrationService } from '../../keycloak-administration/service/keycloak-administration.service'; import { KeycloakConfigurationModule } from '../keycloak-configuration.module'; diff --git a/apps/server/src/infra/preview-generator/preview.producer.spec.ts b/apps/server/src/infra/preview-generator/preview.producer.spec.ts index e6c5b680aff..2110dc5adf5 100644 --- a/apps/server/src/infra/preview-generator/preview.producer.spec.ts +++ b/apps/server/src/infra/preview-generator/preview.producer.spec.ts @@ -3,8 +3,8 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { InternalServerErrorException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { setupEntities } from '@testing/setup-entities'; import { ErrorMapper, FilesPreviewEvents, FilesPreviewExchange } from '../rabbitmq'; import { PreviewFileOptions } from './interface'; import { PreviewProducer } from './preview.producer'; diff --git a/apps/server/src/infra/schulconnex-client/response/schulconnex-name-response.ts b/apps/server/src/infra/schulconnex-client/response/schulconnex-name-response.ts index 7cf7d9f5f54..157bacb7443 100644 --- a/apps/server/src/infra/schulconnex-client/response/schulconnex-name-response.ts +++ b/apps/server/src/infra/schulconnex-client/response/schulconnex-name-response.ts @@ -1,9 +1,13 @@ -import { IsString } from 'class-validator'; +import { IsOptional, IsString } from 'class-validator'; export class SchulconnexNameResponse { @IsString() - familienname!: string; + public familienname!: string; @IsString() - vorname!: string; + public vorname!: string; + + @IsOptional() + @IsString() + public rufname?: string; } diff --git a/apps/server/src/infra/schulconnex-client/schulconnex-rest-client.spec.ts b/apps/server/src/infra/schulconnex-client/schulconnex-rest-client.spec.ts index 49ad5e2fa29..fddba6e7090 100644 --- a/apps/server/src/infra/schulconnex-client/schulconnex-rest-client.spec.ts +++ b/apps/server/src/infra/schulconnex-client/schulconnex-rest-client.spec.ts @@ -1,8 +1,8 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { OauthAdapterService, OAuthTokenDto } from '@modules/oauth'; import { HttpService } from '@nestjs/axios'; -import { axiosResponseFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { of } from 'rxjs'; import { SchulconnexConfigurationMissingLoggable } from './loggable'; import { diff --git a/apps/server/src/infra/schulconnex-client/testing/schulconnex-response-factory.ts b/apps/server/src/infra/schulconnex-client/testing/schulconnex-response-factory.ts index c41e603e37e..78edb0e1a7c 100644 --- a/apps/server/src/infra/schulconnex-client/testing/schulconnex-response-factory.ts +++ b/apps/server/src/infra/schulconnex-client/testing/schulconnex-response-factory.ts @@ -8,6 +8,7 @@ export const schulconnexResponseFactory = Factory.define(() person: { name: { vorname: 'Hans', + rufname: 'Hansi', familienname: 'Peter', }, geburt: { diff --git a/apps/server/src/infra/sync/media-licenses/service/vidis-fetch.service.spec.ts b/apps/server/src/infra/sync/media-licenses/service/vidis-fetch.service.spec.ts index f8952db1973..efdec90b9be 100644 --- a/apps/server/src/infra/sync/media-licenses/service/vidis-fetch.service.spec.ts +++ b/apps/server/src/infra/sync/media-licenses/service/vidis-fetch.service.spec.ts @@ -7,8 +7,9 @@ import { MediaSourceBasicAuthConfigNotFoundLoggableException } from '@modules/me import { mediaSourceFactory } from '@modules/media-source/testing'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { axiosErrorFactory, axiosResponseFactory } from '@shared/testing'; import { AxiosErrorLoggable } from '@src/core/error/loggable'; +import { axiosErrorFactory } from '@testing/factory/axios-error.factory'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { AxiosResponse, RawAxiosRequestConfig } from 'axios'; import { vidisPageOfferFactory } from '../testing'; import { VidisFetchService } from './vidis-fetch.service'; diff --git a/apps/server/src/infra/sync/tsp/tsp-legacy-migration.service.integration.spec.ts b/apps/server/src/infra/sync/tsp/tsp-legacy-migration.service.integration.spec.ts index ee52feb75cf..8b60134417e 100644 --- a/apps/server/src/infra/sync/tsp/tsp-legacy-migration.service.integration.spec.ts +++ b/apps/server/src/infra/sync/tsp/tsp-legacy-migration.service.integration.spec.ts @@ -1,13 +1,15 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; import { SchoolFeature } from '@shared/domain/types'; -import { cleanupCollections, schoolEntityFactory, systemEntityFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; -import { MongoMemoryDatabaseModule } from '@src/infra/database'; import { SystemType } from '@src/modules/system'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; import { TspLegacyMigrationSystemMissingLoggable } from './loggable/tsp-legacy-migration-system-missing.loggable'; import { TspLegacyMigrationService } from './tsp-legacy-migration.service'; diff --git a/apps/server/src/infra/sync/tsp/tsp-sync-migration.service.spec.ts b/apps/server/src/infra/sync/tsp/tsp-sync-migration.service.spec.ts index fb3d1586757..2473509985c 100644 --- a/apps/server/src/infra/sync/tsp/tsp-sync-migration.service.spec.ts +++ b/apps/server/src/infra/sync/tsp/tsp-sync-migration.service.spec.ts @@ -5,9 +5,9 @@ import { UserService } from '@modules/user'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { UserSourceOptions } from '@shared/domain/domainobject/user-source-options.do'; -import { userDoFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; import { accountDoFactory } from '@src/modules/account/testing'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { TspSyncMigrationService } from './tsp-sync-migration.service'; import { TspSyncConfig } from './tsp-sync.config'; diff --git a/apps/server/src/infra/sync/tsp/tsp-sync.service.spec.ts b/apps/server/src/infra/sync/tsp/tsp-sync.service.spec.ts index 106565cdf7b..6871276568f 100644 --- a/apps/server/src/infra/sync/tsp/tsp-sync.service.spec.ts +++ b/apps/server/src/infra/sync/tsp/tsp-sync.service.spec.ts @@ -4,12 +4,13 @@ import { School, SchoolService } from '@modules/school'; import { SystemService, SystemType } from '@modules/system'; import { Test, TestingModule } from '@nestjs/testing'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { federalStateFactory, schoolYearFactory } from '@shared/testing'; import { FederalStateService, SchoolYearService } from '@src/modules/legacy-school'; import { FileStorageType, SchoolProps } from '@src/modules/school/domain'; import { FederalStateEntityMapper, SchoolYearEntityMapper } from '@src/modules/school/repo/mikro-orm/mapper'; import { schoolFactory } from '@src/modules/school/testing'; import { systemFactory } from '@src/modules/system/testing'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; import { TspSyncService } from './tsp-sync.service'; describe(TspSyncService.name, () => { diff --git a/apps/server/src/modules/account/api/account.uc.spec.ts b/apps/server/src/modules/account/api/account.uc.spec.ts index 40e60bc0907..a366aa2e80f 100644 --- a/apps/server/src/modules/account/api/account.uc.spec.ts +++ b/apps/server/src/modules/account/api/account.uc.spec.ts @@ -9,7 +9,10 @@ import { UnauthorizedException } from '@nestjs/common/exceptions/unauthorized.ex import { Role, User } from '@shared/domain/entity'; import { Permission, RoleName } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; -import { currentUserFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Account, AccountSave } from '../domain'; import { AccountEntity } from '../domain/entity/account.entity'; import { AccountService } from '../domain/services'; diff --git a/apps/server/src/modules/account/api/test/account.api.spec.ts b/apps/server/src/modules/account/api/test/account.api.spec.ts index 417e6a3a26b..c930aac7d8c 100644 --- a/apps/server/src/modules/account/api/test/account.api.spec.ts +++ b/apps/server/src/modules/account/api/test/account.api.spec.ts @@ -5,7 +5,11 @@ import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; import { Permission, RoleName } from '@shared/domain/interface'; -import { TestApiClient, cleanupCollections, roleFactory, schoolEntityFactory, userFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { AccountEntity } from '../../domain/entity/account.entity'; import { accountFactory } from '../../testing'; import { diff --git a/apps/server/src/modules/account/domain/services/account-db.service.spec.ts b/apps/server/src/modules/account/domain/services/account-db.service.spec.ts index 2669d1a8278..c1d257ce4d2 100644 --- a/apps/server/src/modules/account/domain/services/account-db.service.spec.ts +++ b/apps/server/src/modules/account/domain/services/account-db.service.spec.ts @@ -7,8 +7,9 @@ import { Test, TestingModule } from '@nestjs/testing'; import { EntityNotFoundError } from '@shared/common'; import { IdmAccount } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; -import { setupEntities, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import bcrypt from 'bcryptjs'; import { v1 } from 'uuid'; import { AccountConfig } from '../../account-config'; diff --git a/apps/server/src/modules/account/domain/services/account.service.integration.spec.ts b/apps/server/src/modules/account/domain/services/account.service.integration.spec.ts index 9d75d0a0308..f6b862e890a 100644 --- a/apps/server/src/modules/account/domain/services/account.service.integration.spec.ts +++ b/apps/server/src/modules/account/domain/services/account.service.integration.spec.ts @@ -2,6 +2,7 @@ import { createMock } from '@golevelup/ts-jest'; import { MongoMemoryDatabaseModule } from '@infra/database'; import { IdentityManagementModule, IdentityManagementService } from '@infra/identity-management'; import { KeycloakAdministrationService } from '@infra/identity-management/keycloak-administration/service/keycloak-administration.service'; +import { KeycloakIdentityManagementService } from '@infra/identity-management/keycloak/service/keycloak-identity-management.service'; import KeycloakAdminClient from '@keycloak/keycloak-admin-client-cjs/keycloak-admin-client-cjs-index'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { ConfigModule } from '@nestjs/config'; @@ -9,9 +10,8 @@ import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; import { IdmAccount } from '@shared/domain/interface'; import { UserRepo } from '@shared/repo'; -import { cleanupCollections } from '@shared/testing'; import { Logger } from '@src/core/logger'; -import { KeycloakIdentityManagementService } from '@src/infra/identity-management/keycloak/service/keycloak-identity-management.service'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { v1 } from 'uuid'; import { Account, AccountSave } from '..'; import { AccountRepo } from '../../repo/micro-orm/account.repo'; diff --git a/apps/server/src/modules/account/domain/services/account.service.spec.ts b/apps/server/src/modules/account/domain/services/account.service.spec.ts index 63d56f28f00..e93f6c8b11b 100644 --- a/apps/server/src/modules/account/domain/services/account.service.spec.ts +++ b/apps/server/src/modules/account/domain/services/account.service.spec.ts @@ -17,8 +17,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { AuthorizationError, EntityNotFoundError, ForbiddenOperationError, ValidationError } from '@shared/common'; import { User } from '@shared/domain/entity'; import { UserRepo } from '@shared/repo'; -import { schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import 'reflect-metadata'; import { Account, AccountSave, UpdateAccount } from '..'; import { AccountConfig } from '../../account-config'; diff --git a/apps/server/src/modules/account/repo/micro-orm/account.repo.integration.spec.ts b/apps/server/src/modules/account/repo/micro-orm/account.repo.integration.spec.ts index a20ee96bf16..7bf456df1a4 100644 --- a/apps/server/src/modules/account/repo/micro-orm/account.repo.integration.spec.ts +++ b/apps/server/src/modules/account/repo/micro-orm/account.repo.integration.spec.ts @@ -3,7 +3,8 @@ import { NotFoundError } from '@mikro-orm/core'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; -import { cleanupCollections, userFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { userFactory } from '@testing/factory/user.factory'; import { AccountEntity } from '../../domain/entity/account.entity'; import { accountDoFactory, accountFactory } from '../../testing'; import { AccountRepo } from './account.repo'; diff --git a/apps/server/src/modules/account/testing/account-do.factory.ts b/apps/server/src/modules/account/testing/account-do.factory.ts index ac56df2c552..ef8f31b6172 100644 --- a/apps/server/src/modules/account/testing/account-do.factory.ts +++ b/apps/server/src/modules/account/testing/account-do.factory.ts @@ -1,6 +1,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { Account, AccountProps } from '@modules/account'; -import { DomainObjectFactory } from '@shared/testing/factory/domainobject'; +import { DomainObjectFactory } from '@testing/factory/domainobject'; export const accountDoFactory = DomainObjectFactory.define(Account, ({ sequence, params }) => { return { diff --git a/apps/server/src/modules/account/testing/account.factory.ts b/apps/server/src/modules/account/testing/account.factory.ts index 0cfa746e4cb..aa745f6d15c 100644 --- a/apps/server/src/modules/account/testing/account.factory.ts +++ b/apps/server/src/modules/account/testing/account.factory.ts @@ -3,8 +3,8 @@ import { User } from '@shared/domain/entity'; import { EntityId } from '@shared/domain/types'; import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing/factory/base.factory'; -import { AccountEntity, IdmAccountProperties } from '@src/modules/account/domain/entity/account.entity'; +import { AccountEntity, IdmAccountProperties } from '@modules/account/domain/entity/account.entity'; +import { BaseFactory } from '@testing/factory/base.factory'; import { DeepPartial } from 'fishery'; export const defaultTestPassword = 'DummyPasswd!1'; diff --git a/apps/server/src/modules/alert/adapter/status.adapter.spec.ts b/apps/server/src/modules/alert/adapter/status.adapter.spec.ts index c35c17bd001..0b308f7b256 100644 --- a/apps/server/src/modules/alert/adapter/status.adapter.spec.ts +++ b/apps/server/src/modules/alert/adapter/status.adapter.spec.ts @@ -1,14 +1,14 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { HttpService } from '@nestjs/axios'; import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { ConfigService } from '@nestjs/config'; import { ServerConfig } from '@modules/server'; -import { axiosResponseFactory } from '@shared/testing'; -import { of, throwError } from 'rxjs'; +import { HttpService } from '@nestjs/axios'; +import { ConfigService } from '@nestjs/config'; +import { Test, TestingModule } from '@nestjs/testing'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { AxiosError } from 'axios'; -import { StatusAdapter } from './status.adapter'; -import { ComponentDto, ComponentResponse, IncidentsResponse } from './dto'; +import { of, throwError } from 'rxjs'; import { createComponent, createIncident } from '../testing'; +import { ComponentDto, ComponentResponse, IncidentsResponse } from './dto'; +import { StatusAdapter } from './status.adapter'; describe('StatusAdapter', () => { const incidentsPath = '/api/v1/incidents'; diff --git a/apps/server/src/modules/alert/controller/api-test/alert.api.spec.ts b/apps/server/src/modules/alert/controller/api-test/alert.api.spec.ts index 4913bdf0fad..c6f3834aa79 100644 --- a/apps/server/src/modules/alert/controller/api-test/alert.api.spec.ts +++ b/apps/server/src/modules/alert/controller/api-test/alert.api.spec.ts @@ -1,15 +1,15 @@ -import { INestApplication } from '@nestjs/common'; import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { HttpService } from '@nestjs/axios'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import request from 'supertest'; -import { of } from 'rxjs'; -import { axiosResponseFactory } from '@shared/testing'; import { SchulcloudTheme } from '@shared/domain/types'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; +import { of } from 'rxjs'; +import request from 'supertest'; import { serverConfig, ServerTestModule } from '../../../server'; +import { ComponentDto, ComponentResponse, IncidentsResponse } from '../../adapter/dto'; import { createComponent, createIncident } from '../../testing'; import { AlertResponse } from '../dto'; -import { ComponentDto, ComponentResponse, IncidentsResponse } from '../../adapter/dto'; describe('Alert Controller api', () => { const alertPath = '/alert'; diff --git a/apps/server/src/modules/authentication/controllers/api-test/login.api.spec.ts b/apps/server/src/modules/authentication/controllers/api-test/login.api.spec.ts index 4ce70bc6408..dd27cc46167 100644 --- a/apps/server/src/modules/authentication/controllers/api-test/login.api.spec.ts +++ b/apps/server/src/modules/authentication/controllers/api-test/login.api.spec.ts @@ -1,4 +1,6 @@ import { EntityManager } from '@mikro-orm/core'; +import { AccountEntity } from '@modules/account/domain/entity/account.entity'; +import { accountFactory } from '@modules/account/testing'; import { OauthTokenResponse } from '@modules/oauth/service/dto'; import { ServerTestModule } from '@modules/server/server.module'; import { SystemEntity } from '@modules/system/entity'; @@ -6,9 +8,11 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity, User } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; -import { JwtTestFactory, roleFactory, schoolEntityFactory, systemEntityFactory, userFactory } from '@shared/testing'; -import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; -import { accountFactory } from '@src/modules/account/testing'; +import { JwtTestFactory } from '@testing/factory/jwt.test.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userFactory } from '@testing/factory/user.factory'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import jwt from 'jsonwebtoken'; diff --git a/apps/server/src/modules/authentication/controllers/api-test/logout.api.spec.ts b/apps/server/src/modules/authentication/controllers/api-test/logout.api.spec.ts index a9b11a5dc8a..732ceaa1aa0 100644 --- a/apps/server/src/modules/authentication/controllers/api-test/logout.api.spec.ts +++ b/apps/server/src/modules/authentication/controllers/api-test/logout.api.spec.ts @@ -1,28 +1,25 @@ -import { EntityManager } from '@mikro-orm/mongodb'; import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; -import { ServerTestModule } from '@modules/server/server.module'; -import { serverConfig, ServerConfig } from '@modules/server'; -import { oauthSessionTokenEntityFactory } from '@modules/oauth/testing'; +import { EntityManager } from '@mikro-orm/mongodb'; import { OauthSessionTokenEntity } from '@modules/oauth/entity'; +import { oauthSessionTokenEntityFactory } from '@modules/oauth/testing'; +import { serverConfig, ServerConfig } from '@modules/server'; +import { ServerTestModule } from '@modules/server/server.module'; import { systemOauthConfigFactory } from '@modules/system/testing'; import { CACHE_MANAGER } from '@nestjs/cache-manager'; import { ExecutionContext, HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { - cleanupCollections, - JwtTestFactory, - currentUserFactory, - schoolEntityFactory, - systemEntityFactory, - systemOauthConfigEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; +import { JwtTestFactory } from '@testing/factory/jwt.test.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory, systemOauthConfigEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import axios from 'axios'; +import MockAdapter from 'axios-mock-adapter'; import { Cache } from 'cache-manager'; -import { Response } from 'supertest'; import { Request } from 'express'; -import MockAdapter from 'axios-mock-adapter'; -import axios from 'axios'; +import { Response } from 'supertest'; jest.mock('jwks-rsa', () => () => { return { diff --git a/apps/server/src/modules/authentication/errors/external-system-logout-failed.loggable-exception.spec.ts b/apps/server/src/modules/authentication/errors/external-system-logout-failed.loggable-exception.spec.ts index 4211be1c2ac..e5b3f2e50a1 100644 --- a/apps/server/src/modules/authentication/errors/external-system-logout-failed.loggable-exception.spec.ts +++ b/apps/server/src/modules/authentication/errors/external-system-logout-failed.loggable-exception.spec.ts @@ -1,5 +1,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { axiosErrorFactory, axiosResponseFactory } from '@shared/testing'; +import { axiosErrorFactory } from '@testing/factory/axios-error.factory'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { ExternalSystemLogoutFailedLoggableException } from './external-system-logout-failed.loggable-exception'; describe(ExternalSystemLogoutFailedLoggableException.name, () => { diff --git a/apps/server/src/modules/authentication/mapper/current-user.mapper.spec.ts b/apps/server/src/modules/authentication/mapper/current-user.mapper.spec.ts index 19f243333e9..ae79b552670 100644 --- a/apps/server/src/modules/authentication/mapper/current-user.mapper.spec.ts +++ b/apps/server/src/modules/authentication/mapper/current-user.mapper.spec.ts @@ -1,7 +1,11 @@ import { ValidationError } from '@shared/common'; import { UserDO } from '@shared/domain/domainobject/user.do'; import { Permission, RoleName } from '@shared/domain/interface'; -import { roleFactory, schoolEntityFactory, setupEntities, userDoFactory, userFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { OauthCurrentUser } from '../interface'; import { CurrentUserMapper } from './current-user.mapper'; diff --git a/apps/server/src/modules/authentication/services/authentication.service.spec.ts b/apps/server/src/modules/authentication/services/authentication.service.spec.ts index 35a015c7cde..06daf10162f 100644 --- a/apps/server/src/modules/authentication/services/authentication.service.spec.ts +++ b/apps/server/src/modules/authentication/services/authentication.service.spec.ts @@ -2,27 +2,25 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { JwtPayloadFactory } from '@infra/auth-guard'; import { DefaultEncryptionService, EncryptionService, SymmetricKeyEncryptionService } from '@infra/encryption'; import { Account, AccountService } from '@modules/account'; -import { OauthConfig } from '@modules/system'; -import { OauthSessionTokenService } from '@modules/oauth'; import { accountDoFactory } from '@modules/account/testing'; -import { systemFactory } from '@modules/system/testing'; -import { oauthSessionTokenFactory } from '@modules/oauth/testing'; +import { OauthSessionTokenService } from '@modules/oauth'; import { OauthConfigMissingLoggableException } from '@modules/oauth/loggable'; +import { oauthSessionTokenFactory } from '@modules/oauth/testing'; +import { OauthConfig } from '@modules/system'; +import { systemFactory } from '@modules/system/testing'; +import { HttpService } from '@nestjs/axios'; import { UnauthorizedException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { JwtService } from '@nestjs/jwt'; import { Test, TestingModule } from '@nestjs/testing'; -import { HttpService } from '@nestjs/axios'; -import { - axiosErrorFactory, - axiosResponseFactory, - currentUserFactory, - setupEntities, - userFactory, -} from '@shared/testing'; import { Logger } from '@src/core/logger'; -import jwt from 'jsonwebtoken'; +import { axiosErrorFactory } from '@testing/factory/axios-error.factory'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { AxiosHeaders, AxiosRequestConfig } from 'axios'; +import jwt from 'jsonwebtoken'; import { of, throwError } from 'rxjs'; import { BruteForceError, diff --git a/apps/server/src/modules/authentication/services/logout.service.spec.ts b/apps/server/src/modules/authentication/services/logout.service.spec.ts index bb4954641a4..989b6414551 100644 --- a/apps/server/src/modules/authentication/services/logout.service.spec.ts +++ b/apps/server/src/modules/authentication/services/logout.service.spec.ts @@ -8,7 +8,8 @@ import { systemFactory, systemOauthConfigFactory } from '@modules/system/testing import { UserService } from '@modules/user'; import { Test, TestingModule } from '@nestjs/testing'; import { NotFoundLoggableException } from '@shared/common/loggable-exception'; -import { JwtTestFactory, userDoFactory } from '@shared/testing'; +import { JwtTestFactory } from '@testing/factory/jwt.test.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { AccountSystemMismatchLoggableException, InvalidTokenLoggableException } from '../loggable'; import { LogoutService } from './logout.service'; diff --git a/apps/server/src/modules/authentication/strategy/ldap.strategy.spec.ts b/apps/server/src/modules/authentication/strategy/ldap.strategy.spec.ts index 95e98a18aca..3b47b22107a 100644 --- a/apps/server/src/modules/authentication/strategy/ldap.strategy.spec.ts +++ b/apps/server/src/modules/authentication/strategy/ldap.strategy.spec.ts @@ -1,6 +1,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ICurrentUser } from '@infra/auth-guard'; import { Account } from '@modules/account'; +import { accountDoFactory, defaultTestPassword, defaultTestPasswordHash } from '@modules/account/testing'; import { System, SystemService } from '@modules/system'; import { systemFactory } from '@modules/system/testing'; import { UnauthorizedException } from '@nestjs/common'; @@ -10,9 +11,11 @@ import { LegacySchoolDo } from '@shared/domain/domainobject'; import { User } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; import { LegacySchoolRepo, UserRepo } from '@shared/repo'; -import { legacySchoolDoFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; -import { accountDoFactory, defaultTestPassword, defaultTestPasswordHash } from '@src/modules/account/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LdapAuthorizationBodyParams } from '../controllers/dto'; import { AuthenticationService } from '../services/authentication.service'; import { LdapService } from '../services/ldap.service'; diff --git a/apps/server/src/modules/authentication/strategy/local.strategy.spec.ts b/apps/server/src/modules/authentication/strategy/local.strategy.spec.ts index a28a2d362b6..39ec95796ab 100644 --- a/apps/server/src/modules/authentication/strategy/local.strategy.spec.ts +++ b/apps/server/src/modules/authentication/strategy/local.strategy.spec.ts @@ -1,14 +1,15 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { IdentityManagementOauthService } from '@infra/identity-management'; import { Account } from '@modules/account'; +import { accountDoFactory } from '@modules/account/testing'; import { ServerConfig } from '@modules/server'; import { UnauthorizedException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { User } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; import { UserRepo } from '@shared/repo'; -import { setupEntities, userFactory } from '@shared/testing'; -import { accountDoFactory } from '@src/modules/account/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import bcrypt from 'bcryptjs'; import { AuthenticationService } from '../services/authentication.service'; import { LocalStrategy } from './local.strategy'; diff --git a/apps/server/src/modules/authentication/strategy/oauth2.strategy.spec.ts b/apps/server/src/modules/authentication/strategy/oauth2.strategy.spec.ts index 1efe72daaf1..c7e5a6f313a 100644 --- a/apps/server/src/modules/authentication/strategy/oauth2.strategy.spec.ts +++ b/apps/server/src/modules/authentication/strategy/oauth2.strategy.spec.ts @@ -6,7 +6,8 @@ import { Test, TestingModule } from '@nestjs/testing'; import { UserDO } from '@shared/domain/domainobject/user.do'; import { RoleName } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; -import { JwtTestFactory, userDoFactory } from '@shared/testing'; +import { JwtTestFactory } from '@testing/factory/jwt.test.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { OauthCurrentUser } from '../interface'; import { AccountNotFoundLoggableException, diff --git a/apps/server/src/modules/authentication/uc/login.uc.spec.ts b/apps/server/src/modules/authentication/uc/login.uc.spec.ts index adc3bb2b6b5..180a20d8769 100644 --- a/apps/server/src/modules/authentication/uc/login.uc.spec.ts +++ b/apps/server/src/modules/authentication/uc/login.uc.spec.ts @@ -1,6 +1,6 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Test, TestingModule } from '@nestjs/testing'; -import { currentUserFactory } from '@shared/testing'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; import { AuthenticationService } from '../services/authentication.service'; import { LoginDto } from './dto'; import { LoginUc } from './login.uc'; diff --git a/apps/server/src/modules/authentication/uc/logout.uc.spec.ts b/apps/server/src/modules/authentication/uc/logout.uc.spec.ts index ba39be4ab67..c17ed65c193 100644 --- a/apps/server/src/modules/authentication/uc/logout.uc.spec.ts +++ b/apps/server/src/modules/authentication/uc/logout.uc.spec.ts @@ -1,17 +1,18 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { accountDoFactory } from '@modules/account/testing'; +import { OauthSessionTokenService } from '@modules/oauth'; +import { oauthSessionTokenFactory } from '@modules/oauth/testing'; +import { SystemService } from '@modules/system'; +import { systemFactory } from '@modules/system/testing'; import { BadRequestException } from '@nestjs/common'; +import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { ErrorLoggable } from '@src/core/error/loggable'; import { Logger } from '@src/core/logger'; -import { currentUserFactory, JwtTestFactory } from '@shared/testing'; -import { ConfigService } from '@nestjs/config'; -import { SystemService } from '@modules/system'; -import { systemFactory } from '@modules/system/testing'; -import { OauthSessionTokenService } from '@modules/oauth'; -import { oauthSessionTokenFactory } from '@modules/oauth/testing'; -import { AuthenticationService, LogoutService } from '../services'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; +import { JwtTestFactory } from '@testing/factory/jwt.test.factory'; import { ExternalSystemLogoutIsDisabledLoggableException } from '../errors'; +import { AuthenticationService, LogoutService } from '../services'; import { LogoutUc } from './logout.uc'; describe(LogoutUc.name, () => { diff --git a/apps/server/src/modules/authorization-reference/api/test/authorization.api.spec.ts b/apps/server/src/modules/authorization-reference/api/test/authorization.api.spec.ts index 7fd4f059902..4f27da385cf 100644 --- a/apps/server/src/modules/authorization-reference/api/test/authorization.api.spec.ts +++ b/apps/server/src/modules/authorization-reference/api/test/authorization.api.spec.ts @@ -1,17 +1,18 @@ import { EntityManager } from '@mikro-orm/core'; -import { ServerTestModule } from '@modules/server'; -import { HttpStatus, INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; -import { Permission } from '@shared/domain/interface'; import { Action, + AuthorizableReferenceType, AuthorizationContext, AuthorizationContextBuilder, - AuthorizableReferenceType, } from '@modules/authorization'; -import { AuthorizationReponseMapper } from '../mapper'; +import { ServerTestModule } from '@modules/server'; +import { HttpStatus, INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { Permission } from '@shared/domain/interface'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { AuthorizationBodyParams } from '../dto'; +import { AuthorizationReponseMapper } from '../mapper'; const createExamplePostData = (userId: string): AuthorizationBodyParams => { const referenceType = AuthorizableReferenceType.User; diff --git a/apps/server/src/modules/authorization-reference/domain/authorization-reference.service.spec.ts b/apps/server/src/modules/authorization-reference/domain/authorization-reference.service.spec.ts index b0ba329b99a..d31e0845958 100644 --- a/apps/server/src/modules/authorization-reference/domain/authorization-reference.service.spec.ts +++ b/apps/server/src/modules/authorization-reference/domain/authorization-reference.service.spec.ts @@ -1,7 +1,4 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { NotFoundException } from '@nestjs/common'; -import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, setupEntities, userFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; import { AuthorizableReferenceType, @@ -9,8 +6,13 @@ import { AuthorizationService, ForbiddenLoggableException, } from '@modules/authorization'; -import { ReferenceLoader } from './reference.loader'; +import { NotFoundException } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { AuthorizationReferenceService } from './authorization-reference.service'; +import { ReferenceLoader } from './reference.loader'; describe('AuthorizationReferenceService', () => { let service: AuthorizationReferenceService; diff --git a/apps/server/src/modules/authorization-reference/domain/reference.loader.spec.ts b/apps/server/src/modules/authorization-reference/domain/reference.loader.spec.ts index eac81888b35..02c3ff19ca5 100644 --- a/apps/server/src/modules/authorization-reference/domain/reference.loader.spec.ts +++ b/apps/server/src/modules/authorization-reference/domain/reference.loader.spec.ts @@ -6,7 +6,8 @@ import { NotImplementedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { EntityId } from '@shared/domain/types'; import { CourseGroupRepo, CourseRepo, LegacySchoolRepo, SubmissionRepo, TaskRepo, UserRepo } from '@shared/repo'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ReferenceLoader } from './reference.loader'; describe('reference.loader', () => { diff --git a/apps/server/src/modules/authorization-rules/rules/course-group.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/course-group.rule.spec.ts index 1c197d3b6e2..710bd4a26cc 100644 --- a/apps/server/src/modules/authorization-rules/rules/course-group.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/course-group.rule.spec.ts @@ -2,7 +2,11 @@ import { Action, AuthorizationHelper, AuthorizationInjectionService } from '@mod import { Test, TestingModule } from '@nestjs/testing'; import { CourseGroup, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { courseFactory, courseGroupFactory, roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseGroupRule } from './course-group.rule'; import { CourseRule } from './course.rule'; diff --git a/apps/server/src/modules/authorization-rules/rules/course.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/course.rule.spec.ts index 97a29a0841c..922831c0cd2 100644 --- a/apps/server/src/modules/authorization-rules/rules/course.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/course.rule.spec.ts @@ -3,7 +3,10 @@ import { courseFactory } from '@modules/learnroom/testing'; import { Test, TestingModule } from '@nestjs/testing'; import { Course, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { courseFactory as courseEntityFactory, roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory as courseEntityFactory } from '@testing/factory/course.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseRule } from './course.rule'; describe('CourseRule', () => { diff --git a/apps/server/src/modules/authorization-rules/rules/group.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/group.rule.spec.ts index 37af3eccf6a..192a5eb32c3 100644 --- a/apps/server/src/modules/authorization-rules/rules/group.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/group.rule.spec.ts @@ -10,7 +10,11 @@ import { Group } from '@modules/group'; import { Test, TestingModule } from '@nestjs/testing'; import { Role, SchoolEntity, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { groupFactory, roleFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { GroupRule } from './group.rule'; describe('GroupRule', () => { diff --git a/apps/server/src/modules/authorization-rules/rules/instance.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/instance.rule.spec.ts index de5e1147041..76488ce5020 100644 --- a/apps/server/src/modules/authorization-rules/rules/instance.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/instance.rule.spec.ts @@ -8,7 +8,8 @@ import { import { instanceFactory } from '@modules/instance/testing'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { InstanceRule } from './instance.rule'; describe(InstanceRule.name, () => { diff --git a/apps/server/src/modules/authorization-rules/rules/legacy-school.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/legacy-school.rule.spec.ts index 4760a35955d..62b7c9a8518 100644 --- a/apps/server/src/modules/authorization-rules/rules/legacy-school.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/legacy-school.rule.spec.ts @@ -2,7 +2,10 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { Action, AuthorizationHelper, AuthorizationInjectionService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { legacySchoolDoFactory, roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LegacySchoolRule } from './legacy-school.rule'; describe('LegacySchoolRule', () => { diff --git a/apps/server/src/modules/authorization-rules/rules/lesson.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/lesson.rule.spec.ts index 338c4490e47..362bf5d1aa5 100644 --- a/apps/server/src/modules/authorization-rules/rules/lesson.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/lesson.rule.spec.ts @@ -10,14 +10,12 @@ import { NotImplementedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { LessonEntity, User } from '@shared/domain/entity'; import { Permission, RoleName } from '@shared/domain/interface'; -import { - courseFactory, - courseGroupFactory, - lessonFactory, - roleFactory, - setupEntities, - userFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseGroupRule } from './course-group.rule'; import { CourseRule } from './course.rule'; import { LessonRule } from './lesson.rule'; diff --git a/apps/server/src/modules/authorization-rules/rules/school-system-options.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/school-system-options.rule.spec.ts index 49964341624..45de029e1f5 100644 --- a/apps/server/src/modules/authorization-rules/rules/school-system-options.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/school-system-options.rule.spec.ts @@ -10,13 +10,11 @@ import { SystemEntity } from '@modules/system/entity'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { - schoolEntityFactory, - schoolSystemOptionsFactory, - setupEntities, - systemEntityFactory, - userFactory, -} from '@shared/testing'; +import { schoolSystemOptionsFactory } from '@testing/factory/domainobject'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SchoolSystemOptionsRule } from './school-system-options.rule'; describe(SchoolSystemOptionsRule.name, () => { diff --git a/apps/server/src/modules/authorization-rules/rules/school.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/school.rule.spec.ts index f3df85dc95b..b5a2fedb671 100644 --- a/apps/server/src/modules/authorization-rules/rules/school.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/school.rule.spec.ts @@ -7,7 +7,9 @@ import { import { schoolFactory } from '@modules/school/testing/school.factory'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface/permission.enum'; -import { schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SchoolRule } from './school.rule'; describe('SchoolRule', () => { diff --git a/apps/server/src/modules/authorization-rules/rules/submission.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/submission.rule.spec.ts index 2e38fee4b5e..2a150c59629 100644 --- a/apps/server/src/modules/authorization-rules/rules/submission.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/submission.rule.spec.ts @@ -7,15 +7,13 @@ import { import { NotImplementedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { - courseFactory, - courseGroupFactory, - roleFactory, - setupEntities, - submissionFactory, - taskFactory, - userFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseGroupRule } from './course-group.rule'; import { CourseRule } from './course.rule'; import { LessonRule } from './lesson.rule'; diff --git a/apps/server/src/modules/authorization-rules/rules/system.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/system.rule.spec.ts index 6b9d2b72935..11f2228fd28 100644 --- a/apps/server/src/modules/authorization-rules/rules/system.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/system.rule.spec.ts @@ -10,7 +10,10 @@ import { systemFactory } from '@modules/system/testing'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { schoolEntityFactory, setupEntities, systemEntityFactory, userFactory } from '@shared/testing'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SystemRule } from './system.rule'; describe(SystemRule.name, () => { diff --git a/apps/server/src/modules/authorization-rules/rules/task.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/task.rule.spec.ts index 37bf29fb2a3..662e5c40299 100644 --- a/apps/server/src/modules/authorization-rules/rules/task.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/task.rule.spec.ts @@ -2,7 +2,12 @@ import { DeepPartial } from '@mikro-orm/core'; import { Action, AuthorizationHelper, AuthorizationInjectionService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { courseFactory, lessonFactory, roleFactory, setupEntities, taskFactory, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseGroupRule } from './course-group.rule'; import { CourseRule } from './course.rule'; import { LessonRule } from './lesson.rule'; diff --git a/apps/server/src/modules/authorization-rules/rules/team.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/team.rule.spec.ts index 4a7026c2789..2bfaa07278a 100644 --- a/apps/server/src/modules/authorization-rules/rules/team.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/team.rule.spec.ts @@ -5,7 +5,10 @@ import { } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { roleFactory, setupEntities, teamFactory, userFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { teamFactory } from '@testing/factory/team.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { TeamRule } from './team.rule'; describe('TeamRule', () => { diff --git a/apps/server/src/modules/authorization-rules/rules/user-login-migration.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/user-login-migration.rule.spec.ts index 4640e1ee176..e3a8527e61d 100644 --- a/apps/server/src/modules/authorization-rules/rules/user-login-migration.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/user-login-migration.rule.spec.ts @@ -9,7 +9,10 @@ import { import { Test, TestingModule } from '@nestjs/testing'; import { UserLoginMigrationDO } from '@shared/domain/domainobject'; import { Permission } from '@shared/domain/interface'; -import { schoolEntityFactory, setupEntities, userFactory, userLoginMigrationDOFactory } from '@shared/testing'; +import { userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserLoginMigrationRule } from './user-login-migration.rule'; describe('UserLoginMigrationRule', () => { diff --git a/apps/server/src/modules/authorization-rules/rules/user.rule.spec.ts b/apps/server/src/modules/authorization-rules/rules/user.rule.spec.ts index 62722af6ac9..c43c70e5fb3 100644 --- a/apps/server/src/modules/authorization-rules/rules/user.rule.spec.ts +++ b/apps/server/src/modules/authorization-rules/rules/user.rule.spec.ts @@ -2,7 +2,9 @@ import { Action, AuthorizationHelper, AuthorizationInjectionService } from '@mod import { Test, TestingModule } from '@nestjs/testing'; import { Role, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserRule } from './user.rule'; describe('UserRule', () => { diff --git a/apps/server/src/modules/authorization/domain/service/authorization.helper.spec.ts b/apps/server/src/modules/authorization/domain/service/authorization.helper.spec.ts index 4dba8bc5357..e604f25d4de 100644 --- a/apps/server/src/modules/authorization/domain/service/authorization.helper.spec.ts +++ b/apps/server/src/modules/authorization/domain/service/authorization.helper.spec.ts @@ -1,12 +1,10 @@ import { courseFactory } from '@modules/learnroom/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { - courseFactory as courseEntityFactory, - roleFactory, - setupEntities, - taskFactory, - userFactory, -} from '@shared/testing'; +import { courseFactory as courseEntityFactory } from '@testing/factory/course.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { AuthorizationHelper } from './authorization.helper'; describe('AuthorizationHelper', () => { diff --git a/apps/server/src/modules/authorization/domain/service/authorization.service.spec.ts b/apps/server/src/modules/authorization/domain/service/authorization.service.spec.ts index d5d4cf3ed72..7120f2b2d90 100644 --- a/apps/server/src/modules/authorization/domain/service/authorization.service.spec.ts +++ b/apps/server/src/modules/authorization/domain/service/authorization.service.spec.ts @@ -3,7 +3,8 @@ import { UnauthorizedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; import { UserRepo } from '@shared/repo'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ForbiddenLoggableException } from '../error'; import { AuthorizationContextBuilder } from '../mapper'; import { Rule } from '../type'; diff --git a/apps/server/src/modules/authorization/domain/service/rule-manager.spec.ts b/apps/server/src/modules/authorization/domain/service/rule-manager.spec.ts index 3213261f612..4b27377834c 100644 --- a/apps/server/src/modules/authorization/domain/service/rule-manager.spec.ts +++ b/apps/server/src/modules/authorization/domain/service/rule-manager.spec.ts @@ -1,7 +1,9 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { InternalServerErrorException, NotImplementedException } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { courseFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { RuleManager } from '.'; import { AuthorizationContextBuilder } from '../mapper'; import { AuthorizationInjectionService } from './authorization-injection.service'; diff --git a/apps/server/src/modules/board-context/board-context-api-helper.service.spec.ts b/apps/server/src/modules/board-context/board-context-api-helper.service.spec.ts index 3332bf269c0..1be6fab5b13 100644 --- a/apps/server/src/modules/board-context/board-context-api-helper.service.spec.ts +++ b/apps/server/src/modules/board-context/board-context-api-helper.service.spec.ts @@ -3,7 +3,9 @@ import { AnyBoardNode, BoardExternalReferenceType, BoardNodeService } from '@mod import { CourseService } from '@modules/learnroom'; import { RoomService } from '@modules/room'; import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, schoolEntityFactory, setupEntities } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { setupEntities } from '@testing/setup-entities'; import { cardFactory, columnBoardFactory, columnFactory } from '../board/testing'; import { roomFactory } from '../room/testing'; import { BoardContextApiHelperService } from './board-context-api-helper.service'; diff --git a/apps/server/src/modules/board/authorisation/board-node.rule.spec.ts b/apps/server/src/modules/board/authorisation/board-node.rule.spec.ts index 2c580152b53..0c84053298f 100644 --- a/apps/server/src/modules/board/authorisation/board-node.rule.spec.ts +++ b/apps/server/src/modules/board/authorisation/board-node.rule.spec.ts @@ -1,11 +1,13 @@ import { ObjectId } from '@mikro-orm/mongodb'; +import { Action, AuthorizationHelper, AuthorizationInjectionService } from '@modules/authorization'; import { BoardNodeAuthorizable, BoardRoles } from '@modules/board'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { roleFactory, setupEntities, userFactory } from '@shared/testing'; -import { AuthorizationHelper, AuthorizationInjectionService, Action } from '@modules/authorization'; -import { BoardNodeRule } from './board-node.rule'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { columnBoardFactory, drawingElementFactory, fileElementFactory, submissionItemFactory } from '../testing'; +import { BoardNodeRule } from './board-node.rule'; describe(BoardNodeRule.name, () => { let service: BoardNodeRule; diff --git a/apps/server/src/modules/board/board-collaboration.app.module.ts b/apps/server/src/modules/board/board-collaboration.app.module.ts index 10995308119..1c02b6e25df 100644 --- a/apps/server/src/modules/board/board-collaboration.app.module.ts +++ b/apps/server/src/modules/board/board-collaboration.app.module.ts @@ -8,7 +8,6 @@ import { defaultMikroOrmOptions } from '@shared/common/defaultMikroOrmOptions'; import { ALL_ENTITIES } from '@shared/domain/entity/all-entities'; import { createConfigModuleOptions, DB_PASSWORD, DB_URL, DB_USERNAME } from '@src/config'; import { CoreModule } from '@src/core'; -import { AuthenticationApiModule } from '../authentication/authentication-api.module'; import { AuthorizationModule } from '../authorization'; import { serverConfig } from '../server'; import { config } from './board-collaboration.config'; @@ -50,7 +49,6 @@ const testConfig = () => { imports: [ ...imports, ConfigModule.forRoot(createConfigModuleOptions(testConfig)), - AuthenticationApiModule, MongoMemoryDatabaseModule.forRoot({ ...defaultMikroOrmOptions, entities: ALL_ENTITIES, diff --git a/apps/server/src/modules/board/controller/api-test/board-context-in-course.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-context-in-course.api.spec.ts index 1fc0caf98bc..1ea820e4d11 100644 --- a/apps/server/src/modules/board/controller/api-test/board-context-in-course.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-context-in-course.api.spec.ts @@ -2,9 +2,12 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; -import { columnBoardEntityFactory } from '../../testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; +import { columnBoardEntityFactory } from '../../testing'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-context-in-rooms.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-context-in-rooms.api.spec.ts index 15b42ea15a8..b189f8052c5 100644 --- a/apps/server/src/modules/board/controller/api-test/board-context-in-rooms.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-context-in-rooms.api.spec.ts @@ -1,15 +1,19 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { accountFactory } from '@modules/account/testing'; +import { GroupEntityTypes } from '@modules/group/entity'; +import { roomMembershipEntityFactory } from '@modules/room-membership/testing'; +import { roomEntityFactory } from '@modules/room/testing'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, cleanupCollections, groupEntityFactory, roleFactory, userFactory } from '@shared/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { accountFactory } from '@src/modules/account/testing'; -import { GroupEntityTypes } from '@src/modules/group/entity'; -import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; -import { roomEntityFactory } from '@src/modules/room/testing'; -import { columnBoardEntityFactory } from '../../testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; +import { columnBoardEntityFactory } from '../../testing'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-copy-in-course.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-copy-in-course.api.spec.ts index 854cf4e36e9..d9007276c08 100644 --- a/apps/server/src/modules/board/controller/api-test/board-copy-in-course.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-copy-in-course.api.spec.ts @@ -1,12 +1,15 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { CopyApiResponse, CopyElementType, CopyStatusEnum } from '@modules/copy-helper'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; -import { CopyApiResponse, CopyElementType, CopyStatusEnum } from '@modules/copy-helper'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType, ColumnBoardProps } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { columnBoardEntityFactory } from '../../testing'; -import { BoardExternalReferenceType, ColumnBoardProps } from '../../domain'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-copy-in-room.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-copy-in-room.api.spec.ts index 5e02e65be08..158e00ac9e6 100644 --- a/apps/server/src/modules/board/controller/api-test/board-copy-in-room.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-copy-in-room.api.spec.ts @@ -1,19 +1,17 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { GroupEntityTypes } from '@modules/group/entity'; +import { roomMembershipEntityFactory } from '@modules/room-membership/testing'; +import { roomEntityFactory } from '@modules/room/testing'; +import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; -import { GroupEntityTypes } from '@src/modules/group/entity'; -import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; -import { roomEntityFactory } from '@src/modules/room/testing'; -import { ServerTestModule } from '@src/modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, ColumnBoardProps } from '../../domain'; import { columnBoardEntityFactory } from '../../testing'; diff --git a/apps/server/src/modules/board/controller/api-test/board-create-in-course.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-create-in-course.api.spec.ts index 1ca293aad55..1dbe83a9223 100644 --- a/apps/server/src/modules/board/controller/api-test/board-create-in-course.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-create-in-course.api.spec.ts @@ -2,9 +2,12 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; -import { BoardNodeEntity } from '../../repo'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, BoardLayout } from '../../domain'; +import { BoardNodeEntity } from '../../repo'; import { CreateBoardBodyParams } from '../dto'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-create-in-room.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-create-in-room.api.spec.ts index bb439583707..66cd5ece6b4 100644 --- a/apps/server/src/modules/board/controller/api-test/board-create-in-room.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-create-in-room.api.spec.ts @@ -1,21 +1,19 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { accountFactory } from '@modules/account/testing'; +import { GroupEntityTypes } from '@modules/group/entity'; +import { roomMembershipEntityFactory } from '@modules/room-membership/testing'; +import { roomEntityFactory } from '@modules/room/testing'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; import { RoleName } from '@shared/domain/interface/rolename.enum'; -import { - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, - TestApiClient, - userFactory, -} from '@shared/testing'; -import { accountFactory } from '@src/modules/account/testing'; -import { GroupEntityTypes } from '@src/modules/group/entity'; -import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; -import { roomEntityFactory } from '@src/modules/room/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, BoardLayout } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { CreateBoardBodyParams } from '../dto'; diff --git a/apps/server/src/modules/board/controller/api-test/board-delete-in-course.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-delete-in-course.api.spec.ts index 7bcc32a50bf..8cf900cf774 100644 --- a/apps/server/src/modules/board/controller/api-test/board-delete-in-course.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-delete-in-course.api.spec.ts @@ -2,7 +2,10 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { columnBoardEntityFactory, columnEntityFactory } from '../../testing'; diff --git a/apps/server/src/modules/board/controller/api-test/board-delete-in-room.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-delete-in-room.api.spec.ts index c46ae270dfd..1c76b01df8c 100644 --- a/apps/server/src/modules/board/controller/api-test/board-delete-in-room.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-delete-in-room.api.spec.ts @@ -1,16 +1,20 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { accountFactory } from '@modules/account/testing'; +import { GroupEntityTypes } from '@modules/group/entity'; +import { roomMembershipEntityFactory } from '@modules/room-membership/testing'; +import { roomEntityFactory } from '@modules/room/testing'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, groupEntityFactory, roleFactory, TestApiClient, userFactory } from '@shared/testing'; -import { accountFactory } from '@src/modules/account/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { GroupEntityTypes } from '@src/modules/group/entity'; -import { roomEntityFactory } from '@src/modules/room/testing'; -import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; -import { columnBoardEntityFactory, columnEntityFactory } from '../../testing'; -import { BoardNodeEntity } from '../../repo'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; +import { BoardNodeEntity } from '../../repo'; +import { columnBoardEntityFactory, columnEntityFactory } from '../../testing'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-lookup-in-course.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-lookup-in-course.api.spec.ts index b6e0419ace9..f094f9f8615 100644 --- a/apps/server/src/modules/board/controller/api-test/board-lookup-in-course.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-lookup-in-course.api.spec.ts @@ -2,10 +2,12 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, BoardLayout } from '../../domain'; - -import { cardEntityFactory, columnEntityFactory, columnBoardEntityFactory } from '../../testing'; +import { cardEntityFactory, columnBoardEntityFactory, columnEntityFactory } from '../../testing'; import { BoardResponse } from '../dto'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-lookup-in-room.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-lookup-in-room.api.spec.ts index 0f1dea74740..71135c8cb15 100644 --- a/apps/server/src/modules/board/controller/api-test/board-lookup-in-room.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-lookup-in-room.api.spec.ts @@ -2,16 +2,20 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, groupEntityFactory, roleFactory, TestApiClient, userFactory } from '@shared/testing'; +import { accountFactory } from '@modules/account/testing'; +import { GroupEntityTypes } from '@modules/group/entity'; +import { roomMembershipEntityFactory } from '@modules/room-membership/testing'; +import { roomEntityFactory } from '@modules/room/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { accountFactory } from '@src/modules/account/testing'; -import { GroupEntityTypes } from '@src/modules/group/entity'; -import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; -import { roomEntityFactory } from '@src/modules/room/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, BoardLayout } from '../../domain'; +import { cardEntityFactory, columnBoardEntityFactory, columnEntityFactory } from '../../testing'; import { BoardResponse } from '../dto'; -import { cardEntityFactory, columnEntityFactory, columnBoardEntityFactory } from '../../testing'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-update-title-in-course.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-update-title-in-course.api.spec.ts index 57b5489e707..128ba768732 100644 --- a/apps/server/src/modules/board/controller/api-test/board-update-title-in-course.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-update-title-in-course.api.spec.ts @@ -3,10 +3,13 @@ import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { columnBoardEntityFactory } from '../../testing'; -import { BoardExternalReferenceType } from '../../domain'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-update-title-in-room.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-update-title-in-room.api.spec.ts index 168f2ac77f6..dbbe1a1bf61 100644 --- a/apps/server/src/modules/board/controller/api-test/board-update-title-in-room.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-update-title-in-room.api.spec.ts @@ -3,15 +3,19 @@ import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; -import { TestApiClient, cleanupCollections, groupEntityFactory, roleFactory, userFactory } from '@shared/testing'; import { Permission, RoleName } from '@shared/domain/interface'; import { accountFactory } from '@src/modules/account/testing'; import { GroupEntityTypes } from '@src/modules/group/entity'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; import { roomEntityFactory } from '@src/modules/room/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { columnBoardEntityFactory } from '../../testing'; -import { BoardExternalReferenceType } from '../../domain'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-visibility-in-course.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-visibility-in-course.api.spec.ts index 36126152bb7..8f2a510e207 100644 --- a/apps/server/src/modules/board/controller/api-test/board-visibility-in-course.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-visibility-in-course.api.spec.ts @@ -2,10 +2,13 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { columnBoardEntityFactory } from '../../testing'; -import { BoardExternalReferenceType } from '../../domain'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/board-visibility-in-room.api.spec.ts b/apps/server/src/modules/board/controller/api-test/board-visibility-in-room.api.spec.ts index 8bd6a4b9eab..86ab2de22ba 100644 --- a/apps/server/src/modules/board/controller/api-test/board-visibility-in-room.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/board-visibility-in-room.api.spec.ts @@ -2,15 +2,19 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, cleanupCollections, groupEntityFactory, roleFactory, userFactory } from '@shared/testing'; import { Permission, RoleName } from '@shared/domain/interface'; import { accountFactory } from '@src/modules/account/testing'; import { GroupEntityTypes } from '@src/modules/group/entity'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; import { roomEntityFactory } from '@src/modules/room/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; -import { columnBoardEntityFactory } from '../../testing'; import { BoardNodeEntity } from '../../repo'; +import { columnBoardEntityFactory } from '../../testing'; const baseRouteName = '/boards'; diff --git a/apps/server/src/modules/board/controller/api-test/card-create.api.spec.ts b/apps/server/src/modules/board/controller/api-test/card-create.api.spec.ts index c347396e8e5..fc936bb3e50 100644 --- a/apps/server/src/modules/board/controller/api-test/card-create.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/card-create.api.spec.ts @@ -1,63 +1,31 @@ -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { ApiValidationError } from '@shared/common'; -import { cleanupCollections, courseFactory, mapUserToCurrentUser, userFactory } from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, ContentElementType } from '../../domain'; import { columnBoardEntityFactory, columnEntityFactory } from '../../testing'; import { CardResponse } from '../dto'; const baseRouteName = '/columns'; -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async post(columnId: string, requestBody?: object) { - const response = await request(this.app.getHttpServer()) - .post(`${baseRouteName}/${columnId}/cards`) - .set('Accept', 'application/json') - .send(requestBody); - - return { - result: response.body as CardResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} - describe(`card create (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; + let apiClient: TestApiClient; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); - api = new API(app); + apiClient = new TestApiClient(app, baseRouteName); }); afterAll(async () => { @@ -66,9 +34,9 @@ describe(`card create (api)`, () => { const setup = async () => { await cleanupCollections(em); - const user = userFactory.build(); + const { teacherAccount: account, teacherUser: user } = UserAndAccountTestFactory.buildTeacher(); const course = courseFactory.build({ teachers: [user] }); - await em.persistAndFlush([user, course]); + await em.persistAndFlush([user, account, course]); const columnBoardNode = columnBoardEntityFactory.build({ context: { id: course.id, type: BoardExternalReferenceType.Course }, @@ -83,30 +51,30 @@ describe(`card create (api)`, () => { requiredEmptyElements: [ContentElementType.RICH_TEXT, ContentElementType.FILE, ContentElementType.LINK], }; - return { user, columnBoardNode, columnNode, createCardBodyParams }; + const loggedInClient = await apiClient.login(account); + + return { user, columnBoardNode, columnNode, createCardBodyParams, loggedInClient }; }; describe('with valid user', () => { it('should return status 201', async () => { - const { user, columnNode } = await setup(); - currentUser = mapUserToCurrentUser(user); + const { columnNode, loggedInClient } = await setup(); - const response = await api.post(columnNode.id); + const response = await loggedInClient.post(`${columnNode.id}/cards`); expect(response.status).toEqual(201); }); it('should return the created card', async () => { - const { user, columnNode } = await setup(); - currentUser = mapUserToCurrentUser(user); + const { columnNode, loggedInClient } = await setup(); - const { result } = await api.post(columnNode.id); + const response = await loggedInClient.post(`${columnNode.id}/cards`); + const result = response.body as CardResponse; expect(result.id).toBeDefined(); }); it('created card should contain empty text, file and link elements', async () => { - const { user, columnNode, createCardBodyParams } = await setup(); - currentUser = mapUserToCurrentUser(user); + const { columnNode, createCardBodyParams, loggedInClient } = await setup(); const expectedEmptyElements = [ { @@ -130,7 +98,8 @@ describe(`card create (api)`, () => { }, ]; - const { result } = await api.post(columnNode.id, createCardBodyParams); + const response = await loggedInClient.post(`${columnNode.id}/cards`, createCardBodyParams); + const result = response.body as CardResponse; const { elements } = result; expect(elements[0]).toMatchObject(expectedEmptyElements[0]); @@ -138,14 +107,14 @@ describe(`card create (api)`, () => { expect(elements[2]).toMatchObject(expectedEmptyElements[2]); }); it('should return status 400 as the content element is unknown', async () => { - const { user, columnNode } = await setup(); - currentUser = mapUserToCurrentUser(user); + const { columnNode, loggedInClient } = await setup(); const invalidBodyParams = { requiredEmptyElements: ['unknown-content-element'], }; - const response = await api.post(columnNode.id, invalidBodyParams); + const response = await loggedInClient.post(`${columnNode.id}/cards`, invalidBodyParams); + expect(response.status).toEqual(400); }); }); @@ -153,13 +122,27 @@ describe(`card create (api)`, () => { describe('with invalid user', () => { it('should return status 403', async () => { const { columnNode } = await setup(); - const invalidUser = userFactory.build(); - await em.persistAndFlush([invalidUser]); - currentUser = mapUserToCurrentUser(invalidUser); + const { teacherAccount: account, teacherUser: user } = UserAndAccountTestFactory.buildTeacher(); + await em.persistAndFlush([user, account]); - const response = await api.post(columnNode.id); + const api = new TestApiClient(app, baseRouteName); + const loggedInClient = await api.login(account); + + const response = await loggedInClient.post(`${columnNode.id}/cards`); expect(response.status).toEqual(403); }); }); + + describe('with not logged in user', () => { + it('should return status 403', async () => { + const { columnNode } = await setup(); + const { teacherAccount: account, teacherUser: user } = UserAndAccountTestFactory.buildTeacher(); + await em.persistAndFlush([user, account]); + + const response = await apiClient.post(`${columnNode.id}/cards`); + + expect(response.status).toEqual(401); + }); + }); }); diff --git a/apps/server/src/modules/board/controller/api-test/card-delete.api.spec.ts b/apps/server/src/modules/board/controller/api-test/card-delete.api.spec.ts index 636d41153c3..358b17f737d 100644 --- a/apps/server/src/modules/board/controller/api-test/card-delete.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/card-delete.api.spec.ts @@ -2,7 +2,10 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { diff --git a/apps/server/src/modules/board/controller/api-test/card-lookup.api.spec.ts b/apps/server/src/modules/board/controller/api-test/card-lookup.api.spec.ts index 8ff95ec8562..ec8319040f5 100644 --- a/apps/server/src/modules/board/controller/api-test/card-lookup.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/card-lookup.api.spec.ts @@ -2,7 +2,10 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; import { cardEntityFactory, diff --git a/apps/server/src/modules/board/controller/api-test/card-move.api.spec.ts b/apps/server/src/modules/board/controller/api-test/card-move.api.spec.ts index 6157c340669..b162b12b215 100644 --- a/apps/server/src/modules/board/controller/api-test/card-move.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/card-move.api.spec.ts @@ -2,7 +2,10 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, pathOfChildren } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { cardEntityFactory, columnBoardEntityFactory, columnEntityFactory } from '../../testing'; diff --git a/apps/server/src/modules/board/controller/api-test/card-update-height.api.spec.ts b/apps/server/src/modules/board/controller/api-test/card-update-height.api.spec.ts index a433c736383..d2a6968e540 100644 --- a/apps/server/src/modules/board/controller/api-test/card-update-height.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/card-update-height.api.spec.ts @@ -2,10 +2,13 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { cardEntityFactory, columnBoardEntityFactory, columnEntityFactory } from '../../testing'; -import { BoardExternalReferenceType } from '../../domain'; describe(`card update height (api)`, () => { let app: INestApplication; diff --git a/apps/server/src/modules/board/controller/api-test/card-update-title.api.spec.ts b/apps/server/src/modules/board/controller/api-test/card-update-title.api.spec.ts index 054d5b61aa1..0a0fab79fac 100644 --- a/apps/server/src/modules/board/controller/api-test/card-update-title.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/card-update-title.api.spec.ts @@ -2,7 +2,10 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { cardEntityFactory, columnBoardEntityFactory, columnEntityFactory } from '../../testing'; diff --git a/apps/server/src/modules/board/controller/api-test/column-create.api.spec.ts b/apps/server/src/modules/board/controller/api-test/column-create.api.spec.ts index fea177dfb79..0603498fdd2 100644 --- a/apps/server/src/modules/board/controller/api-test/column-create.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/column-create.api.spec.ts @@ -1,115 +1,125 @@ -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { ApiValidationError } from '@shared/common'; -import { cleanupCollections, courseFactory, mapUserToCurrentUser, userFactory } from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; import { columnBoardEntityFactory } from '../../testing'; import { ColumnResponse } from '../dto'; const baseRouteName = '/boards'; -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async post(boardId: string) { - const response = await request(this.app.getHttpServer()) - .post(`${baseRouteName}/${boardId}/columns`) - .set('Accept', 'application/json'); - - return { - result: response.body as ColumnResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} - describe(`board create (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; + let apiClient: TestApiClient; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); - api = new API(app); + apiClient = new TestApiClient(app, baseRouteName); }); afterAll(async () => { await app.close(); }); - const setup = async () => { - await cleanupCollections(em); - const user = userFactory.build(); - const course = courseFactory.build({ teachers: [user] }); - await em.persistAndFlush([user, course]); + describe('with valid user', () => { + const setup = async () => { + await cleanupCollections(em); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + await em.persistAndFlush([teacherUser, teacherAccount, course]); - const columnBoardNode = columnBoardEntityFactory.build({ - context: { id: course.id, type: BoardExternalReferenceType.Course }, - }); + const columnBoardNode = columnBoardEntityFactory.build({ + context: { id: course.id, type: BoardExternalReferenceType.Course }, + }); - await em.persistAndFlush([user, columnBoardNode]); - em.clear(); + await em.persistAndFlush([columnBoardNode]); + em.clear(); - return { user, columnBoardNode }; - }; + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, columnBoardNode }; + }; - describe('with valid user', () => { it('should return status 201', async () => { - const { user, columnBoardNode } = await setup(); - currentUser = mapUserToCurrentUser(user); + const { columnBoardNode, loggedInClient } = await setup(); - const response = await api.post(columnBoardNode.id); + const response = await loggedInClient.post(`${columnBoardNode.id}/columns`); expect(response.status).toEqual(201); }); it('should return the created column', async () => { - const { user, columnBoardNode } = await setup(); - currentUser = mapUserToCurrentUser(user); + const { columnBoardNode, loggedInClient } = await setup(); - const { result } = await api.post(columnBoardNode.id); + const result = await loggedInClient.post(`${columnBoardNode.id}/columns`); + const response = result.body as ColumnResponse; - expect(result.id).toBeDefined(); + expect(response.id).toBeDefined(); }); }); - describe('with valid user', () => { - it('should return status 403', async () => { - const { columnBoardNode } = await setup(); + describe('with unauthorized user', () => { + const setup = async () => { + await cleanupCollections(em); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [] }); + await em.persistAndFlush([teacherUser, teacherAccount, course]); + + const columnBoardNode = columnBoardEntityFactory.build({ + context: { id: course.id, type: BoardExternalReferenceType.Course }, + }); - const invalidUser = userFactory.build(); - await em.persistAndFlush([invalidUser]); - currentUser = mapUserToCurrentUser(invalidUser); + await em.persistAndFlush([columnBoardNode]); + em.clear(); - const response = await api.post(columnBoardNode.id); + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, columnBoardNode }; + }; + + it('should return status 403', async () => { + const { columnBoardNode, loggedInClient } = await setup(); + + const response = await loggedInClient.post(`${columnBoardNode.id}/columns`); expect(response.status).toEqual(403); }); }); + + describe('with not logged in user', () => { + const setup = async () => { + await cleanupCollections(em); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [] }); + await em.persistAndFlush([teacherUser, teacherAccount, course]); + + const columnBoardNode = columnBoardEntityFactory.build({ + context: { id: course.id, type: BoardExternalReferenceType.Course }, + }); + + await em.persistAndFlush([columnBoardNode]); + em.clear(); + + return { columnBoardNode }; + }; + + it('should return status 403', async () => { + const { columnBoardNode } = await setup(); + + const response = await apiClient.post(`${columnBoardNode.id}/columns`); + + expect(response.status).toEqual(401); + }); + }); }); diff --git a/apps/server/src/modules/board/controller/api-test/column-delete.api.spec.ts b/apps/server/src/modules/board/controller/api-test/column-delete.api.spec.ts index dfad720936a..dd37f200d42 100644 --- a/apps/server/src/modules/board/controller/api-test/column-delete.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/column-delete.api.spec.ts @@ -2,7 +2,10 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { cardEntityFactory, columnBoardEntityFactory, columnEntityFactory } from '../../testing'; diff --git a/apps/server/src/modules/board/controller/api-test/column-move.api.spec.ts b/apps/server/src/modules/board/controller/api-test/column-move.api.spec.ts index dac3478a50c..ff9e4fddf12 100644 --- a/apps/server/src/modules/board/controller/api-test/column-move.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/column-move.api.spec.ts @@ -2,7 +2,10 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { cardEntityFactory, columnBoardEntityFactory, columnEntityFactory } from '../../testing'; diff --git a/apps/server/src/modules/board/controller/api-test/column-update-title.api.spec.ts b/apps/server/src/modules/board/controller/api-test/column-update-title.api.spec.ts index 806ba48bcd3..61e8beadb39 100644 --- a/apps/server/src/modules/board/controller/api-test/column-update-title.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/column-update-title.api.spec.ts @@ -2,10 +2,13 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { columnBoardEntityFactory, columnEntityFactory } from '../../testing/entity'; -import { BoardExternalReferenceType } from '../../domain'; const baseRouteName = '/columns'; diff --git a/apps/server/src/modules/board/controller/api-test/content-element-create.api.spec.ts b/apps/server/src/modules/board/controller/api-test/content-element-create.api.spec.ts index b7a2f655d25..02d6e32b969 100644 --- a/apps/server/src/modules/board/controller/api-test/content-element-create.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/content-element-create.api.spec.ts @@ -2,9 +2,12 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; -import { BoardNodeEntity } from '../../repo'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, ContentElementType } from '../../domain'; +import { BoardNodeEntity } from '../../repo'; import { cardEntityFactory, columnBoardEntityFactory, diff --git a/apps/server/src/modules/board/controller/api-test/content-element-delete.api.spec.ts b/apps/server/src/modules/board/controller/api-test/content-element-delete.api.spec.ts index 14a6484daa7..21b6ce58884 100644 --- a/apps/server/src/modules/board/controller/api-test/content-element-delete.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/content-element-delete.api.spec.ts @@ -1,15 +1,14 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { TldrawClientAdapter } from '@infra/tldraw-client'; import { EntityManager } from '@mikro-orm/mongodb'; import { FilesStorageClientAdapterService } from '@modules/files-storage-client'; import { ServerTestModule } from '@modules/server/server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { ApiValidationError } from '@shared/common'; -import { cleanupCollections, courseFactory, mapUserToCurrentUser, userFactory } from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { @@ -22,32 +21,12 @@ import { const baseRouteName = '/elements'; -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async delete(elementId: string) { - const response = await request(this.app.getHttpServer()) - .delete(`${baseRouteName}/${elementId}`) - .set('Accept', 'application/json'); - - return { - error: response.body as ApiValidationError, - status: response.status, - }; - } -} - describe(`content element delete (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; let filesStorageClientAdapterService: DeepMocked; let drawingElementAdapterService: DeepMocked; - let api: API; + let apiClient: TestApiClient; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -57,14 +36,6 @@ describe(`content element delete (api)`, () => { .useValue(createMock()) .overrideProvider(TldrawClientAdapter) .useValue(createMock()) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .compile(); app = module.createNestApplication(); @@ -72,127 +43,198 @@ describe(`content element delete (api)`, () => { em = module.get(EntityManager); filesStorageClientAdapterService = module.get(FilesStorageClientAdapterService); drawingElementAdapterService = module.get(TldrawClientAdapter); - api = new API(app); + apiClient = new TestApiClient(app, baseRouteName); }); afterAll(async () => { await app.close(); }); - const setup = async () => { - await cleanupCollections(em); - const user = userFactory.build(); - const course = courseFactory.build({ teachers: [user] }); - await em.persistAndFlush([user, course]); + describe('with authorized user', () => { + const setup = async () => { + await cleanupCollections(em); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + await em.persistAndFlush([teacherAccount, teacherUser, course]); - const columnBoardNode = columnBoardEntityFactory.build({ - context: { id: course.id, type: BoardExternalReferenceType.Course }, - }); - const columnNode = columnEntityFactory.withParent(columnBoardNode).build(); - const cardNode = cardEntityFactory.withParent(columnNode).build(); - const element = richTextElementEntityFactory.withParent(cardNode).build(); - const sibling = richTextElementEntityFactory.withParent(cardNode).build(); + const columnBoardNode = columnBoardEntityFactory.build({ + context: { id: course.id, type: BoardExternalReferenceType.Course }, + }); + const columnNode = columnEntityFactory.withParent(columnBoardNode).build(); + const cardNode = cardEntityFactory.withParent(columnNode).build(); + const element = richTextElementEntityFactory.withParent(cardNode).build(); + const sibling = richTextElementEntityFactory.withParent(cardNode).build(); + + await em.persistAndFlush([columnBoardNode, columnNode, cardNode, element, sibling]); + em.clear(); - await em.persistAndFlush([user, columnBoardNode, columnNode, cardNode, element, sibling]); - em.clear(); + const loggedInClient = await apiClient.login(teacherAccount); - return { user, columnBoardNode, columnNode, cardNode, element, sibling }; - }; + return { loggedInClient, columnBoardNode, columnNode, cardNode, element, sibling }; + }; - describe('with valid user', () => { it('should return status 204', async () => { - const { user, element } = await setup(); - currentUser = mapUserToCurrentUser(user); + const { element, loggedInClient } = await setup(); - const response = await api.delete(element.id); + const response = await loggedInClient.delete(element.id); expect(response.status).toEqual(204); }); it('should actually delete element', async () => { - const { user, element } = await setup(); - currentUser = mapUserToCurrentUser(user); + const { element, loggedInClient } = await setup(); - await api.delete(element.id); + await loggedInClient.delete(element.id); await expect(em.findOneOrFail(BoardNodeEntity, element.id)).rejects.toThrow(); }); it('should not delete siblings', async () => { - const { user, element, sibling } = await setup(); - currentUser = mapUserToCurrentUser(user); + const { element, sibling, loggedInClient } = await setup(); - await api.delete(element.id); + await loggedInClient.delete(element.id); const siblingFromDb = await em.findOneOrFail(BoardNodeEntity, sibling.id); expect(siblingFromDb).toBeDefined(); }); }); - describe('with invalid user', () => { - it('should return status 403', async () => { - const { element } = await setup(); + describe('with not authorized user', () => { + const setup = async () => { + await cleanupCollections(em); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [] }); + await em.persistAndFlush([teacherAccount, teacherUser, course]); + + const columnBoardNode = columnBoardEntityFactory.build({ + context: { id: course.id, type: BoardExternalReferenceType.Course }, + }); + const columnNode = columnEntityFactory.withParent(columnBoardNode).build(); + const cardNode = cardEntityFactory.withParent(columnNode).build(); + const element = richTextElementEntityFactory.withParent(cardNode).build(); + const sibling = richTextElementEntityFactory.withParent(cardNode).build(); + + await em.persistAndFlush([columnBoardNode, columnNode, cardNode, element, sibling]); + em.clear(); - const invalidUser = userFactory.build(); - await em.persistAndFlush([invalidUser]); - currentUser = mapUserToCurrentUser(invalidUser); + const loggedInClient = await apiClient.login(teacherAccount); - const response = await api.delete(element.id); + return { loggedInClient, columnBoardNode, columnNode, cardNode, element, sibling }; + }; + + it('should return status 403', async () => { + const { element, loggedInClient } = await setup(); + + const response = await loggedInClient.delete(element.id); expect(response.status).toEqual(403); }); }); describe('for drawing element', () => { - const drawingSetup = async () => { - await cleanupCollections(em); - const teacher = userFactory.asTeacher().build(); - const student = userFactory.asStudent().build(); - const course = courseFactory.build({ teachers: [teacher], students: [student] }); - await em.persistAndFlush([teacher, student, course]); + describe('with authorized teacher user', () => { + const drawingSetup = async () => { + await cleanupCollections(em); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + await em.persistAndFlush([teacherAccount, teacherUser, course]); - const columnBoardNode = columnBoardEntityFactory.build({ - context: { id: course.id, type: BoardExternalReferenceType.Course }, - }); - const columnNode = columnEntityFactory.withParent(columnBoardNode).build(); - const cardNode = cardEntityFactory.withParent(columnNode).build(); - const element = drawingElementEntityFactory.withParent(cardNode).build(); + const columnBoardNode = columnBoardEntityFactory.build({ + context: { id: course.id, type: BoardExternalReferenceType.Course }, + }); + const columnNode = columnEntityFactory.withParent(columnBoardNode).build(); + const cardNode = cardEntityFactory.withParent(columnNode).build(); + const element = drawingElementEntityFactory.withParent(cardNode).build(); - filesStorageClientAdapterService.deleteFilesOfParent.mockResolvedValueOnce([]); - drawingElementAdapterService.deleteDrawingBinData.mockResolvedValueOnce(); + filesStorageClientAdapterService.deleteFilesOfParent.mockResolvedValueOnce([]); + drawingElementAdapterService.deleteDrawingBinData.mockResolvedValueOnce(); - await em.persistAndFlush([columnBoardNode, columnNode, cardNode, element]); - em.clear(); + await em.persistAndFlush([columnBoardNode, columnNode, cardNode, element]); + em.clear(); - return { teacher, student, columnBoardNode, columnNode, cardNode, element }; - }; + const loggedInClient = await apiClient.login(teacherAccount); + + return { element, loggedInClient }; + }; - describe('with valid user', () => { it('should return status 204', async () => { - const { teacher, element } = await drawingSetup(); - currentUser = mapUserToCurrentUser(teacher); + const { element, loggedInClient } = await drawingSetup(); - const response = await api.delete(element.id); + const response = await loggedInClient.delete(element.id); expect(response.status).toEqual(204); }); it('should actually delete element', async () => { - const { teacher, element } = await drawingSetup(); - currentUser = mapUserToCurrentUser(teacher); + const { element, loggedInClient } = await drawingSetup(); - await api.delete(element.id); + await loggedInClient.delete(element.id); await expect(em.findOneOrFail(BoardNodeEntity, element.id)).rejects.toThrow(); }); }); - describe('with invalid user', () => { + describe('with not logged in teacher user', () => { + const drawingSetup = async () => { + await cleanupCollections(em); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + await em.persistAndFlush([teacherAccount, teacherUser, course]); + + const columnBoardNode = columnBoardEntityFactory.build({ + context: { id: course.id, type: BoardExternalReferenceType.Course }, + }); + const columnNode = columnEntityFactory.withParent(columnBoardNode).build(); + const cardNode = cardEntityFactory.withParent(columnNode).build(); + const element = drawingElementEntityFactory.withParent(cardNode).build(); + + filesStorageClientAdapterService.deleteFilesOfParent.mockResolvedValueOnce([]); + drawingElementAdapterService.deleteDrawingBinData.mockResolvedValueOnce(); + + await em.persistAndFlush([columnBoardNode, columnNode, cardNode, element]); + em.clear(); + + return { element }; + }; + + it('should return status 204', async () => { + const { element } = await drawingSetup(); + + const response = await apiClient.delete(element.id); + + expect(response.status).toEqual(401); + }); + }); + + describe('with with unauthorized student user', () => { + const drawingSetup = async () => { + await cleanupCollections(em); + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const course = courseFactory.build({ teachers: [], students: [studentUser] }); + await em.persistAndFlush([studentAccount, studentUser, course]); + + const columnBoardNode = columnBoardEntityFactory.build({ + context: { id: course.id, type: BoardExternalReferenceType.Course }, + }); + const columnNode = columnEntityFactory.withParent(columnBoardNode).build(); + const cardNode = cardEntityFactory.withParent(columnNode).build(); + const element = drawingElementEntityFactory.withParent(cardNode).build(); + + filesStorageClientAdapterService.deleteFilesOfParent.mockResolvedValueOnce([]); + drawingElementAdapterService.deleteDrawingBinData.mockResolvedValueOnce(); + + await em.persistAndFlush([columnBoardNode, columnNode, cardNode, element]); + em.clear(); + + const loggedInClient = await apiClient.login(studentAccount); + + return { element, loggedInClient }; + }; + it('should return status 403', async () => { - const { element, student } = await drawingSetup(); - currentUser = mapUserToCurrentUser(student); + const { element, loggedInClient } = await drawingSetup(); - const response = await api.delete(element.id); + const response = await loggedInClient.delete(element.id); expect(response.status).toEqual(403); }); diff --git a/apps/server/src/modules/board/controller/api-test/content-element-move.api.spec.ts b/apps/server/src/modules/board/controller/api-test/content-element-move.api.spec.ts index e11e0d309ab..9fdded4ecc6 100644 --- a/apps/server/src/modules/board/controller/api-test/content-element-move.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/content-element-move.api.spec.ts @@ -2,7 +2,10 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, pathOfChildren } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { diff --git a/apps/server/src/modules/board/controller/api-test/content-element-update-content.spec.ts b/apps/server/src/modules/board/controller/api-test/content-element-update-content.spec.ts index fc5ee4ac7a0..74116bb6f73 100644 --- a/apps/server/src/modules/board/controller/api-test/content-element-update-content.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/content-element-update-content.spec.ts @@ -4,7 +4,10 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { sanitizeRichText } from '@shared/controller/transformer/sanitize-html.transformer'; import { InputFormat } from '@shared/domain/types'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, ContentElementType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { diff --git a/apps/server/src/modules/board/controller/api-test/drawing-item-check-permission.api.spec.ts b/apps/server/src/modules/board/controller/api-test/drawing-item-check-permission.api.spec.ts index d3b8ec147f2..e16bef47f48 100644 --- a/apps/server/src/modules/board/controller/api-test/drawing-item-check-permission.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/drawing-item-check-permission.api.spec.ts @@ -2,14 +2,17 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType } from '../../domain'; import { cardEntityFactory, - columnEntityFactory, columnBoardEntityFactory, + columnEntityFactory, drawingElementEntityFactory, } from '../../testing'; -import { BoardExternalReferenceType } from '../../domain'; const baseRouteName = '/elements'; describe('drawing permission check (api)', () => { diff --git a/apps/server/src/modules/board/controller/api-test/submission-item-create.api.spec.ts b/apps/server/src/modules/board/controller/api-test/submission-item-create.api.spec.ts index 984b2ac42cf..f9e65d6b6b8 100644 --- a/apps/server/src/modules/board/controller/api-test/submission-item-create.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/submission-item-create.api.spec.ts @@ -2,13 +2,12 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - courseFactory, - userFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { cardEntityFactory, @@ -16,7 +15,6 @@ import { columnEntityFactory, submissionContainerElementEntityFactory, } from '../../testing'; -import { BoardExternalReferenceType } from '../../domain'; import { SubmissionItemResponse } from '../dto'; const baseRouteName = '/elements'; diff --git a/apps/server/src/modules/board/controller/api-test/submission-item-delete.api.spec.ts b/apps/server/src/modules/board/controller/api-test/submission-item-delete.api.spec.ts index 39e8c019229..60b49a961cf 100644 --- a/apps/server/src/modules/board/controller/api-test/submission-item-delete.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/submission-item-delete.api.spec.ts @@ -2,7 +2,11 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { cardEntityFactory, @@ -11,7 +15,6 @@ import { submissionContainerElementEntityFactory, submissionItemEntityFactory, } from '../../testing'; -import { BoardExternalReferenceType } from '../../domain'; import { SubmissionItemResponse } from '../dto'; const baseRouteName = '/board-submissions'; diff --git a/apps/server/src/modules/board/controller/api-test/submission-item-lookup.api.spec.ts b/apps/server/src/modules/board/controller/api-test/submission-item-lookup.api.spec.ts index 796048d8aef..54289d1cc8a 100644 --- a/apps/server/src/modules/board/controller/api-test/submission-item-lookup.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/submission-item-lookup.api.spec.ts @@ -2,13 +2,11 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - courseFactory, - userFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, ContentElementType } from '../../domain'; import { cardEntityFactory, diff --git a/apps/server/src/modules/board/controller/api-test/submission-item-update.api.spec.ts b/apps/server/src/modules/board/controller/api-test/submission-item-update.api.spec.ts index c134feefe0b..44547513708 100644 --- a/apps/server/src/modules/board/controller/api-test/submission-item-update.api.spec.ts +++ b/apps/server/src/modules/board/controller/api-test/submission-item-update.api.spec.ts @@ -2,7 +2,11 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, courseFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { BoardExternalReferenceType } from '../../domain'; import { BoardNodeEntity } from '../../repo'; import { cardEntityFactory, @@ -11,7 +15,6 @@ import { submissionContainerElementEntityFactory, submissionItemEntityFactory, } from '../../testing'; -import { BoardExternalReferenceType } from '../../domain'; const baseRouteName = '/board-submissions'; describe('submission item update (api)', () => { diff --git a/apps/server/src/modules/board/controller/media-board/api-test/media-board.api.spec.ts b/apps/server/src/modules/board/controller/media-board/api-test/media-board.api.spec.ts index 6613478ab8d..772882fd67c 100644 --- a/apps/server/src/modules/board/controller/media-board/api-test/media-board.api.spec.ts +++ b/apps/server/src/modules/board/controller/media-board/api-test/media-board.api.spec.ts @@ -1,14 +1,17 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; +import { mediaSourceEntityFactory } from '@modules/media-source/testing'; import { serverConfig, type ServerConfig, ServerTestModule } from '@modules/server'; import { contextExternalToolEntityFactory } from '@modules/tool/context-external-tool/testing'; import { externalToolEntityFactory } from '@modules/tool/external-tool/testing'; import { schoolExternalToolEntityFactory } from '@modules/tool/school-external-tool/testing'; import { MediaUserLicenseEntity } from '@modules/user-license/entity'; import { mediaUserLicenseEntityFactory } from '@modules/user-license/testing'; -import { mediaSourceEntityFactory } from '@modules/media-source/testing'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { DateToString, fileRecordFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { DateToString } from '@testing/date-to-string'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, BoardLayout, MediaBoardColors } from '../../../domain'; import { BoardNodeEntity } from '../../../repo'; import { diff --git a/apps/server/src/modules/board/controller/media-board/api-test/media-element.api.spec.ts b/apps/server/src/modules/board/controller/media-board/api-test/media-element.api.spec.ts index 0ef23aa3fb2..712fd4a7142 100644 --- a/apps/server/src/modules/board/controller/media-board/api-test/media-element.api.spec.ts +++ b/apps/server/src/modules/board/controller/media-board/api-test/media-element.api.spec.ts @@ -6,7 +6,8 @@ import { externalToolEntityFactory } from '@modules/tool/external-tool/testing'; import { schoolExternalToolEntityFactory } from '@modules/tool/school-external-tool/testing'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType } from '../../../domain'; import { BoardNodeEntity } from '../../../repo'; import { diff --git a/apps/server/src/modules/board/controller/media-board/api-test/media-line.api.spec.ts b/apps/server/src/modules/board/controller/media-board/api-test/media-line.api.spec.ts index aba9b5a7d8d..7e63941b3ac 100644 --- a/apps/server/src/modules/board/controller/media-board/api-test/media-line.api.spec.ts +++ b/apps/server/src/modules/board/controller/media-board/api-test/media-line.api.spec.ts @@ -2,12 +2,13 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { type ServerConfig, serverConfig, ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; -import { BoardNodeEntity } from '../../../repo'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { BoardExternalReferenceType, MediaBoardColors } from '../../../domain'; +import { BoardNodeEntity } from '../../../repo'; +import { mediaBoardEntityFactory, mediaLineEntityFactory } from '../../../testing'; import { MoveColumnBodyParams, RenameBodyParams } from '../../dto'; import { CollapsableBodyParams, ColorBodyParams } from '../dto'; -import { mediaBoardEntityFactory, mediaLineEntityFactory } from '../../../testing'; const baseRouteName = '/media-lines'; diff --git a/apps/server/src/modules/board/gateway/api-test/board-collaboration.gateway.spec.ts b/apps/server/src/modules/board/gateway/api-test/board-collaboration.gateway.spec.ts index 0b587e5a9b5..537a692dd96 100644 --- a/apps/server/src/modules/board/gateway/api-test/board-collaboration.gateway.spec.ts +++ b/apps/server/src/modules/board/gateway/api-test/board-collaboration.gateway.spec.ts @@ -4,8 +4,12 @@ import { Test } from '@nestjs/testing'; import { MongoIoAdapter } from '@infra/socketio'; import { InputFormat } from '@shared/domain/types/input-format.types'; -import { cleanupCollections, courseFactory, userFactory } from '@shared/testing'; -import { getSocketApiClient, waitForEvent } from '@shared/testing/test-socket-api-client'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { JwtAuthenticationFactory } from '@testing/factory/jwt-authentication.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { getSocketApiClient, waitForEvent } from '@testing/test-socket-api-client'; import { Socket } from 'socket.io-client'; import { BoardCollaborationTestModule } from '../../board-collaboration.app.module'; import { BoardExternalReferenceType, CardProps, ContentElementType } from '../../domain'; @@ -48,14 +52,34 @@ describe(BoardCollaborationGateway.name, () => { const setup = async () => { await cleanupCollections(em); - const user = userFactory.buildWithId(); - const unauthorizedUser = userFactory.buildWithId(); + const school = schoolEntityFactory.build(); + const { teacherUser, teacherAccount } = UserAndAccountTestFactory.buildTeacher({ school }); - const course = courseFactory.build({ teachers: [user] }); - await em.persistAndFlush([user, unauthorizedUser, course]); + const teacherAuthJwt = JwtAuthenticationFactory.createJwt({ + accountId: teacherAccount.id, + userId: teacherUser.id, + schoolId: teacherUser.school.id, + roles: [teacherUser.roles[0].id], + support: false, + isExternalUser: false, + }); + + const { studentUser, studentAccount } = UserAndAccountTestFactory.buildStudent({ school }); + + const studentAuthJwt = JwtAuthenticationFactory.createJwt({ + accountId: studentAccount.id, + userId: studentUser.id, + schoolId: studentUser.school.id, + roles: [studentUser.roles[0].id], + support: false, + isExternalUser: false, + }); + + const course = courseFactory.build({ teachers: [teacherUser] }); + await em.persistAndFlush([teacherUser, teacherAccount, studentUser, studentAccount, course]); - ioClient = await getSocketApiClient(app, user); - unauthorizedIoClient = await getSocketApiClient(app, unauthorizedUser); + ioClient = await getSocketApiClient(app, teacherAuthJwt); + unauthorizedIoClient = await getSocketApiClient(app, studentAuthJwt); const columnBoardNode = columnBoardEntityFactory.buildWithId({ context: { id: course.id, type: BoardExternalReferenceType.Course }, diff --git a/apps/server/src/modules/board/metrics/metrics.service.spec.ts b/apps/server/src/modules/board/metrics/metrics.service.spec.ts index 9da48af0baa..dc3de9cd0c9 100644 --- a/apps/server/src/modules/board/metrics/metrics.service.spec.ts +++ b/apps/server/src/modules/board/metrics/metrics.service.spec.ts @@ -1,8 +1,9 @@ import { DeepMocked, createMock } from '@golevelup/ts-jest'; import { Test, TestingModule } from '@nestjs/testing'; -import { UserService } from '@src/modules/user'; import { RoleName } from '@shared/domain/interface'; -import { roleFactory, userDoFactory } from '@shared/testing'; +import { UserService } from '@src/modules/user'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { MetricsService } from './metrics.service'; describe(MetricsService.name, () => { diff --git a/apps/server/src/modules/board/repo/board-node.repo.spec.ts b/apps/server/src/modules/board/repo/board-node.repo.spec.ts index 3a6cf173d23..1e6b6cf096c 100644 --- a/apps/server/src/modules/board/repo/board-node.repo.spec.ts +++ b/apps/server/src/modules/board/repo/board-node.repo.spec.ts @@ -1,8 +1,8 @@ +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { BaseEntityWithTimestamps } from '@shared/domain/entity'; -import { cleanupCollections } from '@shared/testing'; -import { MongoMemoryDatabaseModule } from '@src/infra/database'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { ColumnBoard } from '../domain'; import { cardFactory, columnBoardFactory, columnFactory } from '../testing'; import { BoardNodeRepo } from './board-node.repo'; diff --git a/apps/server/src/modules/board/service/board-node-authorizable.service.spec.ts b/apps/server/src/modules/board/service/board-node-authorizable.service.spec.ts index 10d768d1c73..064dbc1971b 100644 --- a/apps/server/src/modules/board/service/board-node-authorizable.service.spec.ts +++ b/apps/server/src/modules/board/service/board-node-authorizable.service.spec.ts @@ -1,13 +1,13 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { AuthorizableReferenceType, AuthorizationInjectionService } from '@modules/authorization'; -import { columnBoardFactory, columnFactory } from '../testing'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@testing/setup-entities'; import { BoardNodeAuthorizable, BoardRoles, UserWithBoardRoles } from '../domain'; import { BoardNodeRepo } from '../repo'; -import { BoardContextService } from './internal/board-context.service'; +import { columnBoardFactory, columnFactory } from '../testing'; import { BoardNodeAuthorizableService } from './board-node-authorizable.service'; import { BoardNodeService } from './board-node.service'; +import { BoardContextService } from './internal/board-context.service'; describe(BoardNodeAuthorizableService.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/board/service/board-node-permission.service.spec.ts b/apps/server/src/modules/board/service/board-node-permission.service.spec.ts index 3d636d1561c..d0ac8fe1ea2 100644 --- a/apps/server/src/modules/board/service/board-node-permission.service.spec.ts +++ b/apps/server/src/modules/board/service/board-node-permission.service.spec.ts @@ -1,11 +1,12 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Action, AuthorizationContext, AuthorizationService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { BoardNodeAuthorizable, BoardRoles, UserWithBoardRoles } from '../domain'; +import { columnBoardFactory } from '../testing'; import { BoardNodeAuthorizableService } from './board-node-authorizable.service'; import { BoardNodePermissionService } from './board-node-permission.service'; -import { columnBoardFactory } from '../testing'; describe(BoardNodePermissionService.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/board/service/board-node.service.spec.ts b/apps/server/src/modules/board/service/board-node.service.spec.ts index 77449a10034..a586446bf56 100644 --- a/apps/server/src/modules/board/service/board-node.service.spec.ts +++ b/apps/server/src/modules/board/service/board-node.service.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ObjectId } from '@mikro-orm/mongodb'; import { NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { Card, ColumnBoard } from '../domain'; import { BoardNodeRepo } from '../repo'; import { diff --git a/apps/server/src/modules/board/service/event/user-deleted-event-handler.service.spec.ts b/apps/server/src/modules/board/service/event/user-deleted-event-handler.service.spec.ts index d8482bcad0e..e4248daf5b5 100644 --- a/apps/server/src/modules/board/service/event/user-deleted-event-handler.service.spec.ts +++ b/apps/server/src/modules/board/service/event/user-deleted-event-handler.service.spec.ts @@ -11,8 +11,8 @@ import { } from '@modules/deletion'; import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { setupEntities } from '@testing/setup-entities'; import { mediaBoardFactory } from '../../testing'; import { BoardNodeService } from '../board-node.service'; import { MediaBoardService } from '../media-board'; diff --git a/apps/server/src/modules/board/service/internal/board-context.service.spec.ts b/apps/server/src/modules/board/service/internal/board-context.service.spec.ts index 322d9ea4361..79ff2a5ae82 100644 --- a/apps/server/src/modules/board/service/internal/board-context.service.spec.ts +++ b/apps/server/src/modules/board/service/internal/board-context.service.spec.ts @@ -7,7 +7,11 @@ import { roomFactory } from '@modules/room/testing'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission, RoleName } from '@shared/domain/interface'; import { CourseRepo } from '@shared/repo/course'; -import { courseFactory, groupFactory, roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { groupFactory } from '@testing/factory/domainobject'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { BoardExternalReferenceType, BoardRoles, UserWithBoardRoles } from '../../domain'; import { columnBoardFactory, columnFactory } from '../../testing'; import { BoardContextService } from './board-context.service'; diff --git a/apps/server/src/modules/board/service/internal/board-node-copy-general.service.spec.ts b/apps/server/src/modules/board/service/internal/board-node-copy-general.service.spec.ts index 3d6b27b7ec5..e1a61f1c06b 100644 --- a/apps/server/src/modules/board/service/internal/board-node-copy-general.service.spec.ts +++ b/apps/server/src/modules/board/service/internal/board-node-copy-general.service.spec.ts @@ -2,13 +2,13 @@ import { createMock } from '@golevelup/ts-jest'; import { ObjectId } from '@mikro-orm/mongodb'; import { CopyElementType, CopyHelperService, CopyStatus, CopyStatusEnum } from '@modules/copy-helper'; import { StorageLocation } from '@modules/files-storage/interface'; -import { SchoolExternalToolService } from '@modules/tool/school-external-tool/service'; import { ContextExternalToolService } from '@modules/tool/context-external-tool/service'; +import { SchoolExternalToolService } from '@modules/tool/school-external-tool/service'; import { ToolConfig } from '@modules/tool/tool-config'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { FilesStorageClientAdapterService } from '@src/modules/files-storage-client'; +import { setupEntities } from '@testing/setup-entities'; import { cardFactory, collaborativeTextEditorFactory, diff --git a/apps/server/src/modules/board/service/internal/board-node-copy-specific.service.spec.ts b/apps/server/src/modules/board/service/internal/board-node-copy-specific.service.spec.ts index 80ce46a5082..2a5ca3a4a9f 100644 --- a/apps/server/src/modules/board/service/internal/board-node-copy-specific.service.spec.ts +++ b/apps/server/src/modules/board/service/internal/board-node-copy-specific.service.spec.ts @@ -1,18 +1,20 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ObjectId } from '@mikro-orm/mongodb'; import { CopyElementType, CopyHelperService, CopyStatus, CopyStatusEnum } from '@modules/copy-helper'; +import { FilesStorageClientAdapterService } from '@modules/files-storage-client'; +import { CopyFileDto } from '@modules/files-storage-client/dto'; import { StorageLocation } from '@modules/files-storage/interface'; +import { CopyContextExternalToolRejectData } from '@modules/tool/context-external-tool/domain'; import { ContextExternalToolService } from '@modules/tool/context-external-tool/service'; +import { + contextExternalToolFactory, + copyContextExternalToolRejectDataFactory, +} from '@modules/tool/context-external-tool/testing'; import { ToolConfig } from '@modules/tool/tool-config'; -import { copyContextExternalToolRejectDataFactory } from '@modules/tool/context-external-tool/testing'; -import { CopyContextExternalToolRejectData } from '@modules/tool/context-external-tool/domain'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; -import { FilesStorageClientAdapterService } from '@src/modules/files-storage-client'; -import { CopyFileDto } from '@src/modules/files-storage-client/dto'; -import { contextExternalToolFactory } from '@src/modules/tool/context-external-tool/testing'; +import { setupEntities } from '@testing/setup-entities'; import { Card, CollaborativeTextEditorElement, diff --git a/apps/server/src/modules/board/service/internal/board-node-delete-hooks.service.spec.ts b/apps/server/src/modules/board/service/internal/board-node-delete-hooks.service.spec.ts index 50105169fdf..febca79475a 100644 --- a/apps/server/src/modules/board/service/internal/board-node-delete-hooks.service.spec.ts +++ b/apps/server/src/modules/board/service/internal/board-node-delete-hooks.service.spec.ts @@ -1,11 +1,11 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { TldrawClientAdapter } from '@infra/tldraw-client'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { CollaborativeTextEditorService } from '@src/modules/collaborative-text-editor'; import { FilesStorageClientAdapterService } from '@src/modules/files-storage-client'; import { ContextExternalToolService } from '@src/modules/tool/context-external-tool'; import { contextExternalToolFactory } from '@src/modules/tool/context-external-tool/testing'; +import { setupEntities } from '@testing/setup-entities'; import { collaborativeTextEditorFactory, drawingElementFactory, diff --git a/apps/server/src/modules/board/service/internal/column-board-copy.service.spec.ts b/apps/server/src/modules/board/service/internal/column-board-copy.service.spec.ts index 25feffbeb24..d199c41db18 100644 --- a/apps/server/src/modules/board/service/internal/column-board-copy.service.spec.ts +++ b/apps/server/src/modules/board/service/internal/column-board-copy.service.spec.ts @@ -4,12 +4,14 @@ import { CopyElementType, CopyStatus, CopyStatusEnum } from '@modules/copy-helpe import { FilesStorageClientAdapterService } from '@modules/files-storage-client/service'; import { StorageLocation } from '@modules/files-storage/interface'; import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, setupEntities } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { setupEntities } from '@testing/setup-entities'; import { BoardExternalReferenceType } from '../../domain/types'; import { columnBoardFactory } from '../../testing/column-board.factory'; import { BoardNodeService } from '../board-node.service'; import { ColumnBoardCopyService, CopyColumnBoardParams } from './column-board-copy.service'; import { ColumnBoardTitleService } from './column-board-title.service'; + // Warning: do not move the BoardNodeCopyService import up. Otherwise it will lead to dependency cycle. import { BoardNodeCopyService } from './board-node-copy.service'; diff --git a/apps/server/src/modules/board/service/internal/column-board-link.service.spec.ts b/apps/server/src/modules/board/service/internal/column-board-link.service.spec.ts index aca7d8ea204..beaa46ebab8 100644 --- a/apps/server/src/modules/board/service/internal/column-board-link.service.spec.ts +++ b/apps/server/src/modules/board/service/internal/column-board-link.service.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { EntityId } from '@shared/domain/types'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { ColumnBoard, LinkElement } from '../../domain'; import { BoardNodeRepo } from '../../repo'; import { diff --git a/apps/server/src/modules/board/service/media-board/media-available-line.service.spec.ts b/apps/server/src/modules/board/service/media-board/media-available-line.service.spec.ts index 7a63e64773b..53f45d1d61a 100644 --- a/apps/server/src/modules/board/service/media-board/media-available-line.service.spec.ts +++ b/apps/server/src/modules/board/service/media-board/media-available-line.service.spec.ts @@ -15,7 +15,8 @@ import { schoolExternalToolFactory } from '@modules/tool/school-external-tool/te import { Test, TestingModule } from '@nestjs/testing'; import { Page } from '@shared/domain/domainobject'; import { User } from '@shared/domain/entity'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { MediaAvailableLine, MediaBoard, MediaExternalToolElement } from '../../domain'; import { MediaAvailableLineService } from './media-available-line.service'; diff --git a/apps/server/src/modules/board/testing/board-node-authorizable.factory.ts b/apps/server/src/modules/board/testing/board-node-authorizable.factory.ts index e34d399b5c7..a6cfd651df1 100644 --- a/apps/server/src/modules/board/testing/board-node-authorizable.factory.ts +++ b/apps/server/src/modules/board/testing/board-node-authorizable.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { DomainObjectFactory } from '@shared/testing'; +import { DomainObjectFactory } from '@testing/factory/domainobject'; import { BoardNodeAuthorizable, BoardNodeAuthorizableProps } from '../domain'; import { columnBoardFactory } from './column-board.factory'; import { columnFactory } from './column.factory'; diff --git a/apps/server/src/modules/board/testing/card.factory.ts b/apps/server/src/modules/board/testing/card.factory.ts index 71999aef7e8..7684e4b1ff0 100644 --- a/apps/server/src/modules/board/testing/card.factory.ts +++ b/apps/server/src/modules/board/testing/card.factory.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { Card, CardProps, ROOT_PATH } from '../domain'; export const cardFactory = BaseFactory.define(Card, ({ sequence }) => { diff --git a/apps/server/src/modules/board/testing/collaborative-text-editor.factory.ts b/apps/server/src/modules/board/testing/collaborative-text-editor.factory.ts index 1bc197060a3..95e7167a1f4 100644 --- a/apps/server/src/modules/board/testing/collaborative-text-editor.factory.ts +++ b/apps/server/src/modules/board/testing/collaborative-text-editor.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { CollaborativeTextEditorElement, CollaborativeTextEditorElementProps, ROOT_PATH } from '../domain'; export const collaborativeTextEditorFactory = BaseFactory.define< diff --git a/apps/server/src/modules/board/testing/column-board.factory.ts b/apps/server/src/modules/board/testing/column-board.factory.ts index 48c925dcaf6..03e9966565e 100644 --- a/apps/server/src/modules/board/testing/column-board.factory.ts +++ b/apps/server/src/modules/board/testing/column-board.factory.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { BoardExternalReferenceType, BoardLayout, ColumnBoard, ColumnBoardProps, ROOT_PATH } from '../domain'; class ColumnBoardFactory extends BaseFactory { diff --git a/apps/server/src/modules/board/testing/column.factory.ts b/apps/server/src/modules/board/testing/column.factory.ts index 9de33a2765a..ece7263bd3f 100644 --- a/apps/server/src/modules/board/testing/column.factory.ts +++ b/apps/server/src/modules/board/testing/column.factory.ts @@ -1,6 +1,6 @@ /* istanbul ignore file */ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { Column, ColumnProps, ROOT_PATH } from '../domain'; export const columnFactory = BaseFactory.define(Column, ({ sequence }) => { diff --git a/apps/server/src/modules/board/testing/deleted-element.factory.ts b/apps/server/src/modules/board/testing/deleted-element.factory.ts index 23a682bd3c8..b65c13dcc3a 100644 --- a/apps/server/src/modules/board/testing/deleted-element.factory.ts +++ b/apps/server/src/modules/board/testing/deleted-element.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { ContentElementType, DeletedElement, DeletedElementProps, ROOT_PATH } from '../domain'; export const deletedElementFactory = BaseFactory.define( diff --git a/apps/server/src/modules/board/testing/drawing-element.factory.ts b/apps/server/src/modules/board/testing/drawing-element.factory.ts index 678a23384bc..ee137090962 100644 --- a/apps/server/src/modules/board/testing/drawing-element.factory.ts +++ b/apps/server/src/modules/board/testing/drawing-element.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { DrawingElement, DrawingElementProps, ROOT_PATH } from '../domain'; export const drawingElementFactory = BaseFactory.define( diff --git a/apps/server/src/modules/board/testing/external-tool-element.factory.ts b/apps/server/src/modules/board/testing/external-tool-element.factory.ts index 06e6ec4f5ea..288872801a8 100644 --- a/apps/server/src/modules/board/testing/external-tool-element.factory.ts +++ b/apps/server/src/modules/board/testing/external-tool-element.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { ExternalToolElement, ExternalToolElementProps, ROOT_PATH } from '../domain'; export const externalToolElementFactory = BaseFactory.define( diff --git a/apps/server/src/modules/board/testing/file-element.factory.ts b/apps/server/src/modules/board/testing/file-element.factory.ts index 5599de53251..3c06e8fe9da 100644 --- a/apps/server/src/modules/board/testing/file-element.factory.ts +++ b/apps/server/src/modules/board/testing/file-element.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { FileElement, FileElementProps, ROOT_PATH } from '../domain'; export const fileElementFactory = BaseFactory.define(FileElement, ({ sequence }) => { diff --git a/apps/server/src/modules/board/testing/link-element.factory.ts b/apps/server/src/modules/board/testing/link-element.factory.ts index 257d1f23f72..5ca08669602 100644 --- a/apps/server/src/modules/board/testing/link-element.factory.ts +++ b/apps/server/src/modules/board/testing/link-element.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { LinkElement, LinkElementProps, ROOT_PATH } from '../domain'; export const linkElementFactory = BaseFactory.define(LinkElement, ({ sequence }) => { diff --git a/apps/server/src/modules/board/testing/media-available-line-element.factory.ts b/apps/server/src/modules/board/testing/media-available-line-element.factory.ts index d1615fc2239..16c07724b9f 100644 --- a/apps/server/src/modules/board/testing/media-available-line-element.factory.ts +++ b/apps/server/src/modules/board/testing/media-available-line-element.factory.ts @@ -1,5 +1,5 @@ -import { BaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaAvailableLineElement, MediaAvailableLineElementProps } from '../domain'; export const mediaAvailableLineElementFactory = BaseFactory.define< diff --git a/apps/server/src/modules/board/testing/media-available-line.factory.ts b/apps/server/src/modules/board/testing/media-available-line.factory.ts index ba9ee9e716b..f2f10a9b214 100644 --- a/apps/server/src/modules/board/testing/media-available-line.factory.ts +++ b/apps/server/src/modules/board/testing/media-available-line.factory.ts @@ -1,6 +1,6 @@ +import { BaseFactory } from '@testing/factory/base.factory'; import { DeepPartial } from 'fishery'; -import { BaseFactory } from '@shared/testing'; -import { MediaBoardColors, MediaAvailableLine, MediaAvailableLineElement, MediaAvailableLineProps } from '../domain'; +import { MediaAvailableLine, MediaAvailableLineElement, MediaAvailableLineProps, MediaBoardColors } from '../domain'; class MediaAvailableLineFactory extends BaseFactory { withElement(element: MediaAvailableLineElement): this { diff --git a/apps/server/src/modules/board/testing/media-board.factory.ts b/apps/server/src/modules/board/testing/media-board.factory.ts index 3bbd8a705a0..a3cf5886fbd 100644 --- a/apps/server/src/modules/board/testing/media-board.factory.ts +++ b/apps/server/src/modules/board/testing/media-board.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { BoardExternalReferenceType, BoardLayout, diff --git a/apps/server/src/modules/board/testing/media-external-tool-element.factory.ts b/apps/server/src/modules/board/testing/media-external-tool-element.factory.ts index cb1dbf4c2fc..a47cc9d3e5e 100644 --- a/apps/server/src/modules/board/testing/media-external-tool-element.factory.ts +++ b/apps/server/src/modules/board/testing/media-external-tool-element.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaExternalToolElement, MediaExternalToolElementProps, ROOT_PATH } from '../domain'; export const mediaExternalToolElementFactory = BaseFactory.define< diff --git a/apps/server/src/modules/board/testing/media-line.factory.ts b/apps/server/src/modules/board/testing/media-line.factory.ts index 2f2c7bf3395..47214442397 100644 --- a/apps/server/src/modules/board/testing/media-line.factory.ts +++ b/apps/server/src/modules/board/testing/media-line.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaLine, MediaLineProps, ROOT_PATH } from '../domain'; import { MediaBoardColors } from '../domain/media-board/types'; diff --git a/apps/server/src/modules/board/testing/rich-text-element.factory.ts b/apps/server/src/modules/board/testing/rich-text-element.factory.ts index 215c1d53326..cd7082eeee8 100644 --- a/apps/server/src/modules/board/testing/rich-text-element.factory.ts +++ b/apps/server/src/modules/board/testing/rich-text-element.factory.ts @@ -1,6 +1,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { InputFormat } from '@shared/domain/types'; -import { BaseFactory } from '@shared/testing/factory/base.factory'; +import { BaseFactory } from '@testing/factory/base.factory'; import { RichTextElement, RichTextElementProps, ROOT_PATH } from '../domain'; export const richTextElementFactory = BaseFactory.define( diff --git a/apps/server/src/modules/board/testing/submission-container-element.factory.ts b/apps/server/src/modules/board/testing/submission-container-element.factory.ts index 42d67af9176..0a28758b5a3 100644 --- a/apps/server/src/modules/board/testing/submission-container-element.factory.ts +++ b/apps/server/src/modules/board/testing/submission-container-element.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { ROOT_PATH, SubmissionContainerElement, SubmissionContainerElementProps } from '../domain'; export const submissionContainerElementFactory = BaseFactory.define< diff --git a/apps/server/src/modules/board/testing/submission-item.factory.ts b/apps/server/src/modules/board/testing/submission-item.factory.ts index cc01e1cb114..84bbed2d191 100644 --- a/apps/server/src/modules/board/testing/submission-item.factory.ts +++ b/apps/server/src/modules/board/testing/submission-item.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { ROOT_PATH, SubmissionItem, SubmissionItemProps } from '../domain'; export const submissionItemFactory = BaseFactory.define(SubmissionItem, () => { diff --git a/apps/server/src/modules/board/testing/video-conference-element.factory.ts b/apps/server/src/modules/board/testing/video-conference-element.factory.ts index 3a6e146ed3f..33b83893f6a 100644 --- a/apps/server/src/modules/board/testing/video-conference-element.factory.ts +++ b/apps/server/src/modules/board/testing/video-conference-element.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { ROOT_PATH, VideoConferenceElement, VideoConferenceElementProps } from '../domain'; export const videoConferenceElementFactory = BaseFactory.define( diff --git a/apps/server/src/modules/board/uc/board.uc.spec.ts b/apps/server/src/modules/board/uc/board.uc.spec.ts index 276f3275458..974f1cde702 100644 --- a/apps/server/src/modules/board/uc/board.uc.spec.ts +++ b/apps/server/src/modules/board/uc/board.uc.spec.ts @@ -4,11 +4,12 @@ import { Action, AuthorizationService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; import { CourseRepo } from '@shared/repo/course'; -import { setupEntities, userFactory } from '@shared/testing'; -import { courseFactory } from '@shared/testing/factory'; import { LegacyLogger } from '@src/core/logger'; import { RoomService } from '@src/modules/room'; import { RoomMembershipService } from '@src/modules/room-membership'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CopyElementType, CopyStatus, CopyStatusEnum } from '../../copy-helper'; import { BoardExternalReferenceType, BoardLayout, BoardNodeFactory, Column, ColumnBoard } from '../domain'; import { BoardNodePermissionService, BoardNodeService, ColumnBoardService } from '../service'; diff --git a/apps/server/src/modules/board/uc/card.uc.spec.ts b/apps/server/src/modules/board/uc/card.uc.spec.ts index be5bba4afa8..4533f5e95cd 100644 --- a/apps/server/src/modules/board/uc/card.uc.spec.ts +++ b/apps/server/src/modules/board/uc/card.uc.spec.ts @@ -1,8 +1,9 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Action, AuthorizationService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities, userFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { BoardNodeAuthorizable, BoardNodeFactory, Card, ContentElementType } from '../domain'; import { BoardNodeAuthorizableService, BoardNodePermissionService, BoardNodeService } from '../service'; import { cardFactory, columnBoardFactory, richTextElementFactory } from '../testing'; diff --git a/apps/server/src/modules/board/uc/column.uc.spec.ts b/apps/server/src/modules/board/uc/column.uc.spec.ts index 3c80734550e..83f6c4baf4c 100644 --- a/apps/server/src/modules/board/uc/column.uc.spec.ts +++ b/apps/server/src/modules/board/uc/column.uc.spec.ts @@ -1,8 +1,9 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Action } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities, userFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { BoardNodeFactory, Card, Column, ContentElementType } from '../domain'; import { BoardNodeService } from '../service'; import { BoardNodePermissionService } from '../service/board-node-permission.service'; diff --git a/apps/server/src/modules/board/uc/element.uc.spec.ts b/apps/server/src/modules/board/uc/element.uc.spec.ts index 3309571196c..1ab2c4347ba 100644 --- a/apps/server/src/modules/board/uc/element.uc.spec.ts +++ b/apps/server/src/modules/board/uc/element.uc.spec.ts @@ -3,9 +3,9 @@ import { Action } from '@modules/authorization'; import { HttpService } from '@nestjs/axios'; import { Test, TestingModule } from '@nestjs/testing'; import { InputFormat } from '@shared/domain/types'; -import { setupEntities } from '@shared/testing/setup-entities'; -import { userFactory } from '@shared/testing/factory'; import { Logger } from '@src/core/logger'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { RichTextContentBody } from '../controller/dto'; import { BoardNodeFactory } from '../domain'; import { BoardNodeAuthorizableService, BoardNodePermissionService, BoardNodeService } from '../service'; diff --git a/apps/server/src/modules/board/uc/media-board/media-available-line.uc.spec.ts b/apps/server/src/modules/board/uc/media-board/media-available-line.uc.spec.ts index 534e5b133c0..6e7da60a8d5 100644 --- a/apps/server/src/modules/board/uc/media-board/media-available-line.uc.spec.ts +++ b/apps/server/src/modules/board/uc/media-board/media-available-line.uc.spec.ts @@ -2,6 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ObjectId } from '@mikro-orm/mongodb'; import { Action, AuthorizationService } from '@modules/authorization'; import { ExternalTool } from '@modules/tool/external-tool/domain'; +import { externalToolFactory } from '@modules/tool/external-tool/testing'; import { SchoolExternalTool } from '@modules/tool/school-external-tool/domain'; import { schoolExternalToolFactory } from '@modules/tool/school-external-tool/testing'; import { MediaUserLicense, mediaUserLicenseFactory, MediaUserLicenseService } from '@modules/user-license'; @@ -9,14 +10,14 @@ import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { FeatureDisabledLoggableException } from '@shared/common/loggable-exception'; import { User } from '@shared/domain/entity'; -import { setupEntities, userFactory as userEntityFactory, userFactory } from '@shared/testing'; -import { externalToolFactory } from '@modules/tool/external-tool/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { MediaAvailableLine, MediaAvailableLineElement, MediaBoard, - MediaExternalToolElement, MediaBoardColors, + MediaExternalToolElement, } from '../../domain'; import type { MediaBoardConfig } from '../../media-board.config'; import { @@ -28,8 +29,8 @@ import { import { MediaAvailableLineUc } from './media-available-line.uc'; import { - mediaAvailableLineFactory, mediaAvailableLineElementFactory, + mediaAvailableLineFactory, mediaBoardFactory, mediaExternalToolElementFactory, } from '../../testing'; @@ -441,7 +442,7 @@ describe(MediaAvailableLineUc.name, () => { describe('updateAvailableLineColor', () => { describe('when changes the color of the available line', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); configService.get.mockReturnValueOnce(true); @@ -472,7 +473,7 @@ describe(MediaAvailableLineUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); configService.get.mockReturnValueOnce(false); @@ -496,7 +497,7 @@ describe(MediaAvailableLineUc.name, () => { describe('collapseAvailableLine', () => { describe('when changing the visibility of the available line', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); configService.get.mockReturnValueOnce(true); @@ -527,7 +528,7 @@ describe(MediaAvailableLineUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); configService.get.mockReturnValueOnce(false); diff --git a/apps/server/src/modules/board/uc/media-board/media-board.uc.spec.ts b/apps/server/src/modules/board/uc/media-board/media-board.uc.spec.ts index 8d1b231cb98..dd7c64df291 100644 --- a/apps/server/src/modules/board/uc/media-board/media-board.uc.spec.ts +++ b/apps/server/src/modules/board/uc/media-board/media-board.uc.spec.ts @@ -3,12 +3,13 @@ import { Action, AuthorizationContextBuilder, AuthorizationService } from '@modu import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { FeatureDisabledLoggableException } from '@shared/common/loggable-exception'; -import { setupEntities, userFactory as userEntityFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; +import { BoardLayout, MediaBoardNodeFactory } from '../../domain'; import type { MediaBoardConfig } from '../../media-board.config'; import { BoardNodePermissionService, BoardNodeService, MediaBoardService } from '../../service'; import { mediaBoardFactory, mediaLineFactory } from '../../testing'; import { MediaBoardUc } from './media-board.uc'; -import { BoardLayout, MediaBoardNodeFactory } from '../../domain'; describe(MediaBoardUc.name, () => { let module: TestingModule; @@ -74,7 +75,7 @@ describe(MediaBoardUc.name, () => { describe('getMediaBoardForUser', () => { describe('when the user has no media board', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); configService.get.mockReturnValueOnce(true); @@ -111,7 +112,7 @@ describe(MediaBoardUc.name, () => { describe('when the user has a media board', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); configService.get.mockReturnValueOnce(true); @@ -147,7 +148,7 @@ describe(MediaBoardUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); configService.get.mockReturnValueOnce(false); @@ -167,7 +168,7 @@ describe(MediaBoardUc.name, () => { describe('createLine', () => { describe('when the user creates a new media line', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); const mediaLine = mediaLineFactory.build(); @@ -202,7 +203,7 @@ describe(MediaBoardUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); configService.get.mockReturnValueOnce(false); @@ -224,7 +225,7 @@ describe(MediaBoardUc.name, () => { describe('setLayout', () => { describe('when the user changes the layout of the media board', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build({ layout: BoardLayout.LIST, }); @@ -257,7 +258,7 @@ describe(MediaBoardUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); configService.get.mockReturnValueOnce(false); diff --git a/apps/server/src/modules/board/uc/media-board/media-element.uc.spec.ts b/apps/server/src/modules/board/uc/media-board/media-element.uc.spec.ts index ddfb2b69f97..3dbc5f9c8ea 100644 --- a/apps/server/src/modules/board/uc/media-board/media-element.uc.spec.ts +++ b/apps/server/src/modules/board/uc/media-board/media-element.uc.spec.ts @@ -1,14 +1,15 @@ import { createMock, type DeepMocked } from '@golevelup/ts-jest'; -import { ContextExternalTool } from '@modules/tool/context-external-tool/domain'; import { Action, AuthorizationService } from '@modules/authorization'; +import { ContextExternalTool } from '@modules/tool/context-external-tool/domain'; +import { contextExternalToolFactory } from '@modules/tool/context-external-tool/testing'; import { SchoolExternalToolService } from '@modules/tool/school-external-tool'; import { SchoolExternalTool } from '@modules/tool/school-external-tool/domain'; import { schoolExternalToolFactory } from '@modules/tool/school-external-tool/testing'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { FeatureDisabledLoggableException } from '@shared/common/loggable-exception'; -import { setupEntities, userFactory as userEntityFactory } from '@shared/testing'; -import { contextExternalToolFactory } from '@modules/tool/context-external-tool/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { MediaBoard, MediaBoardNodeFactory, MediaExternalToolElement, MediaLine } from '../../domain'; import { MediaBoardElementAlreadyExistsLoggableException } from '../../loggable'; import type { MediaBoardConfig } from '../../media-board.config'; @@ -86,7 +87,7 @@ describe(MediaElementUc.name, () => { describe('moveElement', () => { describe('when the user moves a media element', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); const mediaElement = mediaExternalToolElementFactory.build(); @@ -129,7 +130,7 @@ describe(MediaElementUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); const mediaElement = mediaExternalToolElementFactory.build(); @@ -155,7 +156,7 @@ describe(MediaElementUc.name, () => { describe('createElement', () => { describe('when the user creates a not existing media element', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); const mediaLine = mediaLineFactory.build(); const mediaElement = mediaExternalToolElementFactory.build(); @@ -253,7 +254,7 @@ describe(MediaElementUc.name, () => { describe('when the user creates an existing media element', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); const mediaLine = mediaLineFactory.build(); const mediaElement = mediaExternalToolElementFactory.build(); @@ -291,7 +292,7 @@ describe(MediaElementUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); const mediaElement = mediaExternalToolElementFactory.build(); @@ -317,7 +318,7 @@ describe(MediaElementUc.name, () => { describe('deleteElement', () => { describe('when the user deletes a media element', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaElement = mediaExternalToolElementFactory.build(); configService.get.mockReturnValueOnce(true); @@ -348,7 +349,7 @@ describe(MediaElementUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaElement = mediaExternalToolElementFactory.build(); configService.get.mockReturnValueOnce(false); diff --git a/apps/server/src/modules/board/uc/media-board/media-line.uc.spec.ts b/apps/server/src/modules/board/uc/media-board/media-line.uc.spec.ts index 96732a1e4dd..8fcc850fc2a 100644 --- a/apps/server/src/modules/board/uc/media-board/media-line.uc.spec.ts +++ b/apps/server/src/modules/board/uc/media-board/media-line.uc.spec.ts @@ -3,13 +3,14 @@ import { Action } from '@modules/authorization'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { FeatureDisabledLoggableException } from '@shared/common/loggable-exception'; -import { setupEntities, userFactory as userEntityFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; +import { MediaBoard, MediaLine } from '../../domain'; +import { MediaBoardColors } from '../../domain/media-board/types'; import type { MediaBoardConfig } from '../../media-board.config'; import { BoardNodePermissionService, BoardNodeService, MediaBoardService } from '../../service'; import { mediaBoardFactory, mediaLineFactory } from '../../testing'; import { MediaLineUc } from './media-line.uc'; -import { MediaBoard, MediaLine } from '../../domain'; -import { MediaBoardColors } from '../../domain/media-board/types'; describe(MediaLineUc.name, () => { let module: TestingModule; @@ -63,7 +64,7 @@ describe(MediaLineUc.name, () => { describe('moveLine', () => { describe('when the user moves a media line', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard: MediaBoard = mediaBoardFactory.build(); const mediaLine = mediaLineFactory.build(); @@ -105,7 +106,7 @@ describe(MediaLineUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaBoard = mediaBoardFactory.build(); const mediaLine = mediaLineFactory.build(); @@ -131,7 +132,7 @@ describe(MediaLineUc.name, () => { describe('updateLineTitle', () => { describe('when the user renames a media line', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); configService.get.mockReturnValueOnce(true); @@ -163,7 +164,7 @@ describe(MediaLineUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); configService.get.mockReturnValueOnce(false); @@ -187,7 +188,7 @@ describe(MediaLineUc.name, () => { describe('deleteLine', () => { describe('when the user deletes a media line', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); configService.get.mockReturnValueOnce(true); @@ -215,7 +216,7 @@ describe(MediaLineUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); configService.get.mockReturnValueOnce(false); @@ -237,7 +238,7 @@ describe(MediaLineUc.name, () => { describe('updateLineColor', () => { describe('when the user changes background color of media line', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); configService.get.mockReturnValueOnce(true); @@ -269,7 +270,7 @@ describe(MediaLineUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); configService.get.mockReturnValueOnce(false); @@ -293,7 +294,7 @@ describe(MediaLineUc.name, () => { describe('collapseLine', () => { describe('when the user collapse a media line', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); configService.get.mockReturnValueOnce(true); @@ -325,7 +326,7 @@ describe(MediaLineUc.name, () => { describe('when the feature is disabled', () => { const setup = () => { - const user = userEntityFactory.build(); + const user = userFactory.build(); const mediaLine = mediaLineFactory.build(); configService.get.mockReturnValueOnce(false); diff --git a/apps/server/src/modules/board/uc/submission-item.uc.spec.ts b/apps/server/src/modules/board/uc/submission-item.uc.spec.ts index a516784b6fe..3e14683d668 100644 --- a/apps/server/src/modules/board/uc/submission-item.uc.spec.ts +++ b/apps/server/src/modules/board/uc/submission-item.uc.spec.ts @@ -2,7 +2,8 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Action } from '@modules/authorization'; import { BadRequestException, ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { BoardNodeAuthorizable, BoardNodeFactory, diff --git a/apps/server/src/modules/class/domain/testing/factory/class.factory.ts b/apps/server/src/modules/class/domain/testing/factory/class.factory.ts index 63ae07d6809..c019cdb5e3a 100644 --- a/apps/server/src/modules/class/domain/testing/factory/class.factory.ts +++ b/apps/server/src/modules/class/domain/testing/factory/class.factory.ts @@ -1,8 +1,8 @@ -import { DoBaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { DoBaseFactory } from '@testing/factory/domainobject'; import { DeepPartial } from 'fishery'; -import { Class, ClassProps } from '../../class.do'; import { ClassSourceOptions } from '../../class-source-options.do'; +import { Class, ClassProps } from '../../class.do'; class ClassFactory extends DoBaseFactory { withUserIds(userIds: string[]): this { diff --git a/apps/server/src/modules/class/entity/testing/class.entity.spec.ts b/apps/server/src/modules/class/entity/testing/class.entity.spec.ts index 7339e74ddb4..6306a9e1a03 100644 --- a/apps/server/src/modules/class/entity/testing/class.entity.spec.ts +++ b/apps/server/src/modules/class/entity/testing/class.entity.spec.ts @@ -1,7 +1,7 @@ /* eslint-disable no-new */ -import { setupEntities } from '@shared/testing'; -import { classEntityFactory } from '@modules/class/entity/testing/factory/class.entity.factory'; import { ObjectId } from '@mikro-orm/mongodb'; +import { classEntityFactory } from '@modules/class/entity/testing/factory/class.entity.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ClassEntity } from '../class.entity'; describe(ClassEntity.name, () => { diff --git a/apps/server/src/modules/class/entity/testing/factory/class.entity.factory.ts b/apps/server/src/modules/class/entity/testing/factory/class.entity.factory.ts index 4089c70a9c7..c6c04c092c9 100644 --- a/apps/server/src/modules/class/entity/testing/factory/class.entity.factory.ts +++ b/apps/server/src/modules/class/entity/testing/factory/class.entity.factory.ts @@ -1,6 +1,6 @@ -import { ClassEntity, ClassEntityProps, ClassSourceOptionsEntity } from '@modules/class/entity'; -import { BaseFactory } from '@shared/testing/factory/base.factory'; import { ObjectId } from '@mikro-orm/mongodb'; +import { ClassEntity, ClassEntityProps, ClassSourceOptionsEntity } from '@modules/class/entity'; +import { BaseFactory } from '@testing/factory/base.factory'; import { DeepPartial } from 'fishery'; class ClassEntityFactory extends BaseFactory { diff --git a/apps/server/src/modules/class/repo/classes.repo.spec.ts b/apps/server/src/modules/class/repo/classes.repo.spec.ts index c2afd4de81a..8c9f072fe9a 100644 --- a/apps/server/src/modules/class/repo/classes.repo.spec.ts +++ b/apps/server/src/modules/class/repo/classes.repo.spec.ts @@ -5,7 +5,8 @@ import { Test } from '@nestjs/testing'; import { TestingModule } from '@nestjs/testing/testing-module'; import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { SchoolEntity } from '@shared/domain/entity'; -import { cleanupCollections, schoolEntityFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; import { randomUUID } from 'crypto'; import { Class } from '../domain'; import { ClassEntity } from '../entity'; diff --git a/apps/server/src/modules/class/service/class.service.spec.ts b/apps/server/src/modules/class/service/class.service.spec.ts index af54b8da4f2..116e82a022d 100644 --- a/apps/server/src/modules/class/service/class.service.spec.ts +++ b/apps/server/src/modules/class/service/class.service.spec.ts @@ -14,8 +14,8 @@ import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { EntityId } from '@shared/domain/types'; -import { setupEntities } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { setupEntities } from '@testing/setup-entities'; import { Class } from '../domain'; import { classFactory } from '../domain/testing'; import { classEntityFactory } from '../entity/testing'; diff --git a/apps/server/src/modules/collaborative-storage/controller/collaborative-storage.controller.spec.ts b/apps/server/src/modules/collaborative-storage/controller/collaborative-storage.controller.spec.ts index 875be40e91e..5573a026e4c 100644 --- a/apps/server/src/modules/collaborative-storage/controller/collaborative-storage.controller.spec.ts +++ b/apps/server/src/modules/collaborative-storage/controller/collaborative-storage.controller.spec.ts @@ -2,8 +2,8 @@ import { createMock } from '@golevelup/ts-jest'; import { CollaborativeStorageController } from '@modules/collaborative-storage/controller/collaborative-storage.controller'; import { CollaborativeStorageUc } from '@modules/collaborative-storage/uc/collaborative-storage.uc'; import { Test, TestingModule } from '@nestjs/testing'; -import { currentUserFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; describe('CollaborativeStorage Controller', () => { let module: TestingModule; diff --git a/apps/server/src/modules/collaborative-storage/mapper/team.mapper.spec.ts b/apps/server/src/modules/collaborative-storage/mapper/team.mapper.spec.ts index a2d9808f5a6..18bd9db3e25 100644 --- a/apps/server/src/modules/collaborative-storage/mapper/team.mapper.spec.ts +++ b/apps/server/src/modules/collaborative-storage/mapper/team.mapper.spec.ts @@ -1,7 +1,7 @@ -import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; -import { teamFactory } from '@shared/testing/factory/team.factory'; import { TeamMapper } from '@modules/collaborative-storage/mapper/team.mapper'; +import { Test, TestingModule } from '@nestjs/testing'; +import { teamFactory } from '@testing/factory/team.factory'; +import { setupEntities } from '@testing/setup-entities'; describe('TeamMapper', () => { let module: TestingModule; diff --git a/apps/server/src/modules/collaborative-storage/services/collaborative-storage.service.spec.ts b/apps/server/src/modules/collaborative-storage/services/collaborative-storage.service.spec.ts index e934d046730..5063f10f63e 100644 --- a/apps/server/src/modules/collaborative-storage/services/collaborative-storage.service.spec.ts +++ b/apps/server/src/modules/collaborative-storage/services/collaborative-storage.service.spec.ts @@ -11,9 +11,9 @@ import { Test, TestingModule } from '@nestjs/testing'; import { TeamEntity } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; import { TeamsRepo } from '@shared/repo'; -import { setupEntities } from '@shared/testing'; -import { teamFactory } from '@shared/testing/factory/team.factory'; import { LegacyLogger } from '@src/core/logger'; +import { teamFactory } from '@testing/factory/team.factory'; +import { setupEntities } from '@testing/setup-entities'; import { TeamDto } from './dto/team.dto'; describe('Collaborative Storage Service', () => { diff --git a/apps/server/src/modules/collaborative-text-editor/api/tests/delete-sessions.api.spec.ts b/apps/server/src/modules/collaborative-text-editor/api/tests/delete-sessions.api.spec.ts index b60a42c91a1..895d3f75a35 100644 --- a/apps/server/src/modules/collaborative-text-editor/api/tests/delete-sessions.api.spec.ts +++ b/apps/server/src/modules/collaborative-text-editor/api/tests/delete-sessions.api.spec.ts @@ -2,9 +2,11 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { EntityManager } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { cleanupCollections, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; import { EtherpadClientAdapter } from '@src/infra/etherpad-client'; import { ServerTestModule } from '@src/modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; describe('Collaborative Text Editor Controller (API)', () => { let app: INestApplication; diff --git a/apps/server/src/modules/collaborative-text-editor/api/tests/get-collaborative-text-editor.api.spec.ts b/apps/server/src/modules/collaborative-text-editor/api/tests/get-collaborative-text-editor.api.spec.ts index 999c0217d6e..cb29c7c06b2 100644 --- a/apps/server/src/modules/collaborative-text-editor/api/tests/get-collaborative-text-editor.api.spec.ts +++ b/apps/server/src/modules/collaborative-text-editor/api/tests/get-collaborative-text-editor.api.spec.ts @@ -3,7 +3,6 @@ import { Configuration } from '@hpi-schul-cloud/commons/lib'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { cleanupCollections, courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; import { EtherpadClientAdapter } from '@src/infra/etherpad-client'; import { BoardExternalReferenceType } from '@src/modules/board'; import { @@ -13,6 +12,10 @@ import { columnEntityFactory, } from '@src/modules/board/testing'; import { ServerTestModule } from '@src/modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; describe('Collaborative Text Editor Controller (API)', () => { let app: INestApplication; diff --git a/apps/server/src/modules/common-cartridge/controller/common-cartridge.controller.api.spec.ts b/apps/server/src/modules/common-cartridge/controller/common-cartridge.controller.api.spec.ts index bb2fa34132d..1f655323a38 100644 --- a/apps/server/src/modules/common-cartridge/controller/common-cartridge.controller.api.spec.ts +++ b/apps/server/src/modules/common-cartridge/controller/common-cartridge.controller.api.spec.ts @@ -4,8 +4,8 @@ import { ICurrentUser } from '@infra/auth-guard'; import { INestApplication } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { axiosResponseFactory } from '@shared/testing'; import { CoursesApi } from '@src/infra/courses-client/generated'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import supertest from 'supertest'; import { CommonCartridgeApiModule } from '../common-cartridge-api.module'; import { CommonCartridgeFileBuilder } from '../export/builders/common-cartridge-file-builder'; diff --git a/apps/server/src/modules/common-cartridge/testing/link-element.factory.ts b/apps/server/src/modules/common-cartridge/testing/link-element.factory.ts index 726e711d765..b692efbeaec 100644 --- a/apps/server/src/modules/common-cartridge/testing/link-element.factory.ts +++ b/apps/server/src/modules/common-cartridge/testing/link-element.factory.ts @@ -1,5 +1,5 @@ import { faker } from '@faker-js/faker'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { Factory } from 'fishery'; import { LinkElementContentDto } from '../common-cartridge-client/card-client/dto/link-element-content.dto'; import { LinkElementResponseDto } from '../common-cartridge-client/card-client/dto/link-element-response.dto'; diff --git a/apps/server/src/modules/common-cartridge/testing/rich-text-element.factory.ts b/apps/server/src/modules/common-cartridge/testing/rich-text-element.factory.ts index 01e880ae0de..e8c6b1041f0 100644 --- a/apps/server/src/modules/common-cartridge/testing/rich-text-element.factory.ts +++ b/apps/server/src/modules/common-cartridge/testing/rich-text-element.factory.ts @@ -1,8 +1,8 @@ -import { BaseFactory } from '@shared/testing'; import { faker } from '@faker-js/faker'; +import { BaseFactory } from '@testing/factory/base.factory'; import { Factory } from 'fishery'; -import { RichTextElementResponseDto } from '../common-cartridge-client/card-client/dto/rich-text-element-response.dto'; import { RichTextElementContentDto } from '../common-cartridge-client/card-client/dto/rich-text-element-content.dto'; +import { RichTextElementResponseDto } from '../common-cartridge-client/card-client/dto/rich-text-element-response.dto'; import { ContentElementType } from '../common-cartridge-client/card-client/enums/content-element-type.enum'; export const richTextElementContentFactory = Factory.define(() => { diff --git a/apps/server/src/modules/copy-helper/mapper/copy.mapper.spec.ts b/apps/server/src/modules/copy-helper/mapper/copy.mapper.spec.ts index bb82db63761..9871286e6b2 100644 --- a/apps/server/src/modules/copy-helper/mapper/copy.mapper.spec.ts +++ b/apps/server/src/modules/copy-helper/mapper/copy.mapper.spec.ts @@ -1,11 +1,11 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { CopyElementType, CopyStatusEnum } from '@modules/copy-helper'; import { LessonCopyApiParams } from '@modules/learnroom/controller/dto/lesson/lesson-copy.params'; import { LessonCopyParentParams } from '@modules/lesson'; import { TaskCopyApiParams } from '@modules/task/controller/dto/task-copy.params'; import { TaskCopyParentParams } from '@modules/task/types'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@testing/setup-entities'; import { CopyApiResponse } from '../dto/copy.response'; import { CopyMapper } from './copy.mapper'; diff --git a/apps/server/src/modules/copy-helper/service/copy-helper.service.spec.ts b/apps/server/src/modules/copy-helper/service/copy-helper.service.spec.ts index 27276237119..0115d9f65b7 100644 --- a/apps/server/src/modules/copy-helper/service/copy-helper.service.spec.ts +++ b/apps/server/src/modules/copy-helper/service/copy-helper.service.spec.ts @@ -1,5 +1,6 @@ import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, setupEntities } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CopyElementType, CopyStatus, CopyStatusEnum } from '../types/copy.types'; import { CopyHelperService } from './copy-helper.service'; diff --git a/apps/server/src/modules/deletion-console/deletion-client/deletion.client.spec.ts b/apps/server/src/modules/deletion-console/deletion-client/deletion.client.spec.ts index c63efcb4d9d..2a445e9bc4e 100644 --- a/apps/server/src/modules/deletion-console/deletion-client/deletion.client.spec.ts +++ b/apps/server/src/modules/deletion-console/deletion-client/deletion.client.spec.ts @@ -1,14 +1,14 @@ -import { of, throwError } from 'rxjs'; -import { AxiosResponse } from 'axios'; +import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { HttpService } from '@nestjs/axios'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { axiosResponseFactory } from '@shared/testing'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; +import { AxiosResponse } from 'axios'; +import { of, throwError } from 'rxjs'; import { DeletionRequestInputBuilder, DeletionRequestOutputBuilder } from '.'; -import { DeletionRequestOutput } from './interface'; -import { DeletionClient } from './deletion.client'; import { DeletionConsoleConfig } from '../deletion.config'; +import { DeletionClient } from './deletion.client'; +import { DeletionRequestOutput } from './interface'; describe(DeletionClient.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/deletion/api/controller/api-test/deletion-executions.api.spec.ts b/apps/server/src/modules/deletion/api/controller/api-test/deletion-executions.api.spec.ts index 7dbfa9a5f9d..4c2b6ca6beb 100644 --- a/apps/server/src/modules/deletion/api/controller/api-test/deletion-executions.api.spec.ts +++ b/apps/server/src/modules/deletion/api/controller/api-test/deletion-executions.api.spec.ts @@ -1,28 +1,19 @@ -import { XApiKeyGuard } from '@infra/auth-guard'; import { AdminApiServerTestModule } from '@modules/server/admin-api.server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient } from '@shared/testing'; +import { TestApiClient } from '@testing/test-api-client'; const baseRouteName = '/deletionExecutions'; describe(`deletionExecution (api)`, () => { let app: INestApplication; let testApiClient: TestApiClient; - const API_KEY = '7ccd4e11-c6f6-48b0-81eb-cccf7922e7a4'; + const API_KEY = 'someotherkey'; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [AdminApiServerTestModule], - }) - .overrideGuard(XApiKeyGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - return req.headers['x-api-key'] === API_KEY; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); @@ -37,6 +28,7 @@ describe(`deletionExecution (api)`, () => { describe('when execute deletionRequests with default limit', () => { it('should return status 204', async () => { const response = await testApiClient.post(''); + expect(response.status).toEqual(204); }, 20000); }); @@ -44,13 +36,18 @@ describe(`deletionExecution (api)`, () => { describe('without token', () => { it('should refuse with wrong token', async () => { const client = new TestApiClient(app, baseRouteName, 'thisisaninvalidapikey', true); + const response = await client.post(''); - expect(response.status).toEqual(403); + + expect(response.status).toEqual(401); }); + it('should refuse without token', async () => { const client = new TestApiClient(app, baseRouteName, '', true); + const response = await client.post(''); - expect(response.status).toEqual(403); + + expect(response.status).toEqual(401); }); }); }); diff --git a/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-create.api.spec.ts b/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-create.api.spec.ts index bf045d7f868..47aa8bbae30 100644 --- a/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-create.api.spec.ts +++ b/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-create.api.spec.ts @@ -1,10 +1,8 @@ -import { XApiKeyGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { AdminApiServerTestModule } from '@modules/server/admin-api.server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient } from '@shared/testing'; -import { Request } from 'express'; +import { TestApiClient } from '@testing/test-api-client'; import { DomainName } from '../../../domain/types'; import { DeletionRequestEntity } from '../../../repo/entity'; import { DeletionRequestBodyProps, DeletionRequestResponse } from '../dto'; @@ -55,21 +53,12 @@ describe(`deletionRequest create (api)`, () => { let app: INestApplication; let em: EntityManager; let testApiClient: TestApiClient; - const API_KEY = '7ccd4e11-c6f6-48b0-81eb-cccf7922e7a4'; + const API_KEY = 'someotherkey'; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [AdminApiServerTestModule], - }) - .overrideGuard(XApiKeyGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.headers['X-API-KEY'] = API_KEY; - return true; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); diff --git a/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-delete.api.spec.ts b/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-delete.api.spec.ts index bb7665eabd2..501e86f7b0b 100644 --- a/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-delete.api.spec.ts +++ b/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-delete.api.spec.ts @@ -1,10 +1,9 @@ -import { XApiKeyGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { AdminApiServerTestModule } from '@modules/server/admin-api.server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, cleanupCollections } from '@shared/testing'; -import { Request } from 'express'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { TestApiClient } from '@testing/test-api-client'; import { DeletionRequestEntity } from '../../../repo/entity'; import { deletionRequestEntityFactory } from '../../../repo/entity/testing'; @@ -14,21 +13,12 @@ describe(`deletionRequest delete (api)`, () => { let app: INestApplication; let em: EntityManager; let testApiClient: TestApiClient; - const API_KEY = '7ccd4e11-c6f6-48b0-81eb-cccf7922e7a4'; + const API_KEY = 'someotherkey'; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [AdminApiServerTestModule], - }) - .overrideGuard(XApiKeyGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.headers['X-API-KEY'] = API_KEY; - return true; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); diff --git a/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-find.api.spec.ts b/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-find.api.spec.ts index 298021a2a07..1e6d6a7900f 100644 --- a/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-find.api.spec.ts +++ b/apps/server/src/modules/deletion/api/controller/api-test/deletion-request-find.api.spec.ts @@ -1,10 +1,9 @@ -import { XApiKeyGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { AdminApiServerTestModule } from '@modules/server/admin-api.server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, cleanupCollections } from '@shared/testing'; -import { Request } from 'express'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { TestApiClient } from '@testing/test-api-client'; import { deletionRequestEntityFactory } from '../../../repo/entity/testing'; import { DeletionRequestLogResponse } from '../dto'; @@ -14,21 +13,12 @@ describe(`deletionRequest find (api)`, () => { let app: INestApplication; let em: EntityManager; let testApiClient: TestApiClient; - const API_KEY = '7ccd4e11-c6f6-48b0-81eb-cccf7922e7a4'; + const API_KEY = 'someotherkey'; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [AdminApiServerTestModule], - }) - .overrideGuard(XApiKeyGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.headers['X-API-KEY'] = API_KEY; - return true; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); @@ -51,6 +41,7 @@ describe(`deletionRequest find (api)`, () => { return { deletionRequest }; }; + it('should return status 202', async () => { const { deletionRequest } = await setup(); diff --git a/apps/server/src/modules/deletion/api/uc/deletion-request.uc.spec.ts b/apps/server/src/modules/deletion/api/uc/deletion-request.uc.spec.ts index 90fb8ee2b64..c3162b1fc22 100644 --- a/apps/server/src/modules/deletion/api/uc/deletion-request.uc.spec.ts +++ b/apps/server/src/modules/deletion/api/uc/deletion-request.uc.spec.ts @@ -3,9 +3,9 @@ import { MikroORM } from '@mikro-orm/core'; import { ConfigModule } from '@nestjs/config'; import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { createConfigModuleOptions } from '@src/config'; import { LegacyLogger } from '@src/core/logger'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { DomainDeletionReportBuilder, DomainOperationReportBuilder } from '../../domain/builder'; import { UserDeletedEvent } from '../../domain/event'; diff --git a/apps/server/src/modules/deletion/domain/service/deletion-log.service.spec.ts b/apps/server/src/modules/deletion/domain/service/deletion-log.service.spec.ts index 695012e295f..1924d610243 100644 --- a/apps/server/src/modules/deletion/domain/service/deletion-log.service.spec.ts +++ b/apps/server/src/modules/deletion/domain/service/deletion-log.service.spec.ts @@ -1,9 +1,9 @@ -import { Test, TestingModule } from '@nestjs/testing'; import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { setupEntities } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@testing/setup-entities'; import { DeletionLogRepo } from '../../repo'; -import { DomainOperationReportBuilder, DomainDeletionReportBuilder } from '../builder'; +import { DomainDeletionReportBuilder, DomainOperationReportBuilder } from '../builder'; import { deletionLogFactory } from '../testing'; import { DomainName, OperationType } from '../types'; import { DeletionLogService } from './deletion-log.service'; diff --git a/apps/server/src/modules/deletion/domain/service/deletion-request.service.spec.ts b/apps/server/src/modules/deletion/domain/service/deletion-request.service.spec.ts index 1e4b59d2bc9..03be40c8581 100644 --- a/apps/server/src/modules/deletion/domain/service/deletion-request.service.spec.ts +++ b/apps/server/src/modules/deletion/domain/service/deletion-request.service.spec.ts @@ -1,9 +1,9 @@ -import { Test, TestingModule } from '@nestjs/testing'; import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { setupEntities } from '@shared/testing'; -import { ObjectId } from 'bson'; import { ConfigModule } from '@nestjs/config'; +import { Test, TestingModule } from '@nestjs/testing'; import { createConfigModuleOptions } from '@src/config'; +import { setupEntities } from '@testing/setup-entities'; +import { ObjectId } from 'bson'; import { DeletionRequestRepo } from '../../repo'; import { deletionRequestFactory, deletionTestConfig } from '../testing'; import { DomainName, StatusModel } from '../types'; diff --git a/apps/server/src/modules/deletion/domain/testing/factory/deletion-log.factory.ts b/apps/server/src/modules/deletion/domain/testing/factory/deletion-log.factory.ts index 802f8189714..34a2da0923d 100644 --- a/apps/server/src/modules/deletion/domain/testing/factory/deletion-log.factory.ts +++ b/apps/server/src/modules/deletion/domain/testing/factory/deletion-log.factory.ts @@ -1,6 +1,6 @@ -import { DoBaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; -import { DomainOperationReportBuilder, DomainDeletionReportBuilder } from '../../builder'; +import { DoBaseFactory } from '@testing/factory/domainobject'; +import { DomainDeletionReportBuilder, DomainOperationReportBuilder } from '../../builder'; import { DeletionLog, DeletionLogProps } from '../../do'; import { DomainName, OperationType } from '../../types'; diff --git a/apps/server/src/modules/deletion/domain/testing/factory/deletion-request.factory.ts b/apps/server/src/modules/deletion/domain/testing/factory/deletion-request.factory.ts index d10fbd9defd..dd5e653a868 100644 --- a/apps/server/src/modules/deletion/domain/testing/factory/deletion-request.factory.ts +++ b/apps/server/src/modules/deletion/domain/testing/factory/deletion-request.factory.ts @@ -1,5 +1,5 @@ -import { DoBaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { DoBaseFactory } from '@testing/factory/domainobject'; import { DeepPartial } from 'fishery'; import { DeletionRequest, DeletionRequestProps } from '../../do'; import { DomainName, StatusModel } from '../../types'; diff --git a/apps/server/src/modules/deletion/repo/deletion-log.repo.spec.ts b/apps/server/src/modules/deletion/repo/deletion-log.repo.spec.ts index 38039f50d6f..caafc5b4bb4 100644 --- a/apps/server/src/modules/deletion/repo/deletion-log.repo.spec.ts +++ b/apps/server/src/modules/deletion/repo/deletion-log.repo.spec.ts @@ -1,8 +1,8 @@ +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test } from '@nestjs/testing'; import { TestingModule } from '@nestjs/testing/testing-module'; -import { MongoMemoryDatabaseModule } from '@infra/database'; -import { cleanupCollections } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { DeletionLog } from '../domain/do'; import { deletionLogFactory } from '../domain/testing'; import { DeletionLogRepo } from './deletion-log.repo'; diff --git a/apps/server/src/modules/deletion/repo/deletion-request.repo.spec.ts b/apps/server/src/modules/deletion/repo/deletion-request.repo.spec.ts index 5ffbd1b9658..aa6b7755532 100644 --- a/apps/server/src/modules/deletion/repo/deletion-request.repo.spec.ts +++ b/apps/server/src/modules/deletion/repo/deletion-request.repo.spec.ts @@ -1,9 +1,9 @@ +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; -import { ObjectId } from 'bson'; import { Test } from '@nestjs/testing'; import { TestingModule } from '@nestjs/testing/testing-module'; -import { MongoMemoryDatabaseModule } from '@infra/database'; -import { cleanupCollections } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { ObjectId } from 'bson'; import { DeletionRequest } from '../domain/do'; import { deletionRequestFactory } from '../domain/testing'; import { StatusModel } from '../domain/types'; diff --git a/apps/server/src/modules/deletion/repo/entity/deletion-log.entity.spec.ts b/apps/server/src/modules/deletion/repo/entity/deletion-log.entity.spec.ts index 26aec1fd133..5e8e1dbd873 100644 --- a/apps/server/src/modules/deletion/repo/entity/deletion-log.entity.spec.ts +++ b/apps/server/src/modules/deletion/repo/entity/deletion-log.entity.spec.ts @@ -1,6 +1,6 @@ -import { setupEntities } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; -import { DomainOperationReport, DomainDeletionReport } from '../../domain/interface'; +import { setupEntities } from '@testing/setup-entities'; +import { DomainDeletionReport, DomainOperationReport } from '../../domain/interface'; import { DomainName, OperationType } from '../../domain/types'; import { DeletionLogEntity } from './deletion-log.entity'; diff --git a/apps/server/src/modules/deletion/repo/entity/deletion-request.entity.spec.ts b/apps/server/src/modules/deletion/repo/entity/deletion-request.entity.spec.ts index c939de71304..74d4eb036cf 100644 --- a/apps/server/src/modules/deletion/repo/entity/deletion-request.entity.spec.ts +++ b/apps/server/src/modules/deletion/repo/entity/deletion-request.entity.spec.ts @@ -1,5 +1,5 @@ -import { setupEntities } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { setupEntities } from '@testing/setup-entities'; import { DomainName, StatusModel } from '../../domain/types'; import { DeletionRequestEntity } from './deletion-request.entity'; diff --git a/apps/server/src/modules/deletion/repo/entity/testing/factory/deletion-log.entity.factory.ts b/apps/server/src/modules/deletion/repo/entity/testing/factory/deletion-log.entity.factory.ts index faf0ade5bf8..02bdaf1e678 100644 --- a/apps/server/src/modules/deletion/repo/entity/testing/factory/deletion-log.entity.factory.ts +++ b/apps/server/src/modules/deletion/repo/entity/testing/factory/deletion-log.entity.factory.ts @@ -1,6 +1,6 @@ -import { BaseFactory } from '@shared/testing'; -import { DomainOperationReportBuilder, DomainDeletionReportBuilder } from '@src/modules/deletion/domain/builder'; +import { DomainDeletionReportBuilder, DomainOperationReportBuilder } from '@src/modules/deletion/domain/builder'; import { DomainName, OperationType } from '@src/modules/deletion/domain/types'; +import { BaseFactory } from '@testing/factory/base.factory'; import { ObjectId } from 'bson'; import { DeletionLogEntity, DeletionLogEntityProps } from '../../deletion-log.entity'; diff --git a/apps/server/src/modules/deletion/repo/entity/testing/factory/deletion-request.entity.factory.ts b/apps/server/src/modules/deletion/repo/entity/testing/factory/deletion-request.entity.factory.ts index 4629a3fbdb8..da60d815462 100644 --- a/apps/server/src/modules/deletion/repo/entity/testing/factory/deletion-request.entity.factory.ts +++ b/apps/server/src/modules/deletion/repo/entity/testing/factory/deletion-request.entity.factory.ts @@ -1,5 +1,5 @@ -import { BaseFactory } from '@shared/testing'; import { DomainName, StatusModel } from '@src/modules/deletion/domain/types'; +import { BaseFactory } from '@testing/factory/base.factory'; import { ObjectId } from 'bson'; import { DeletionRequestEntity, DeletionRequestEntityProps } from '../../deletion-request.entity'; diff --git a/apps/server/src/modules/files-storage-client/mapper/copy-files-of-parent-param.builder.spec.ts b/apps/server/src/modules/files-storage-client/mapper/copy-files-of-parent-param.builder.spec.ts index 3f0df0394b1..3b24b5a33dd 100644 --- a/apps/server/src/modules/files-storage-client/mapper/copy-files-of-parent-param.builder.spec.ts +++ b/apps/server/src/modules/files-storage-client/mapper/copy-files-of-parent-param.builder.spec.ts @@ -1,7 +1,9 @@ import { FileRecordParentType } from '@infra/rabbitmq'; import { ObjectId } from '@mikro-orm/mongodb'; import { StorageLocation } from '@modules/files-storage/interface'; -import { lessonFactory, setupEntities, taskFactory } from '@shared/testing'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CopyFilesOfParentParamBuilder } from './copy-files-of-parent-param.builder'; import { FileParamBuilder } from './files-storage-param.builder'; diff --git a/apps/server/src/modules/files-storage-client/mapper/files-storage-param.builder.spec.ts b/apps/server/src/modules/files-storage-client/mapper/files-storage-param.builder.spec.ts index 5ae33d5f22a..fcee02bc74b 100644 --- a/apps/server/src/modules/files-storage-client/mapper/files-storage-param.builder.spec.ts +++ b/apps/server/src/modules/files-storage-client/mapper/files-storage-param.builder.spec.ts @@ -1,6 +1,8 @@ import { FileRecordParentType } from '@infra/rabbitmq'; import { StorageLocation } from '@modules/files-storage/interface'; -import { lessonFactory, setupEntities, taskFactory } from '@shared/testing'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileParamBuilder } from './files-storage-param.builder'; describe('FileParamBuilder', () => { diff --git a/apps/server/src/modules/files-storage-client/service/copy-files.service.spec.ts b/apps/server/src/modules/files-storage-client/service/copy-files.service.spec.ts index 99eb7ddf3f2..a0f4dd88e5c 100644 --- a/apps/server/src/modules/files-storage-client/service/copy-files.service.spec.ts +++ b/apps/server/src/modules/files-storage-client/service/copy-files.service.spec.ts @@ -2,13 +2,11 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { CopyElementType, CopyHelperService } from '@modules/copy-helper'; import { Test, TestingModule } from '@nestjs/testing'; import { ComponentProperties, ComponentType } from '@shared/domain/entity'; -import { - courseFactory, - legacyFileEntityMockFactory, - lessonFactory, - schoolEntityFactory, - setupEntities, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { legacyFileEntityMockFactory } from '@testing/factory/legacy-file-entity-mock.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CopyFilesService } from './copy-files.service'; import { FilesStorageClientAdapterService } from './files-storage-client.service'; diff --git a/apps/server/src/modules/files-storage-client/service/files-storage-client.service.spec.ts b/apps/server/src/modules/files-storage-client/service/files-storage-client.service.spec.ts index 1b36f9cd62f..cbe5764240f 100644 --- a/apps/server/src/modules/files-storage-client/service/files-storage-client.service.spec.ts +++ b/apps/server/src/modules/files-storage-client/service/files-storage-client.service.spec.ts @@ -13,8 +13,10 @@ import { deletionRequestFactory } from '@modules/deletion/domain/testing'; import { StorageLocation } from '@modules/files-storage/interface'; import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; -import { schoolEntityFactory, setupEntities, taskFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileParamBuilder, FilesStorageClientMapper } from '../mapper'; import { CopyFilesOfParentParamBuilder } from '../mapper/copy-files-of-parent-param.builder'; import { FilesStorageClientAdapterService } from './files-storage-client.service'; diff --git a/apps/server/src/modules/files-storage-client/service/files-storage.producer.spec.ts b/apps/server/src/modules/files-storage-client/service/files-storage.producer.spec.ts index b5c9371ccb6..a9df04db683 100644 --- a/apps/server/src/modules/files-storage-client/service/files-storage.producer.spec.ts +++ b/apps/server/src/modules/files-storage-client/service/files-storage.producer.spec.ts @@ -5,8 +5,8 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { StorageLocation } from '@modules/files-storage/interface'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { setupEntities } from '@testing/setup-entities'; import { FilesStorageProducer } from './files-storage.producer'; describe('FilesStorageProducer', () => { diff --git a/apps/server/src/modules/files-storage/controller/api-test/files-security.api.spec.ts b/apps/server/src/modules/files-storage/controller/api-test/files-security.api.spec.ts index aa8f543cc1c..f4c1519ef23 100644 --- a/apps/server/src/modules/files-storage/controller/api-test/files-security.api.spec.ts +++ b/apps/server/src/modules/files-storage/controller/api-test/files-security.api.spec.ts @@ -1,18 +1,13 @@ import { createMock } from '@golevelup/ts-jest'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; -import { - cleanupCollections, - fileRecordFactory, - mapUserToCurrentUser, - schoolEntityFactory, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; import NodeClam from 'clamscan'; -import { Request } from 'express'; import request from 'supertest'; import { FileRecord } from '../../entity'; import { FilesStorageTestModule } from '../../files-storage-test.module'; @@ -46,7 +41,6 @@ class API { describe(`${baseRouteName} (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; let api: API; let validId: string; @@ -54,14 +48,7 @@ describe(`${baseRouteName} (api)`, () => { const module: TestingModule = await Test.createTestingModule({ imports: [FilesStorageTestModule], }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) + .overrideProvider(NodeClam) .useValue(createMock()) .compile(); @@ -84,7 +71,6 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); validId = user.school.id; }); diff --git a/apps/server/src/modules/files-storage/controller/api-test/files-storage-copy-files.api.spec.ts b/apps/server/src/modules/files-storage/controller/api-test/files-storage-copy-files.api.spec.ts index 4e474e32abb..7ad19cd6359 100644 --- a/apps/server/src/modules/files-storage/controller/api-test/files-storage-copy-files.api.spec.ts +++ b/apps/server/src/modules/files-storage/controller/api-test/files-storage-copy-files.api.spec.ts @@ -1,32 +1,27 @@ import { createMock } from '@golevelup/ts-jest'; import { AntivirusService } from '@infra/antivirus'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { AuthorizationClientAdapter } from '@infra/authorization-client'; import { S3ClientAdapter } from '@infra/s3-client'; import { EntityManager } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; -import { EntityId } from '@shared/domain/types'; -import { - cleanupCollections, - courseFactory, - fileRecordFactory, - mapUserToCurrentUser, - schoolEntityFactory, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { JwtAuthenticationFactory } from '@testing/factory/jwt-authentication.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import NodeClam from 'clamscan'; -import { Request } from 'express'; import FileType from 'file-type-cjs/file-type-cjs-index'; -import request from 'supertest'; import { FilesStorageTestModule } from '../../files-storage-test.module'; import { FILES_STORAGE_S3_CONNECTION } from '../../files-storage.config'; import { FileRecordParentType, StorageLocation } from '../../interface'; -import { CopyFileParams, CopyFilesOfParentParams, FileRecordListResponse, FileRecordResponse } from '../dto'; +import { FileRecordListResponse, FileRecordResponse } from '../dto'; import { availableParentTypes } from './mocks'; -const baseRouteName = '/file/copy'; +const baseRouteName = '/file'; jest.mock('file-type-cjs/file-type-cjs-index', () => { return { @@ -34,58 +29,9 @@ jest.mock('file-type-cjs/file-type-cjs-index', () => { }; }); -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async postUploadFile(routeName: string, fileName: string) { - const response = await request(this.app.getHttpServer()) - .post(routeName) - .attach('file', Buffer.from('abcd'), fileName) - .set('connection', 'keep-alive') - .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async copyFile(requestString: string, body: CopyFileParams) { - const response = await request(this.app.getHttpServer()) - .post(`${baseRouteName}${requestString}`) - .send(body || {}); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async copy(requestString: string, body: CopyFilesOfParentParams) { - const response = await request(this.app.getHttpServer()) - .post(`${baseRouteName}${requestString}`) - .set('Accept', 'application/json') - .send(body || {}); - - return { - result: response.body as FileRecordListResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} - describe(`${baseRouteName} (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -95,14 +41,6 @@ describe(`${baseRouteName} (api)`, () => { .useValue(createMock()) .overrideProvider(FILES_STORAGE_S3_CONNECTION) .useValue(createMock()) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .overrideProvider(NodeClam) .useValue(createMock()) .overrideProvider(AuthorizationClientAdapter) @@ -112,7 +50,6 @@ describe(`${baseRouteName} (api)`, () => { app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); - api = new API(app); }); afterAll(async () => { @@ -120,12 +57,33 @@ describe(`${baseRouteName} (api)`, () => { }); describe('copy files of parent', () => { - let validId: string; - let targetParentId: EntityId; - let copyFilesParams: CopyFilesOfParentParams; + describe('with not authenticated user', () => { + const setup = () => { + const copyFilesParams = { + target: { + storageLocation: StorageLocation.SCHOOL, + storageLocationId: '123', + parentId: '123', + parentType: FileRecordParentType.Course, + }, + }; + + const apiClient = new TestApiClient(app, baseRouteName); + + return { apiClient, copyFilesParams }; + }; + + it('should return status 401', async () => { + const { apiClient, copyFilesParams } = setup(); + + const result = await apiClient.post(`/copy/school/123/users/123`, copyFilesParams); + + expect(result.status).toEqual(401); + }); + }); describe('with bad request data', () => { - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -134,11 +92,10 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, school, targetParent, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); - validId = user.school.id; - targetParentId = targetParent.id; + const validId = user.school.id; + const targetParentId = targetParent.id; - copyFilesParams = { + const copyFilesParams = { target: { storageLocation: StorageLocation.SCHOOL, storageLocationId: validId, @@ -146,43 +103,68 @@ describe(`${baseRouteName} (api)`, () => { parentType: FileRecordParentType.Course, }, }; - }); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + return { apiClient, validId, copyFilesParams }; + }; it('should return status 400 for invalid schoolId', async () => { - const response = await api.copy(`/school/123/users/${validId}`, copyFilesParams); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId, copyFilesParams } = await setup(); + + const result = await apiClient.post(`/copy/school/123/users/${validId}`, copyFilesParams); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['storageLocationId must be a mongodb id'], field: ['storageLocationId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for invalid parentId', async () => { - const response = await api.copy(`/school/${validId}/users/123`, copyFilesParams); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId, copyFilesParams } = await setup(); + + const result = await apiClient.post(`/copy/school/${validId}/users/123`, copyFilesParams); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['parentId must be a mongodb id'], field: ['parentId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for invalid parentType', async () => { - const response = await api.copy(`/school/${validId}/cookies/${validId}`, copyFilesParams); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId, copyFilesParams } = await setup(); + + const result = await apiClient.post(`/copy/school/${validId}/cookies/${validId}`, copyFilesParams); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: [`parentType must be one of the following values: ${availableParentTypes}`], field: ['parentType'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for invalid parentType', async () => { - copyFilesParams = { + const { apiClient, validId } = await setup(); + const params = { target: { storageLocation: StorageLocation.SCHOOL, storageLocationId: 'invalidObjectId', @@ -190,13 +172,15 @@ describe(`${baseRouteName} (api)`, () => { parentType: FileRecordParentType.Task, }, }; - const response = await api.copy(`/school/${validId}/users/${validId}`, copyFilesParams); + + const response = await apiClient.post(`/copy/school/${validId}/users/${validId}`, params); + expect(response.status).toEqual(400); }); }); describe(`with valid request data`, () => { - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -205,11 +189,10 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, school, targetParent, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); - validId = user.school.id; - targetParentId = targetParent.id; + const validId = user.school.id; + const targetParentId = targetParent.id; - copyFilesParams = { + const copyFilesParams = { target: { storageLocation: StorageLocation.SCHOOL, storageLocationId: validId, @@ -218,24 +201,36 @@ describe(`${baseRouteName} (api)`, () => { }, }; - jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); - }); - - it('should return status 200 for successful request', async () => { - await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test1.txt'); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); - const response = await api.copy(`/school/${validId}/schools/${validId}`, copyFilesParams); + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); - expect(response.status).toEqual(201); - }); + return { validId, copyFilesParams, apiClient }; + }; it('should return right type of data', async () => { - await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test1.txt'); - const { result } = await api.copy(`/school/${validId}/schools/${validId}`, copyFilesParams); - - expect(Array.isArray(result.data)).toBe(true); - expect(result.data[0]).toBeDefined(); - expect(result.data[0]).toStrictEqual({ + const { validId, copyFilesParams, apiClient } = await setup(); + + await apiClient + .post(`/upload/school/${validId}/schools/${validId}`) + .attach('file', Buffer.from('abcd'), 'test1.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + const result = await apiClient.post(`/copy/school/${validId}/schools/${validId}`, copyFilesParams); + const response = result.body as FileRecordListResponse; + + expect(result.status).toEqual(201); + expect(Array.isArray(response.data)).toBe(true); + expect(response.data[0]).toBeDefined(); + expect(response.data[0]).toStrictEqual({ id: expect.any(String), name: expect.any(String), sourceId: expect.any(String), @@ -245,11 +240,34 @@ describe(`${baseRouteName} (api)`, () => { }); describe('copy single file', () => { - let copyFileParams: CopyFileParams; - let validId: string; - let targetParentId: EntityId; + describe('with not authenticated user', () => { + const setup = () => { + const copyFileParams = { + target: { + storageLocation: StorageLocation.SCHOOL, + storageLocationId: '123', + parentId: '123', + parentType: FileRecordParentType.Course, + }, + fileNamePrefix: 'copy from', + }; + + const apiClient = new TestApiClient(app, baseRouteName); + + return { copyFileParams, apiClient }; + }; + + it('should return status 401', async () => { + const { apiClient, copyFileParams } = setup(); + + const response = await apiClient.post(`/copy/123`, copyFileParams); + + expect(response.status).toEqual(401); + }); + }); + describe('with bad request data', () => { - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -258,11 +276,10 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, school, targetParent, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); - targetParentId = targetParent.id; + const targetParentId = targetParent.id; - validId = user.school.id; - copyFileParams = { + const validId = user.school.id; + const copyFileParams = { target: { storageLocation: StorageLocation.SCHOOL, storageLocationId: validId, @@ -271,11 +288,27 @@ describe(`${baseRouteName} (api)`, () => { }, fileNamePrefix: 'copy from', }; - }); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + return { validId, copyFileParams, apiClient }; + }; it('should return status 400 for invalid fileRecordId', async () => { - const response = await api.copyFile(`/123`, copyFileParams); - expect(response.error.validationErrors).toEqual([ + const { apiClient, copyFileParams } = await setup(); + + const response = await apiClient.post(`/copy/123`, copyFileParams); + const { validationErrors } = response.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['fileRecordId must be a mongodb id'], field: ['fileRecordId'], @@ -286,9 +319,7 @@ describe(`${baseRouteName} (api)`, () => { }); describe(`with valid request data`, () => { - let fileRecordId: string; - - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -297,11 +328,10 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, school, targetParent, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); - targetParentId = targetParent.id; + const targetParentId = targetParent.id; - validId = user.school.id; - copyFileParams = { + const validId = user.school.id; + const copyFileParams = { target: { storageLocation: StorageLocation.SCHOOL, storageLocationId: validId, @@ -311,24 +341,43 @@ describe(`${baseRouteName} (api)`, () => { fileNamePrefix: 'copy from', }; - const { result } = await api.postUploadFile( - `/file/upload/school/${school.id}/schools/${school.id}`, - 'test1.txt' - ); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + const result = await apiClient + .post(`/upload/school/${school.id}/schools/${school.id}`) + .attach('file', Buffer.from('abcd'), 'test1.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + const response = result.body as FileRecordResponse; - fileRecordId = result.id; - }); + const fileRecordId = response.id; + + return { validId, copyFileParams, apiClient, fileRecordId }; + }; it('should return status 200 for successful request', async () => { - const response = await api.copyFile(`/${fileRecordId}`, copyFileParams); + const { fileRecordId, copyFileParams, apiClient } = await setup(); + + const response = await apiClient.post(`/copy/${fileRecordId}`, copyFileParams); expect(response.status).toEqual(201); }); it('should return right type of data', async () => { - const { result } = await api.copyFile(`/${fileRecordId}`, copyFileParams); + const { fileRecordId, copyFileParams, apiClient } = await setup(); - expect(result).toStrictEqual({ + const result = await apiClient.post(`/copy/${fileRecordId}`, copyFileParams); + const response = result.body as FileRecordResponse; + + expect(response).toStrictEqual({ id: expect.any(String), name: expect.any(String), sourceId: expect.any(String), @@ -336,15 +385,18 @@ describe(`${baseRouteName} (api)`, () => { }); it('should return elements not equal of requested scope', async () => { + const { fileRecordId, copyFileParams, apiClient } = await setup(); + const otherFileRecords = fileRecordFactory.buildList(3, { parentType: FileRecordParentType.School, }); await em.persistAndFlush(otherFileRecords); em.clear(); - const { result } = await api.copyFile(`/${fileRecordId}`, copyFileParams); + const result = await apiClient.post(`/copy/${fileRecordId}`, copyFileParams); + const response = result.body as FileRecordResponse; - expect(result.id).not.toEqual(fileRecordId); + expect(response.id).not.toEqual(fileRecordId); }); }); }); diff --git a/apps/server/src/modules/files-storage/controller/api-test/files-storage-delete-files.api.spec.ts b/apps/server/src/modules/files-storage/controller/api-test/files-storage-delete-files.api.spec.ts index 6f2faca6123..0478e763303 100644 --- a/apps/server/src/modules/files-storage/controller/api-test/files-storage-delete-files.api.spec.ts +++ b/apps/server/src/modules/files-storage/controller/api-test/files-storage-delete-files.api.spec.ts @@ -2,24 +2,20 @@ import { createMock } from '@golevelup/ts-jest'; import { AntivirusService } from '@infra/antivirus'; import { S3ClientAdapter } from '@infra/s3-client'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { ApiValidationError } from '@shared/common'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { AuthorizationClientAdapter } from '@infra/authorization-client'; +import { ApiValidationError } from '@shared/common'; import { EntityId } from '@shared/domain/types'; -import { - cleanupCollections, - fileRecordFactory, - mapUserToCurrentUser, - schoolEntityFactory, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { JwtAuthenticationFactory } from '@testing/factory/jwt-authentication.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import NodeClam from 'clamscan'; -import { Request } from 'express'; import FileType from 'file-type-cjs/file-type-cjs-index'; -import request from 'supertest'; import { PreviewStatus } from '../../entity'; import { FilesStorageTestModule } from '../../files-storage-test.module'; import { FILES_STORAGE_S3_CONNECTION } from '../../files-storage.config'; @@ -27,7 +23,7 @@ import { FileRecordParentType } from '../../interface'; import { FileRecordListResponse, FileRecordResponse } from '../dto'; import { availableParentTypes } from './mocks'; -const baseRouteName = '/file/delete'; +const baseRouteName = '/file'; jest.mock('file-type-cjs/file-type-cjs-index', () => { return { @@ -35,58 +31,9 @@ jest.mock('file-type-cjs/file-type-cjs-index', () => { }; }); -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async postUploadFile(routeName: string, fileName: string) { - const response = await request(this.app.getHttpServer()) - .post(routeName) - .attach('file', Buffer.from('abcd'), fileName) - .set('connection', 'keep-alive') - .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async deleteFile(requestString: string) { - const response = await request(this.app.getHttpServer()) - .delete(`${baseRouteName}${requestString}`) - .set('Accept', 'application/json'); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async delete(requestString: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .delete(`${baseRouteName}${requestString}`) - .set('Accept', 'application/json') - .query(query || {}); - - return { - result: response.body as FileRecordListResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} - describe(`${baseRouteName} (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -96,14 +43,6 @@ describe(`${baseRouteName} (api)`, () => { .useValue(createMock()) .overrideProvider(FILES_STORAGE_S3_CONNECTION) .useValue(createMock()) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .overrideProvider(NodeClam) .useValue(createMock()) .overrideProvider(AuthorizationClientAdapter) @@ -113,7 +52,6 @@ describe(`${baseRouteName} (api)`, () => { app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); - api = new API(app); }); afterAll(async () => { @@ -121,10 +59,18 @@ describe(`${baseRouteName} (api)`, () => { }); describe('delete files of parent', () => { - describe('with bad request data', () => { - let validId: string; + describe('with not authenticated user', () => { + it('should return status 401', async () => { + const apiClient = new TestApiClient(app, baseRouteName); + + const result = await apiClient.delete(`/delete/school/123/users/123`); + + expect(result.status).toEqual(401); + }); + }); - beforeEach(async () => { + describe('with bad request data', () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -132,48 +78,79 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); - validId = user.school.id; - }); + const validId = user.school.id; + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + return { apiClient, validId }; + }; it('should return status 400 for invalid schoolId', async () => { - const response = await api.delete(`/school/123/users/${validId}`); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId } = await setup(); + + const result = await apiClient.delete(`/delete/school/123/users/${validId}`); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['storageLocationId must be a mongodb id'], field: ['storageLocationId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for invalid parentId', async () => { - const response = await api.delete(`/school/${validId}/users/123`); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId } = await setup(); + + const result = await apiClient.delete(`/delete/school/${validId}/users/123`); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['parentId must be a mongodb id'], field: ['parentId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for invalid parentType', async () => { - const response = await api.delete(`/school/${validId}/cookies/${validId}`); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId } = await setup(); + + const result = await apiClient.delete(`/delete/school/${validId}/cookies/${validId}`); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: [`parentType must be one of the following values: ${availableParentTypes}`], field: ['parentType'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); }); describe(`with valid request data`, () => { - let validId: string; + const uploadFile = async (apiClient: TestApiClient, schoolId: string, parentId: string, fileName: string) => { + const response = await apiClient + .post(`/upload/school/${schoolId}/schools/${parentId}`) + .attach('file', Buffer.from('abcd'), fileName) + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + + return response.body as FileRecordResponse; + }; - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -181,28 +158,35 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); - validId = user.school.id; + const validId = user.school.id; jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); - }); - it('should return status 200 for successful request', async () => { - await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test1.txt'); - - const response = await api.delete(`/school/${validId}/schools/${validId}`); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); - expect(response.status).toEqual(200); - }); + return { apiClient, validId }; + }; it('should return right type of data', async () => { - await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test1.txt'); + const { apiClient, validId } = await setup(); + + await uploadFile(apiClient, validId, validId, 'test1.txt'); - const { result } = await api.delete(`/school/${validId}/schools/${validId}`); + const result = await apiClient.delete(`/delete/school/${validId}/schools/${validId}`); + const response = result.body as FileRecordListResponse; - expect(Array.isArray(result.data)).toBe(true); - expect(result.data[0]).toBeDefined(); - expect(result.data[0]).toStrictEqual({ + expect(result.status).toEqual(200); + expect(Array.isArray(response.data)).toBe(true); + expect(response.data[0]).toBeDefined(); + expect(response.data[0]).toStrictEqual({ creatorId: expect.any(String), id: expect.any(String), name: expect.any(String), @@ -220,43 +204,69 @@ describe(`${baseRouteName} (api)`, () => { }); it('should return elements of requested scope', async () => { + const { apiClient, validId } = await setup(); const otherParentId = new ObjectId().toHexString(); - const uploadResponse = await Promise.all([ - api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test1.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test2.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test3.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${otherParentId}`, 'other1.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${otherParentId}`, 'other2.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${otherParentId}`, 'other3.txt'), + const fileRecords = await Promise.all([ + await uploadFile(apiClient, validId, validId, 'test1.txt'), + await uploadFile(apiClient, validId, validId, 'test2.txt'), + await uploadFile(apiClient, validId, validId, 'test3.txt'), + await uploadFile(apiClient, validId, otherParentId, 'other1.txt'), + await uploadFile(apiClient, validId, otherParentId, 'other2.txt'), + await uploadFile(apiClient, validId, otherParentId, 'other3.txt'), ]); - const fileRecords = uploadResponse.map(({ result }) => result); + const result = await apiClient.delete(`/delete/school/${validId}/schools/${validId}`); + const response = result.body as FileRecordListResponse; - const { result } = await api.delete(`/school/${validId}/schools/${validId}`); - - const resultData: FileRecordResponse[] = result.data; + const resultData: FileRecordResponse[] = response.data; const ids: EntityId[] = resultData.map((o) => o.id); - expect(result.total).toEqual(3); + expect(response.total).toEqual(3); expect(ids.sort()).toEqual([fileRecords[0].id, fileRecords[1].id, fileRecords[2].id].sort()); }); }); }); describe('delete single file', () => { + describe('with not authenticated user', () => { + it('should return status 401', async () => { + const apiClient = new TestApiClient(app, baseRouteName); + + const response = await apiClient.delete(`/delete/123`); + + expect(response.status).toEqual(401); + }); + }); + describe('with bad request data', () => { - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); await em.persistAndFlush([user, account]); em.clear(); - }); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + return { apiClient }; + }; it('should return status 400 for invalid fileRecordId', async () => { - const response = await api.deleteFile(`/123`); - expect(response.error.validationErrors).toEqual([ + const { apiClient } = await setup(); + + const response = await apiClient.delete(`/delete/123`); + const { validationErrors } = response.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['fileRecordId must be a mongodb id'], field: ['fileRecordId'], @@ -267,9 +277,7 @@ describe(`${baseRouteName} (api)`, () => { }); describe(`with valid request data`, () => { - let fileRecordId: string; - - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -277,26 +285,42 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); - const { result } = await api.postUploadFile( - `/file/upload/school/${school.id}/schools/${school.id}`, - 'test1.txt' - ); + const result = await apiClient + .post(`/upload/school/${school.id}/schools/${school.id}`) + .attach('file', Buffer.from('abcd'), 'test1.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + const response = result.body as FileRecordResponse; + const fileRecordId = response.id; - fileRecordId = result.id; - }); + return { apiClient, fileRecordId }; + }; it('should return status 200 for successful request', async () => { - const response = await api.deleteFile(`/${fileRecordId}`); + const { apiClient, fileRecordId } = await setup(); + + const response = await apiClient.delete(`/delete/${fileRecordId}`); expect(response.status).toEqual(200); }); it('should return right type of data', async () => { - const { result } = await api.deleteFile(`/${fileRecordId}`); + const { apiClient, fileRecordId } = await setup(); + + const result = await apiClient.delete(`/delete/${fileRecordId}`); + const response = result.body as FileRecordResponse; - expect(result).toStrictEqual({ + expect(response).toStrictEqual({ creatorId: expect.any(String), id: expect.any(String), name: expect.any(String), @@ -314,6 +338,7 @@ describe(`${baseRouteName} (api)`, () => { }); it('should return elements of requested scope', async () => { + const { apiClient, fileRecordId } = await setup(); const otherFileRecords = fileRecordFactory.buildList(3, { parentType: FileRecordParentType.School, }); @@ -321,9 +346,10 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush(otherFileRecords); em.clear(); - const { result } = await api.deleteFile(`/${fileRecordId}`); + const result = await apiClient.delete(`/delete/${fileRecordId}`); + const response = result.body as FileRecordResponse; - expect(result.id).toEqual(fileRecordId); + expect(response.id).toEqual(fileRecordId); }); }); }); diff --git a/apps/server/src/modules/files-storage/controller/api-test/files-storage-download-upload.api.spec.ts b/apps/server/src/modules/files-storage/controller/api-test/files-storage-download-upload.api.spec.ts index 6e5878d3ee2..c82fc880995 100644 --- a/apps/server/src/modules/files-storage/controller/api-test/files-storage-download-upload.api.spec.ts +++ b/apps/server/src/modules/files-storage/controller/api-test/files-storage-download-upload.api.spec.ts @@ -1,29 +1,23 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { AntivirusService } from '@infra/antivirus'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { AuthorizationClientAdapter } from '@infra/authorization-client'; import { S3ClientAdapter } from '@infra/s3-client'; -import { EntityManager } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; -import { EntityId } from '@shared/domain/types'; -import { - cleanupCollections, - mapUserToCurrentUser, - schoolEntityFactory, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { JwtAuthenticationFactory } from '@testing/factory/jwt-authentication.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import NodeClam from 'clamscan'; -import { Request } from 'express'; import FileType from 'file-type-cjs/file-type-cjs-index'; -import request from 'supertest'; import { FileRecord } from '../../entity'; import { ErrorType } from '../../error'; import { FilesStorageTestModule } from '../../files-storage-test.module'; import { FILES_STORAGE_S3_CONNECTION } from '../../files-storage.config'; import { TestHelper } from '../../helper/test-helper'; -import { FileRecordResponse } from '../dto'; import { availableParentTypes } from './mocks'; jest.mock('file-type-cjs/file-type-cjs-index', () => { @@ -32,66 +26,6 @@ jest.mock('file-type-cjs/file-type-cjs-index', () => { }; }); -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async postUploadFile(routeName: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .post(routeName) - .attach('file', Buffer.from('abcd'), 'test.txt') - .set('connection', 'keep-alive') - .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20') - .query(query || {}); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async postUploadFromUrl(routeName: string, data: Record) { - const response = await request(this.app.getHttpServer()).post(routeName).send(data); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async getDownloadFile(routeName: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .get(routeName) - .query(query || {}); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - headers: response.headers as Record, - }; - } - - async getDownloadFileBytesRange(routeName: string, bytesRange: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .get(routeName) - .set('Range', bytesRange) - .query(query || {}); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - headers: response.headers as Record, - }; - } -} - const createRndInt = (max) => Math.floor(Math.random() * max); describe('files-storage controller (API)', () => { @@ -99,10 +33,8 @@ describe('files-storage controller (API)', () => { let app: INestApplication; let em: EntityManager; let s3ClientAdapter: DeepMocked; - let currentUser: ICurrentUser; - let api: API; - let validId: EntityId; let appPort: number; + const baseRouteName = '/file'; beforeAll(async () => { appPort = 10000 + createRndInt(10000); @@ -114,14 +46,6 @@ describe('files-storage controller (API)', () => { .useValue(createMock()) .overrideProvider(FILES_STORAGE_S3_CONNECTION) .useValue(createMock()) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .overrideProvider(NodeClam) .useValue(createMock()) .overrideProvider(AuthorizationClientAdapter) @@ -134,7 +58,6 @@ describe('files-storage controller (API)', () => { em = module.get(EntityManager); s3ClientAdapter = module.get(FILES_STORAGE_S3_CONNECTION); - api = new API(app); }); afterAll(async () => { @@ -142,69 +65,114 @@ describe('files-storage controller (API)', () => { await module.close(); }); - beforeEach(async () => { - jest.resetAllMocks(); - await cleanupCollections(em); - const school = schoolEntityFactory.build(); - const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + describe('upload action', () => { + const setup = async () => { + jest.resetAllMocks(); + await cleanupCollections(em); + const school = schoolEntityFactory.build(); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + + await em.persistAndFlush([user, school, account]); + em.clear(); + const validId = school.id; + + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); - await em.persistAndFlush([user, school, account]); - em.clear(); - validId = school.id; - currentUser = mapUserToCurrentUser(user); + return { validId, apiClient, user }; + }; - jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); - }); + const uploadFile = async (routeName: string, apiClient: TestApiClient) => { + const response = await apiClient + .post(routeName) + .attach('file', Buffer.from('abcd'), 'test.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + + return response; + }; + + describe('with not authenticated user', () => { + it('should return status 401', async () => { + const { validId } = await setup(); + const apiClient = new TestApiClient(app, baseRouteName); + + const result = await uploadFile(`/upload/school/123/users/${validId}`, apiClient); + + expect(result.status).toEqual(401); + }); + }); - describe('upload action', () => { describe('with bad request data', () => { it('should return status 400 for invalid schoolId', async () => { - const response = await api.postUploadFile(`/file/upload/school/123/users/${validId}`); + const { apiClient, validId } = await setup(); + + const result = await uploadFile(`/upload/school/123/users/${validId}`, apiClient); - expect(response.error.validationErrors).toEqual([ + const { validationErrors } = result.body as ApiValidationError; + expect(validationErrors).toEqual([ { errors: ['storageLocationId must be a mongodb id'], field: ['storageLocationId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for invalid parentId', async () => { - const response = await api.postUploadFile(`/file/upload/school/${validId}/users/123`); + const { apiClient, validId } = await setup(); + + const result = await uploadFile(`/upload/school/${validId}/users/123`, apiClient); - expect(response.error.validationErrors).toEqual([ + const { validationErrors } = result.body as ApiValidationError; + expect(validationErrors).toEqual([ { errors: ['parentId must be a mongodb id'], field: ['parentId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for invalid parentType', async () => { - const response = await api.postUploadFile(`/file/upload/school/${validId}/cookies/${validId}`); + const { apiClient, validId } = await setup(); - expect(response.status).toEqual(400); + const result = await uploadFile(`/upload/school/${validId}/cookies/${validId}`, apiClient); + + expect(result.status).toEqual(400); }); }); describe(`with valid request data`, () => { it('should return status 201 for successful upload', async () => { - const response = await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`); + const { apiClient, validId } = await setup(); + + const response = await uploadFile(`upload/school/${validId}/schools/${validId}`, apiClient); expect(response.status).toEqual(201); }); it('should return the new created file record', async () => { - const { result } = await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`); + const { apiClient, validId, user } = await setup(); - expect(result).toStrictEqual( + const result = await uploadFile(`/upload/school/${validId}/schools/${validId}`, apiClient); + const response = result.body as FileRecord; + + expect(response).toStrictEqual( expect.objectContaining({ id: expect.any(String), name: 'test.txt', parentId: validId, - creatorId: currentUser.userId, + creatorId: user.id, mimeType: 'text/plain', parentType: 'schools', securityCheckStatus: 'pending', @@ -214,25 +182,78 @@ describe('files-storage controller (API)', () => { }); it('should set iterator number to file name if file already exist', async () => { - await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`); + const { apiClient, validId } = await setup(); + + await uploadFile(`/upload/school/${validId}/schools/${validId}`, apiClient); - const { result } = await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`); + const result = await uploadFile(`/upload/school/${validId}/schools/${validId}`, apiClient); + const response = result.body as FileRecord; - expect(result.name).toEqual('test (1).txt'); + expect(response.name).toEqual('test (1).txt'); }); }); }); describe('upload from url action', () => { - let body = { - url: 'http://localhost/test.txt', - fileName: 'test.txt', - }; + describe('with not authenticated user', () => { + const setup = () => { + const apiClient = new TestApiClient(app, baseRouteName); + + const body = { + url: 'http://localhost/test.txt', + fileName: 'test.txt', + }; + + return { apiClient, body }; + }; + + it('should return status 401', async () => { + const { apiClient, body } = setup(); + + const response = await apiClient.post(`/upload-from-url/school/123/users/123`, body); + + expect(response.status).toEqual(401); + }); + }); + describe('with bad request data', () => { + const setup = async () => { + jest.resetAllMocks(); + await cleanupCollections(em); + const school = schoolEntityFactory.build(); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + + await em.persistAndFlush([user, school, account]); + em.clear(); + const validId = school.id; + + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + const body = { + url: 'http://localhost/test.txt', + fileName: 'test.txt', + }; + + return { validId, apiClient, body }; + }; + it('should return status 400 for invalid schoolId', async () => { - const response = await api.postUploadFromUrl(`/file/upload-from-url/school/123/users/${validId}`, body); + const { apiClient, validId, body } = await setup(); - expect(response.error.validationErrors).toEqual([ + const response = await apiClient.post(`/upload-from-url/school/123/users/${validId}`, body); + const { validationErrors } = response.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['storageLocationId must be a mongodb id'], field: ['storageLocationId'], @@ -242,9 +263,12 @@ describe('files-storage controller (API)', () => { }); it('should return status 400 for invalid parentId', async () => { - const response = await api.postUploadFromUrl(`/file/upload-from-url/school/${validId}/users/123`, body); + const { apiClient, validId, body } = await setup(); + + const response = await apiClient.post(`/upload-from-url/school/${validId}/users/123`, body); + const { validationErrors } = response.body as ApiValidationError; - expect(response.error.validationErrors).toEqual([ + expect(validationErrors).toEqual([ { errors: ['parentId must be a mongodb id'], field: ['parentId'], @@ -254,12 +278,12 @@ describe('files-storage controller (API)', () => { }); it('should return status 400 for invalid parentType', async () => { - const response = await api.postUploadFromUrl( - `/file/upload-from-url/school/${validId}/cookies/${validId}`, - body - ); + const { apiClient, validId, body } = await setup(); - expect(response.error.validationErrors).toEqual([ + const response = await apiClient.post(`/upload-from-url/school/${validId}/cookies/${validId}`, body); + const { validationErrors } = response.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: [`parentType must be one of the following values: ${availableParentTypes}`], field: ['parentType'], @@ -269,9 +293,12 @@ describe('files-storage controller (API)', () => { }); it('should return status 400 for empty url and fileName', async () => { - const response = await api.postUploadFromUrl(`/file/upload-from-url/school/${validId}/schools/${validId}`, {}); + const { validId, apiClient } = await setup(); + + const response = await apiClient.post(`/upload-from-url/school/${validId}/schools/${validId}`, {}); + const { validationErrors } = response.body as ApiValidationError; - expect(response.error.validationErrors).toEqual([ + expect(validationErrors).toEqual([ { errors: ['url should not be empty', 'url must be a string'], field: ['url'], @@ -287,38 +314,69 @@ describe('files-storage controller (API)', () => { describe(`with valid request data`, () => { describe(`with new file`, () => { - beforeEach(async () => { + const setup = async () => { + jest.resetAllMocks(); + await cleanupCollections(em); + const school = schoolEntityFactory.build(); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + + await em.persistAndFlush([user, school, account]); + em.clear(); + const validId = school.id; + + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + const expectedResponse = TestHelper.createFile({ contentRange: 'bytes 0-3/4' }); s3ClientAdapter.get.mockResolvedValueOnce(expectedResponse); - const uploadResponse = await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`); - const { result } = uploadResponse; - body = { - url: `http://localhost:${appPort}/file/download/${result.id}/${result.name}`, + const result = await apiClient + .post(`/upload/school/${validId}/schools/${validId}`) + .attach('file', Buffer.from('abcd'), 'test.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + const response = result.body as FileRecord; + + const body = { + url: `http://localhost:${appPort}/file/download/${response.id}/${response.name}`, fileName: 'test.txt', + headers: { + authorization: `Bearer ${authValue}`, + }, }; - }); + + return { validId, apiClient, body, user }; + }; it('should return status 201 for successful upload', async () => { - const response = await api.postUploadFromUrl( - `/file/upload-from-url/school/${validId}/schools/${validId}`, - body - ); + const { validId, apiClient, body } = await setup(); + + const result = await apiClient.post(`/upload-from-url/school/${validId}/schools/${validId}`, body); - expect(response.status).toEqual(201); + expect(result.status).toEqual(201); }); it('should return the new created file record', async () => { - const { result } = await api.postUploadFromUrl( - `/file/upload-from-url/school/${validId}/schools/${validId}`, - body - ); - expect(result).toStrictEqual( + const { validId, apiClient, body, user } = await setup(); + + const result = await apiClient.post(`/upload-from-url/school/${validId}/schools/${validId}`, body); + const response = result.body as FileRecord; + + expect(response).toStrictEqual( expect.objectContaining({ id: expect.any(String), name: 'test (1).txt', parentId: validId, - creatorId: currentUser.userId, + creatorId: user.id, mimeType: 'application/octet-stream', parentType: 'schools', securityCheckStatus: 'pending', @@ -328,58 +386,138 @@ describe('files-storage controller (API)', () => { }); describe(`with already existing file`, () => { - beforeEach(async () => { + const setup = async () => { + jest.resetAllMocks(); + await cleanupCollections(em); + const school = schoolEntityFactory.build(); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + + await em.persistAndFlush([user, school, account]); + em.clear(); + const validId = school.id; + + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + const expectedResponse1 = TestHelper.createFile({ contentRange: 'bytes 0-3/4' }); const expectedResponse2 = TestHelper.createFile({ contentRange: 'bytes 0-3/4' }); s3ClientAdapter.get.mockResolvedValueOnce(expectedResponse1).mockResolvedValueOnce(expectedResponse2); - const uploadResponse = await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`); - const { result } = uploadResponse; - body = { - url: `http://localhost:${appPort}/file/download/${result.id}/${result.name}`, + const result = await apiClient + .post(`/upload/school/${validId}/schools/${validId}`) + .attach('file', Buffer.from('abcd'), 'test.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + const response = result.body as FileRecord; + const body = { + url: `http://localhost:${appPort}/file/download/${response.id}/${response.name}`, fileName: 'test.txt', + headers: { + authorization: `Bearer ${authValue}`, + }, }; - await api.postUploadFromUrl(`/file/upload-from-url/school/${validId}/schools/${validId}`, body); - }); + await apiClient.post(`/upload-from-url/school/${validId}/schools/${validId}`, body); + + return { validId, apiClient, body }; + }; it('should set iterator number to file name if file already exist', async () => { - const { result } = await api.postUploadFromUrl( - `/file/upload-from-url/school/${validId}/schools/${validId}`, - body - ); + const { validId, apiClient, body } = await setup(); + + const result = await apiClient.post(`/upload-from-url/school/${validId}/schools/${validId}`, body); + const response = result.body as FileRecord; - expect(result.name).toEqual('test (2).txt'); + expect(response.name).toEqual('test (2).txt'); }); }); }); }); describe('download action', () => { + describe('with not authenticated user', () => { + it('should return status 401', async () => { + const apiClient = new TestApiClient(app, baseRouteName); + + const result = await apiClient.get('/download/123/text.txt'); + + expect(result.status).toEqual(401); + }); + }); + describe('with bad request data', () => { + const setup = async () => { + jest.resetAllMocks(); + await cleanupCollections(em); + const school = schoolEntityFactory.build(); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + + await em.persistAndFlush([user, school, account]); + em.clear(); + const validId = school.id; + + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + const result = await apiClient + .post(`/upload/school/${validId}/schools/${validId}`) + .attach('file', Buffer.from('abcd'), 'test.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + const fileRecord = result.body as FileRecord; + + return { validId, apiClient, fileRecord }; + }; + it('should return status 400 for invalid recordId', async () => { - const response = await api.getDownloadFile('/file/download/123/text.txt'); + const { apiClient } = await setup(); - expect(response.error.validationErrors).toEqual([ + const result = await apiClient.get('/download/123/text.txt'); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['fileRecordId must be a mongodb id'], field: ['fileRecordId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 404 for wrong filename', async () => { - const { result } = await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`); - const response = await api.getDownloadFile(`/file/download/${result.id}/wrong-name.txt`); + const { apiClient, fileRecord } = await setup(); - expect(response.error.message).toEqual(ErrorType.FILE_NOT_FOUND); - expect(response.status).toEqual(404); + const result = await apiClient.get(`/download/${fileRecord.id}/wrong-name.txt`); + const response = result.body as ApiValidationError; + + expect(response.message).toEqual(ErrorType.FILE_NOT_FOUND); + expect(result.status).toEqual(404); }); it('should return status 404 for file not found', async () => { - const response = await api.getDownloadFile(`/file/download/${validId}/wrong-name.txt`); + const { apiClient } = await setup(); + const notExistingId = new ObjectId().toHexString(); + + const response = await apiClient.get(`/download/${notExistingId}/wrong-name.txt`); expect(response.status).toEqual(404); }); @@ -388,65 +526,117 @@ describe('files-storage controller (API)', () => { describe(`with valid request data`, () => { describe('when mimetype is not application/pdf', () => { const setup = async () => { - const { result: uploadedFile } = await api.postUploadFile( - `/file/upload/school/${validId}/schools/${validId}` - ); + jest.resetAllMocks(); + await cleanupCollections(em); + const school = schoolEntityFactory.build(); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + + await em.persistAndFlush([user, school, account]); + em.clear(); + const validId = school.id; + + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + const result = await apiClient + .post(`/upload/school/${validId}/schools/${validId}`) + .attach('file', Buffer.from('abcd'), 'test.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + const uploadedFile = result.body as FileRecord; + const expectedResponse = TestHelper.createFile({ contentRange: 'bytes 0-3/4', mimeType: 'image/webp' }); s3ClientAdapter.get.mockResolvedValueOnce(expectedResponse); - return { uploadedFile }; + return { uploadedFile, apiClient }; }; it('should return status 200 for successful download', async () => { - const { uploadedFile } = await setup(); + const { uploadedFile, apiClient } = await setup(); - const response = await api.getDownloadFile(`/file/download/${uploadedFile.id}/${uploadedFile.name}`); + const response = await apiClient.get(`/download/${uploadedFile.id}/${uploadedFile.name}`); expect(response.status).toEqual(200); }); it('should return status 206 and required headers for the successful partial file stream download', async () => { - const { uploadedFile } = await setup(); + const { uploadedFile, apiClient } = await setup(); - const response = await api.getDownloadFileBytesRange( - `/file/download/${uploadedFile.id}/${uploadedFile.name}`, - 'bytes=0-' - ); + const response = await apiClient + .get(`/download/${uploadedFile.id}/${uploadedFile.name}`) + .set('Range', 'bytes=0-'); + const headers = response.headers as Record; expect(response.status).toEqual(206); - expect(response.headers['accept-ranges']).toMatch('bytes'); - expect(response.headers['content-range']).toMatch('bytes 0-3/4'); + expect(headers['accept-ranges']).toMatch('bytes'); + expect(headers['content-range']).toMatch('bytes 0-3/4'); }); it('should set content-disposition header to attachment', async () => { - const { uploadedFile } = await setup(); + const { uploadedFile, apiClient } = await setup(); - const response = await api.getDownloadFile(`/file/download/${uploadedFile.id}/${uploadedFile.name}`); + const response = await apiClient.get(`/download/${uploadedFile.id}/${uploadedFile.name}`); + const headers = response.headers as Record; - expect(response.headers['content-disposition']).toMatch('attachment'); + expect(headers['content-disposition']).toMatch('attachment'); }); }); describe('when mimetype is application/pdf', () => { const setup = async () => { - const { result: uploadedFile } = await api.postUploadFile( - `/file/upload/school/${validId}/schools/${validId}` - ); + jest.resetAllMocks(); + await cleanupCollections(em); + const school = schoolEntityFactory.build(); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + + await em.persistAndFlush([user, school, account]); + em.clear(); + const validId = school.id; + + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + const result = await apiClient + .post(`/upload/school/${validId}/schools/${validId}`) + .attach('file', Buffer.from('abcd'), 'test.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + const uploadedFile = result.body as FileRecord; + const expectedResponse = TestHelper.createFile({ contentRange: 'bytes 0-3/4', mimeType: 'application/pdf' }); s3ClientAdapter.get.mockResolvedValueOnce(expectedResponse); - return { uploadedFile }; + return { uploadedFile, apiClient }; }; it('should set content-disposition to inline', async () => { - const { uploadedFile } = await setup(); + const { uploadedFile, apiClient } = await setup(); - const response = await api.getDownloadFile(`/file/download/${uploadedFile.id}/${uploadedFile.name}`); + const response = await apiClient.get(`/download/${uploadedFile.id}/${uploadedFile.name}`); + const headers = response.headers as Record; - expect(response.headers['content-disposition']).toMatch('inline'); + expect(headers['content-disposition']).toMatch('inline'); }); }); }); @@ -454,8 +644,34 @@ describe('files-storage controller (API)', () => { describe('file-security.download()', () => { describe('with bad request data', () => { + const setup = async () => { + jest.resetAllMocks(); + await cleanupCollections(em); + const school = schoolEntityFactory.build(); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + + await em.persistAndFlush([user, school, account]); + em.clear(); + + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, '', authValue); + + return { apiClient }; + }; + it('should return status 404 for wrong token', async () => { - const response = await api.getDownloadFile('/file-security/download/test-token'); + const { apiClient } = await setup(); + + const response = await apiClient.get('/file-security/download/test-token'); expect(response.status).toEqual(404); }); @@ -463,20 +679,47 @@ describe('files-storage controller (API)', () => { describe(`with valid request data`, () => { const setup = async () => { + jest.resetAllMocks(); + await cleanupCollections(em); + const school = schoolEntityFactory.build(); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + + await em.persistAndFlush([user, school, account]); + em.clear(); + + const validId = school.id; + + jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const fileApiClient = new TestApiClient(app, baseRouteName, authValue); + const apiClient = new TestApiClient(app, '', authValue); + const expectedResponse = TestHelper.createFile({ contentRange: 'bytes 0-3/4' }); s3ClientAdapter.get.mockResolvedValueOnce(expectedResponse); + const result = await fileApiClient + .post(`/upload/school/${validId}/schools/${validId}`) + .attach('file', Buffer.from('abcd'), 'test.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + const fileRecord = result.body as FileRecord; - const { result } = await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`); - const newRecord = await em.findOneOrFail(FileRecord, result.id); + const newRecord = await em.findOneOrFail(FileRecord, { id: fileRecord.id }); - return { newRecord }; + return { newRecord, apiClient }; }; it('should return status 200 for successful download', async () => { - const { newRecord } = await setup(); - const response = await api.getDownloadFile( - `/file-security/download/${newRecord.securityCheck.requestToken || ''}` - ); + const { newRecord, apiClient } = await setup(); + + const response = await apiClient.get(`/file-security/download/${newRecord.securityCheck.requestToken || ''}`); expect(response.status).toEqual(200); }); diff --git a/apps/server/src/modules/files-storage/controller/api-test/files-storage-list-files.api.spec.ts b/apps/server/src/modules/files-storage/controller/api-test/files-storage-list-files.api.spec.ts index 4ff5a612076..2201e148761 100644 --- a/apps/server/src/modules/files-storage/controller/api-test/files-storage-list-files.api.spec.ts +++ b/apps/server/src/modules/files-storage/controller/api-test/files-storage-list-files.api.spec.ts @@ -1,21 +1,17 @@ import { createMock } from '@golevelup/ts-jest'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { AuthorizationClientAdapter } from '@infra/authorization-client'; import { EntityManager } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; import { EntityId } from '@shared/domain/types'; -import { - cleanupCollections, - fileRecordFactory, - mapUserToCurrentUser, - schoolEntityFactory, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { JwtAuthenticationFactory } from '@testing/factory/jwt-authentication.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import NodeClam from 'clamscan'; -import { Request } from 'express'; -import request from 'supertest'; import { PreviewStatus } from '../../entity'; import { FilesStorageTestModule } from '../../files-storage-test.module'; import { FileRecordParentType, StorageLocation } from '../../interface'; @@ -24,46 +20,14 @@ import { availableParentTypes } from './mocks'; const baseRouteName = '/file/list'; -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async get(requestString: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .get(`${baseRouteName}${requestString}`) - .set('Accept', 'application/json') - .query(query || {}); - - return { - result: response.body as FileRecordListResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} - describe(`${baseRouteName} (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; - let validId: string; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [FilesStorageTestModule], }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .overrideProvider(NodeClam) .useValue(createMock()) .overrideProvider(AuthorizationClientAdapter) @@ -73,40 +37,66 @@ describe(`${baseRouteName} (api)`, () => { app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); - api = new API(app); }); afterAll(async () => { await app.close(); }); + describe('with not authenticated user', () => { + it('should return status 401', async () => { + const apiClient = new TestApiClient(app, baseRouteName); + + const response = await apiClient.get(`/school/123/users/123`); + + expect(response.status).toEqual(401); + }); + }); + describe('with bad request data', () => { - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + await em.persistAndFlush([user, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); - validId = user.school.id; - }); + const validId = user.school.id; + + return { apiClient, validId }; + }; it('should return status 400 for invalid schoolId', async () => { - const response = await api.get(`/school/123/users/${validId}`); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId } = await setup(); + const response = await apiClient.get(`/school/123/users/${validId}`); + const { validationErrors } = response.body as ApiValidationError; + + expect(response.status).toEqual(400); + expect(validationErrors).toEqual([ { errors: ['storageLocationId must be a mongodb id'], field: ['storageLocationId'], }, ]); - expect(response.status).toEqual(400); }); it('should return status 400 for invalid parentId', async () => { - const response = await api.get(`/school/${validId}/users/123`); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId } = await setup(); + const response = await apiClient.get(`/school/${validId}/users/123`); + const { validationErrors } = response.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['parentId must be a mongodb id'], field: ['parentId'], @@ -116,8 +106,11 @@ describe(`${baseRouteName} (api)`, () => { }); it('should return status 400 for invalid parentType', async () => { - const response = await api.get(`/school/${validId}/cookies/${validId}`); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId } = await setup(); + const response = await apiClient.get(`/school/${validId}/cookies/${validId}`); + const { validationErrors } = response.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: [`parentType must be one of the following values: ${availableParentTypes}`], field: ['parentType'], @@ -128,28 +121,44 @@ describe(`${baseRouteName} (api)`, () => { }); describe(`with valid request data`, () => { - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + await em.persistAndFlush([user, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); - validId = user.school.id; - }); + const validId = user.school.id; + + return { apiClient, validId }; + }; it('should return status 200 for successful request', async () => { - const response = await api.get(`/school/${validId}/schools/${validId}`); + const { apiClient, validId } = await setup(); + + const response = await apiClient.get(`/school/${validId}/schools/${validId}`); expect(response.status).toEqual(200); }); it('should return a paginated result as default', async () => { - const { result } = await api.get(`/school/${validId}/schools/${validId}`); + const { apiClient, validId } = await setup(); + + const result = await apiClient.get(`/school/${validId}/schools/${validId}`); + const response = result.body as FileRecordListResponse; - expect(result).toEqual({ + expect(response).toEqual({ total: 0, limit: 10, skip: 0, @@ -158,13 +167,17 @@ describe(`${baseRouteName} (api)`, () => { }); it('should pass the pagination qurey params', async () => { - const { result } = await api.get(`/school/${validId}/schools/${validId}`, { limit: 100, skip: 100 }); + const { apiClient, validId } = await setup(); + + const result = await apiClient.get(`/school/${validId}/schools/${validId}`).query({ limit: 100, skip: 100 }); + const response = result.body as FileRecordListResponse; - expect(result.limit).toEqual(100); - expect(result.skip).toEqual(100); + expect(response.limit).toEqual(100); + expect(response.skip).toEqual(100); }); it('should return right type of data', async () => { + const { apiClient, validId } = await setup(); const fileRecords = fileRecordFactory.buildList(1, { storageLocation: StorageLocation.SCHOOL, storageLocationId: validId, @@ -175,11 +188,12 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush(fileRecords); em.clear(); - const { result } = await api.get(`/school/${validId}/schools/${validId}`); + const result = await apiClient.get(`/school/${validId}/schools/${validId}`); + const response = result.body as FileRecordListResponse; - expect(Array.isArray(result.data)).toBe(true); - expect(result.data[0]).toBeDefined(); - expect(result.data[0]).toStrictEqual({ + expect(Array.isArray(response.data)).toBe(true); + expect(response.data[0]).toBeDefined(); + expect(response.data[0]).toStrictEqual({ creatorId: expect.any(String), id: expect.any(String), name: expect.any(String), @@ -196,6 +210,7 @@ describe(`${baseRouteName} (api)`, () => { }); it('should return elements of requested scope', async () => { + const { apiClient, validId } = await setup(); const fileRecords = fileRecordFactory.buildList(3, { storageLocation: StorageLocation.SCHOOL, storageLocationId: validId, @@ -211,12 +226,13 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([...otherFileRecords, ...fileRecords]); em.clear(); - const { result } = await api.get(`/school/${validId}/schools/${validId}`); + const result = await apiClient.get(`/school/${validId}/schools/${validId}`); + const response = result.body as FileRecordListResponse; - const resultData: FileRecordResponse[] = result.data; + const resultData: FileRecordResponse[] = response.data; const ids: EntityId[] = resultData.map((o) => o.id); - expect(result.total).toEqual(3); + expect(response.total).toEqual(3); expect(ids.sort()).toEqual([fileRecords[0].id, fileRecords[1].id, fileRecords[2].id].sort()); }); }); diff --git a/apps/server/src/modules/files-storage/controller/api-test/files-storage-preview.api.spec.ts b/apps/server/src/modules/files-storage/controller/api-test/files-storage-preview.api.spec.ts index b901debc078..c5efea819fb 100644 --- a/apps/server/src/modules/files-storage/controller/api-test/files-storage-preview.api.spec.ts +++ b/apps/server/src/modules/files-storage/controller/api-test/files-storage-preview.api.spec.ts @@ -1,24 +1,20 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { AntivirusService } from '@infra/antivirus'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { AuthorizationClientAdapter } from '@infra/authorization-client'; import { PreviewProducer } from '@infra/preview-generator'; import { S3ClientAdapter } from '@infra/s3-client'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication, NotFoundException, StreamableFile } from '@nestjs/common'; +import { INestApplication, NotFoundException, StreamableFile } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; import { EntityId } from '@shared/domain/types'; -import { - cleanupCollections, - mapUserToCurrentUser, - schoolEntityFactory, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { JwtAuthenticationFactory } from '@testing/factory/jwt-authentication.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import NodeClam from 'clamscan'; -import { Request } from 'express'; import FileType from 'file-type-cjs/file-type-cjs-index'; -import request from 'supertest'; import { FileRecord, ScanStatus } from '../../entity'; import { ErrorType } from '../../error'; import { FilesStorageTestModule } from '../../files-storage-test.module'; @@ -34,68 +30,6 @@ jest.mock('file-type-cjs/file-type-cjs-index', () => { }; }); -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async postUploadFile(routeName: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .post(routeName) - .attach('file', Buffer.from('abcd'), 'test.png') - .set('connection', 'keep-alive') - .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20') - .query(query || {}); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async getPreview(routeName: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .get(routeName) - .query(query || {}); - - return { - result: response.body as StreamableFile, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async getPreviewWithEtag(routeName: string, etag: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .get(routeName) - .query(query || {}) - .set('If-None-Match', etag); - - return { - result: response.body as StreamableFile, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async getPreviewBytesRange(routeName: string, bytesRange: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .get(routeName) - .set('Range', bytesRange) - .query(query || {}); - - return { - result: response.body as StreamableFile, - error: response.body as ApiValidationError, - status: response.status, - headers: response.headers as Record, - }; - } -} - const createRndInt = (max) => Math.floor(Math.random() * max); const defaultQueryParameters = { @@ -109,14 +43,10 @@ describe('File Controller (API) - preview', () => { let em: EntityManager; let s3ClientAdapter: DeepMocked; let antivirusService: DeepMocked; - let currentUser: ICurrentUser; - let api: API; - let schoolId: EntityId; - let appPort: number; let uploadPath: string; beforeAll(async () => { - appPort = 10000 + createRndInt(10000); + const appPort = 10000 + createRndInt(10000); module = await Test.createTestingModule({ imports: [FilesStorageTestModule], @@ -127,14 +57,6 @@ describe('File Controller (API) - preview', () => { .useValue(createMock()) .overrideProvider(FILES_STORAGE_S3_CONNECTION) .useValue(createMock()) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .overrideProvider(NodeClam) .useValue(createMock()) .overrideProvider(AuthorizationClientAdapter) @@ -148,7 +70,6 @@ describe('File Controller (API) - preview', () => { em = module.get(EntityManager); s3ClientAdapter = module.get(FILES_STORAGE_S3_CONNECTION); antivirusService = module.get(AntivirusService); - api = new API(app); }); afterAll(async () => { @@ -159,32 +80,71 @@ describe('File Controller (API) - preview', () => { beforeEach(async () => { jest.resetAllMocks(); await cleanupCollections(em); + }); + + const setScanStatus = async (fileRecordId: EntityId, status: ScanStatus) => { + const fileRecord = await em.findOneOrFail(FileRecord, fileRecordId); + fileRecord.securityCheck.status = status; + await em.flush(); + }; + + const setupApiClient = async () => { const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); - await em.persistAndFlush([user, school, account]); + await em.persistAndFlush([school, user, account]); em.clear(); - schoolId = school.id; - currentUser = mapUserToCurrentUser(user); - uploadPath = `/file/upload/school/${schoolId}/schools/${schoolId}`; + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, '/file', authValue); + + const schoolId = school.id; + uploadPath = `/upload/school/${schoolId}/schools/${schoolId}`; jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); antivirusService.checkStream.mockResolvedValueOnce({ virus_detected: false }); - }); - const setScanStatus = async (fileRecordId: EntityId, status: ScanStatus) => { - const fileRecord = await em.findOneOrFail(FileRecord, fileRecordId); - fileRecord.securityCheck.status = status; - await em.flush(); + return apiClient; + }; + + const uploadFile = async (apiClient: TestApiClient) => { + const uploadResponse = await apiClient + .post(uploadPath) + .attach('file', Buffer.from('abcd'), 'test.png') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20') + .query({}); + const uploadedFile = uploadResponse.body as FileRecordResponse; + + return uploadedFile; }; describe('preview', () => { + describe('with not authenticated user', () => { + it('should return status 401', async () => { + const apiClient = new TestApiClient(app, '/file'); + + const response = await apiClient.get('/preview/123/test.png').query(defaultQueryParameters); + + expect(response.status).toEqual(401); + }); + }); + describe('with bad request data', () => { describe('WHEN recordId is invalid', () => { it('should return status 400', async () => { - const response = await api.getPreview('/file/preview/123/test.png', defaultQueryParameters); + const apiClient = await setupApiClient(); + const response = await apiClient.get('/preview/123/test.png').query(defaultQueryParameters); + const result = response.body as ApiValidationError; - expect(response.error.validationErrors).toEqual([ + expect(result.validationErrors).toEqual([ { errors: ['fileRecordId must be a mongodb id'], field: ['fileRecordId'], @@ -196,15 +156,17 @@ describe('File Controller (API) - preview', () => { describe('WHEN width is other than PreviewWidth Enum', () => { it('should return status 400', async () => { - const { result } = await api.postUploadFile(uploadPath); + const apiClient = await setupApiClient(); + const uploadedFile = await uploadFile(apiClient); + const query = { ...defaultQueryParameters, width: 2000, }; + const response = await apiClient.get(`/preview/${uploadedFile.id}/${uploadedFile.name}`).query(query); + const result = response.body as ApiValidationError; - const response = await api.getPreview(`/file/preview/${result.id}/${result.name}`, query); - - expect(response.error.validationErrors).toEqual([ + expect(result.validationErrors).toEqual([ { errors: ['width must be one of the following values: 500'], field: ['width'], @@ -216,12 +178,14 @@ describe('File Controller (API) - preview', () => { describe('WHEN output format is wrong', () => { it('should return status 400', async () => { - const { result } = await api.postUploadFile(uploadPath); - const query = { ...defaultQueryParameters, outputFormat: 'image/txt' }; + const apiClient = await setupApiClient(); + const uploadedFile = await uploadFile(apiClient); - const response = await api.getPreview(`/file/preview/${result.id}/${result.name}`, query); + const query = { ...defaultQueryParameters, outputFormat: 'image/txt' }; + const response = await apiClient.get(`/preview/${uploadedFile.id}/${uploadedFile.name}`).query(query); + const result = response.body as ApiValidationError; - expect(response.error.validationErrors).toEqual([ + expect(result.validationErrors).toEqual([ { errors: ['outputFormat must be one of the following values: image/webp'], field: ['outputFormat'], @@ -233,32 +197,35 @@ describe('File Controller (API) - preview', () => { describe('WHEN file does not exist', () => { it('should return status 404', async () => { - const { result } = await api.postUploadFile(uploadPath); - const wrongId = new ObjectId().toString(); + const apiClient = await setupApiClient(); + const uploadedFile = await uploadFile(apiClient); - const response = await api.getPreview(`/file/preview/${wrongId}/${result.name}`, defaultQueryParameters); + const wrongId = new ObjectId().toString(); + const response = await apiClient + .get(`/preview/${wrongId}/${uploadedFile.name}`) + .query(defaultQueryParameters); + const result = response.body as ApiValidationError; - expect(response.error.message).toEqual('The requested FileRecord: [object Object] has not been found.'); + expect(result.message).toEqual('The requested FileRecord: [object Object] has not been found.'); expect(response.status).toEqual(404); }); }); describe('WHEN filename is wrong', () => { - const setup = async () => { - const { result } = await api.postUploadFile(uploadPath); - await setScanStatus(result.id, ScanStatus.VERIFIED); + it('should return status 404', async () => { + const apiClient = await setupApiClient(); + const uploadedFile = await uploadFile(apiClient); + await setScanStatus(uploadedFile.id, ScanStatus.VERIFIED); + const error = new NotFoundException(); s3ClientAdapter.get.mockRejectedValueOnce(error); - return { result }; - }; - - it('should return status 404', async () => { - const { result } = await setup(); - - const response = await api.getPreview(`/file/preview/${result.id}/wrong-name.txt`, defaultQueryParameters); + const response = await apiClient + .get(`/preview/${uploadedFile.id}/wrong-name.txt`) + .query(defaultQueryParameters); + const result = response.body as ApiValidationError; - expect(response.error.message).toEqual(ErrorType.FILE_NOT_FOUND); + expect(result.message).toEqual(ErrorType.FILE_NOT_FOUND); expect(response.status).toEqual(404); }); }); @@ -268,101 +235,102 @@ describe('File Controller (API) - preview', () => { describe('WHEN preview does already exist', () => { describe('WHEN forceUpdate is undefined', () => { const setup = async () => { - const { result: uploadedFile } = await api.postUploadFile(uploadPath); + const apiClient = await setupApiClient(); + const uploadedFile = await uploadFile(apiClient); await setScanStatus(uploadedFile.id, ScanStatus.VERIFIED); const previewFile = TestHelper.createFile({ contentRange: 'bytes 0-3/4' }); s3ClientAdapter.get.mockResolvedValueOnce(previewFile); - return { uploadedFile, previewFile }; + return { apiClient, uploadedFile }; }; it('should return status 200 for successful download', async () => { - const { uploadedFile } = await setup(); + const { apiClient, uploadedFile } = await setup(); const buffer = Buffer.from('testText'); - const response = await api.getPreview( - `/file/preview/${uploadedFile.id}/${uploadedFile.name}`, - defaultQueryParameters - ); + const response = await apiClient + .get(`/preview/${uploadedFile.id}/${uploadedFile.name}`) + .query(defaultQueryParameters); + const result = response.body as StreamableFile; expect(response.status).toEqual(200); - expect(response.result).toEqual(buffer); + expect(result).toEqual(buffer); }); it('should return status 206 and required headers for the successful partial file stream download', async () => { - const { uploadedFile } = await setup(); + const { apiClient, uploadedFile } = await setup(); - const response = await api.getPreviewBytesRange( - `/file/preview/${uploadedFile.id}/${uploadedFile.name}`, - 'bytes=0-', - defaultQueryParameters - ); + const response = await apiClient + .get(`/preview/${uploadedFile.id}/${uploadedFile.name}`) + .set('Range', 'bytes=0-') + .query(defaultQueryParameters); + const headers = response.headers as Record; expect(response.status).toEqual(206); - expect(response.headers['accept-ranges']).toMatch('bytes'); - expect(response.headers['content-range']).toMatch('bytes 0-3/4'); + expect(headers['accept-ranges']).toMatch('bytes'); + expect(headers['content-range']).toMatch('bytes 0-3/4'); }); }); describe('WHEN forceUpdate is false', () => { const setup = async () => { - const { result: uploadedFile } = await api.postUploadFile(uploadPath); + const apiClient = await setupApiClient(); + const uploadedFile = await uploadFile(apiClient); await setScanStatus(uploadedFile.id, ScanStatus.VERIFIED); const previewFile = TestHelper.createFile({ contentRange: 'bytes 0-3/4' }); s3ClientAdapter.get.mockResolvedValueOnce(previewFile); - return { uploadedFile }; + return { apiClient, uploadedFile }; }; describe('WHEN header contains no etag', () => { it('should return status 200 for successful download', async () => { - const { uploadedFile } = await setup(); + const { apiClient, uploadedFile } = await setup(); const query = { ...defaultQueryParameters, forceUpdate: false, }; - const response = await api.getPreview(`/file/preview/${uploadedFile.id}/${uploadedFile.name}`, query); + const response = await apiClient.get(`/preview/${uploadedFile.id}/${uploadedFile.name}`).query(query); expect(response.status).toEqual(200); }); it('should return status 206 and required headers for the successful partial file stream download', async () => { - const { uploadedFile } = await setup(); + const { apiClient, uploadedFile } = await setup(); const query = { ...defaultQueryParameters, forceUpdate: false, }; - const response = await api.getPreviewBytesRange( - `/file/preview/${uploadedFile.id}/${uploadedFile.name}`, - 'bytes=0-', - query - ); + const response = await apiClient + .get(`/preview/${uploadedFile.id}/${uploadedFile.name}`) + .set('Range', 'bytes=0-') + .query(query); + const headers = response.headers as Record; expect(response.status).toEqual(206); - expect(response.headers['accept-ranges']).toMatch('bytes'); - expect(response.headers['content-range']).toMatch('bytes 0-3/4'); - expect(response.headers.etag).toMatch('testTag'); + expect(headers['accept-ranges']).toMatch('bytes'); + expect(headers['content-range']).toMatch('bytes 0-3/4'); + expect(headers.etag).toMatch('testTag'); }); }); describe('WHEN header contains not matching etag', () => { it('should return status 200 for successful download', async () => { - const { uploadedFile } = await setup(); + const { apiClient, uploadedFile } = await setup(); const query = { ...defaultQueryParameters, forceUpdate: false, }; const etag = 'otherTag'; - const response = await api.getPreviewWithEtag( - `/file/preview/${uploadedFile.id}/${uploadedFile.name}`, - etag, - query - ); + const response = await apiClient + .get(`/preview/${uploadedFile.id}/${uploadedFile.name}`) + .query(query) + .set('If-None-Match', etag); expect(response.status).toEqual(200); }); @@ -370,18 +338,17 @@ describe('File Controller (API) - preview', () => { describe('WHEN header contains matching etag', () => { it('should return status 304', async () => { - const { uploadedFile } = await setup(); + const { apiClient, uploadedFile } = await setup(); const query = { ...defaultQueryParameters, forceUpdate: false, }; const etag = 'testTag'; - const response = await api.getPreviewWithEtag( - `/file/preview/${uploadedFile.id}/${uploadedFile.name}`, - etag, - query - ); + const response = await apiClient + .get(`/preview/${uploadedFile.id}/${uploadedFile.name}`) + .query(query) + .set('If-None-Match', etag); expect(response.status).toEqual(304); }); @@ -390,83 +357,84 @@ describe('File Controller (API) - preview', () => { describe('WHEN forceUpdate is true', () => { const setup = async () => { - const { result: uploadedFile } = await api.postUploadFile(uploadPath); + const apiClient = await setupApiClient(); + const uploadedFile = await uploadFile(apiClient); await setScanStatus(uploadedFile.id, ScanStatus.VERIFIED); const previewFile = TestHelper.createFile({ contentRange: 'bytes 0-3/4' }); s3ClientAdapter.get.mockResolvedValueOnce(previewFile); - return { uploadedFile }; + return { apiClient, uploadedFile }; }; it('should return status 200 for successful download', async () => { - const { uploadedFile } = await setup(); + const { apiClient, uploadedFile } = await setup(); const query = { ...defaultQueryParameters, forceUpdate: true, }; - const response = await api.getPreview(`/file/preview/${uploadedFile.id}/${uploadedFile.name}`, query); + const response = await apiClient.get(`/preview/${uploadedFile.id}/${uploadedFile.name}`).query(query); expect(response.status).toEqual(200); }); it('should return status 206 and required headers for the successful partial file stream download', async () => { - const { uploadedFile } = await setup(); + const { apiClient, uploadedFile } = await setup(); const query = { ...defaultQueryParameters, forceUpdate: true, }; - const response = await api.getPreviewBytesRange( - `/file/preview/${uploadedFile.id}/${uploadedFile.name}`, - 'bytes=0-', - query - ); + const response = await apiClient + .get(`/preview/${uploadedFile.id}/${uploadedFile.name}`) + .set('Range', 'bytes=0-') + .query(query); + const headers = response.headers as Record; expect(response.status).toEqual(206); - expect(response.headers['accept-ranges']).toMatch('bytes'); - expect(response.headers['content-range']).toMatch('bytes 0-3/4'); - expect(response.headers.etag).toMatch('testTag'); + expect(headers['accept-ranges']).toMatch('bytes'); + expect(headers['content-range']).toMatch('bytes 0-3/4'); + expect(headers.etag).toMatch('testTag'); }); }); - }); - describe('WHEN preview does not already exist', () => { - const setup = async () => { - const { result: uploadedFile } = await api.postUploadFile(uploadPath); - await setScanStatus(uploadedFile.id, ScanStatus.VERIFIED); + describe('WHEN preview does not already exist', () => { + const setup = async () => { + const apiClient = await setupApiClient(); + const uploadedFile = await uploadFile(apiClient); + await setScanStatus(uploadedFile.id, ScanStatus.VERIFIED); - const error = new NotFoundException(); - const previewFile = TestHelper.createFile({ contentRange: 'bytes 0-3/4' }); - s3ClientAdapter.get.mockRejectedValueOnce(error).mockResolvedValueOnce(previewFile); + const error = new NotFoundException(); + const previewFile = TestHelper.createFile({ contentRange: 'bytes 0-3/4' }); + s3ClientAdapter.get.mockRejectedValueOnce(error).mockResolvedValueOnce(previewFile); - return { uploadedFile }; - }; + return { apiClient, uploadedFile }; + }; - it('should return status 200 for successful download', async () => { - const { uploadedFile } = await setup(); + it('should return status 200 for successful download', async () => { + const { apiClient, uploadedFile } = await setup(); - const response = await api.getPreview( - `/file/preview/${uploadedFile.id}/${uploadedFile.name}`, - defaultQueryParameters - ); + const response = await apiClient + .get(`/preview/${uploadedFile.id}/${uploadedFile.name}`) + .query(defaultQueryParameters); - expect(response.status).toEqual(200); - }); + expect(response.status).toEqual(200); + }); - it('should return status 206 and required headers for the successful partial file stream download', async () => { - const { uploadedFile } = await setup(); + it('should return status 206 and required headers for the successful partial file stream download', async () => { + const { apiClient, uploadedFile } = await setup(); - const response = await api.getPreviewBytesRange( - `/file/preview/${uploadedFile.id}/${uploadedFile.name}`, - 'bytes=0-', - defaultQueryParameters - ); + const response = await apiClient + .get(`/preview/${uploadedFile.id}/${uploadedFile.name}`) + .set('Range', 'bytes=0-') + .query(defaultQueryParameters); + const headers = response.headers as Record; - expect(response.status).toEqual(206); - expect(response.headers['accept-ranges']).toMatch('bytes'); - expect(response.headers['content-range']).toMatch('bytes 0-3/4'); + expect(response.status).toEqual(206); + expect(headers['accept-ranges']).toMatch('bytes'); + expect(headers['content-range']).toMatch('bytes 0-3/4'); + }); }); }); }); diff --git a/apps/server/src/modules/files-storage/controller/api-test/files-storage-rename-file.api.spec.ts b/apps/server/src/modules/files-storage/controller/api-test/files-storage-rename-file.api.spec.ts index 0f8ed070423..9b66ab6bf0c 100644 --- a/apps/server/src/modules/files-storage/controller/api-test/files-storage-rename-file.api.spec.ts +++ b/apps/server/src/modules/files-storage/controller/api-test/files-storage-rename-file.api.spec.ts @@ -1,68 +1,30 @@ import { createMock } from '@golevelup/ts-jest'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { AuthorizationClientAdapter } from '@infra/authorization-client'; import { EntityManager } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; -import { - cleanupCollections, - fileRecordFactory, - mapUserToCurrentUser, - schoolEntityFactory, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { JwtAuthenticationFactory } from '@testing/factory/jwt-authentication.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import NodeClam from 'clamscan'; -import { Request } from 'express'; -import request from 'supertest'; -import { FileRecord } from '../../entity'; import { FilesStorageTestModule } from '../../files-storage-test.module'; import { FileRecordParentType } from '../../interface'; -import { FileRecordResponse, RenameFileParams } from '../dto'; +import { FileRecordResponse } from '../dto'; -const baseRouteName = '/file/rename/'; - -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async patch(requestString: string, body?: RenameFileParams | Record) { - const response = await request(this.app.getHttpServer()) - .patch(`${baseRouteName}${requestString}`) - .set('Accept', 'application/json') - .send(body || {}); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} +const baseRouteName = '/file/rename'; describe(`${baseRouteName} (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; - let fileRecord: FileRecord; - let fileRecords: FileRecord[]; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [FilesStorageTestModule], }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .overrideProvider(NodeClam) .useValue(createMock()) .overrideProvider(AuthorizationClientAdapter) @@ -72,14 +34,13 @@ describe(`${baseRouteName} (api)`, () => { app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); - api = new API(app); }); afterAll(async () => { await app.close(); }); - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -91,50 +52,86 @@ describe(`${baseRouteName} (api)`, () => { parentId: school.id, parentType: FileRecordParentType.School, }; - fileRecords = fileRecordFactory.buildList(3, fileParams); - fileRecord = fileRecordFactory.build({ ...fileParams, name: 'test.txt', creatorId: user.id }); + const fileRecords = fileRecordFactory.buildList(3, fileParams); + const fileRecord = fileRecordFactory.build({ ...fileParams, name: 'test.txt', creatorId: user.id }); fileRecords.push(fileRecord); await em.persistAndFlush([user, ...fileRecords, school]); em.clear(); - currentUser = mapUserToCurrentUser(user); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + return { user, fileRecord, apiClient }; + }; + + describe('with not authenticated user', () => { + it('should return status 401', async () => { + const apiClient = new TestApiClient(app, baseRouteName); + + const result = await apiClient.patch(`invalid_id`, { fileName: 'test_new_name.txt' }); + + expect(result.status).toEqual(401); + }); }); describe('with bad request data', () => { it('should return status 400 for invalid fileRecordId', async () => { - const response = await api.patch(`invalid_id`, { fileName: 'test_new_name.txt' }); - expect(response.error.validationErrors).toEqual([ + const { apiClient } = await setup(); + + const result = await apiClient.patch(`invalid_id`, { fileName: 'test_new_name.txt' }); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['fileRecordId must be a mongodb id'], field: ['fileRecordId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for empty filename', async () => { - const response = await api.patch(`${fileRecord.id}`, { fileName: undefined }); - expect(response.error.validationErrors).toEqual([ + const { apiClient, fileRecord } = await setup(); + + const result = await apiClient.patch(`${fileRecord.id}`, { fileName: undefined }); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['fileName should not be empty', 'fileName must be a string'], field: ['fileName'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 409 if filename exists', async () => { - const response = await api.patch(`${fileRecord.id}`, { fileName: 'test.txt' }); - expect(response.error).toEqual({ code: 409, message: 'FILE_NAME_EXISTS', title: 'Conflict', type: 'CONFLICT' }); - expect(response.status).toEqual(409); + const { apiClient, fileRecord } = await setup(); + + const result = await apiClient.patch(`${fileRecord.id}`, { fileName: 'test.txt' }); + + expect(result.body).toEqual({ code: 409, message: 'FILE_NAME_EXISTS', title: 'Conflict', type: 'CONFLICT' }); + expect(result.status).toEqual(409); }); }); describe(`with valid request data`, () => { it('should return status 200 for successful request', async () => { - const response = await api.patch(`${fileRecord.id}`, { fileName: 'test_1.txt' }); - expect(response.result.name).toEqual('test_1.txt'); - expect(response.status).toEqual(200); + const { apiClient, fileRecord } = await setup(); + + const result = await apiClient.patch(`${fileRecord.id}`, { fileName: 'test_1.txt' }); + const response = result.body as FileRecordResponse; + + expect(response.name).toEqual('test_1.txt'); + expect(result.status).toEqual(200); }); }); }); diff --git a/apps/server/src/modules/files-storage/controller/api-test/files-storage-restore-files.api.spec.ts b/apps/server/src/modules/files-storage/controller/api-test/files-storage-restore-files.api.spec.ts index 1cd5d3bca0a..8954687d1f9 100644 --- a/apps/server/src/modules/files-storage/controller/api-test/files-storage-restore-files.api.spec.ts +++ b/apps/server/src/modules/files-storage/controller/api-test/files-storage-restore-files.api.spec.ts @@ -1,26 +1,20 @@ import { createMock } from '@golevelup/ts-jest'; import { AntivirusService } from '@infra/antivirus'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { AuthorizationClientAdapter } from '@infra/authorization-client'; import { S3ClientAdapter } from '@infra/s3-client'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; import { EntityId } from '@shared/domain/types'; -import { - cleanupCollections, - fileRecordFactory, - mapUserToCurrentUser, - roleFactory, - schoolEntityFactory, - UserAndAccountTestFactory, - userFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { JwtAuthenticationFactory } from '@testing/factory/jwt-authentication.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import NodeClam from 'clamscan'; -import { Request } from 'express'; import FileType from 'file-type-cjs/file-type-cjs-index'; -import request from 'supertest'; import { PreviewStatus } from '../../entity'; import { FilesStorageTestModule } from '../../files-storage-test.module'; import { FILES_STORAGE_S3_CONNECTION } from '../../files-storage.config'; @@ -28,7 +22,7 @@ import { FileRecordParentType } from '../../interface'; import { FileRecordListResponse, FileRecordResponse } from '../dto'; import { availableParentTypes } from './mocks'; -const baseRouteName = '/file/restore'; +const baseRouteName = '/file'; jest.mock('file-type-cjs/file-type-cjs-index', () => { return { @@ -36,83 +30,9 @@ jest.mock('file-type-cjs/file-type-cjs-index', () => { }; }); -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async postUploadFile(routeName: string, fileName: string) { - const response = await request(this.app.getHttpServer()) - .post(routeName) - .attach('file', Buffer.from('abcd'), fileName) - .set('connection', 'keep-alive') - .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async restoreFile(requestString: string) { - const response = await request(this.app.getHttpServer()) - .post(`${baseRouteName}${requestString}`) - .set('Accept', 'application/json'); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async restore(requestString: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .post(`${baseRouteName}${requestString}`) - .set('Accept', 'application/json') - .query(query || {}); - - return { - result: response.body as FileRecordListResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async deleteFile(requestString: string) { - const response = await request(this.app.getHttpServer()) - .delete(`/file/delete${requestString}`) - .set('Accept', 'application/json'); - - return { - result: response.body as FileRecordResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } - - async delete(requestString: string, query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .delete(`/file/delete${requestString}`) - .set('Accept', 'application/json') - .query(query || {}); - - return { - result: response.body as FileRecordListResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} - describe(`${baseRouteName} (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ @@ -122,14 +42,6 @@ describe(`${baseRouteName} (api)`, () => { .useValue(createMock()) .overrideProvider(FILES_STORAGE_S3_CONNECTION) .useValue(createMock()) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .overrideProvider(NodeClam) .useValue(createMock()) .overrideProvider(AuthorizationClientAdapter) @@ -139,7 +51,6 @@ describe(`${baseRouteName} (api)`, () => { app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); - api = new API(app); }); afterAll(async () => { @@ -147,60 +58,88 @@ describe(`${baseRouteName} (api)`, () => { }); describe('restore files of parent', () => { - describe('with bad request data', () => { - let validId: string; + describe('with not authenticated uer', () => { + it('should return status 401', async () => { + const apiClient = new TestApiClient(app, baseRouteName); + + const result = await apiClient.post(`/restore/school/123/users/123`); + + expect(result.status).toEqual(401); + }); + }); - beforeEach(async () => { + describe('with bad request data', () => { + const setup = async () => { await cleanupCollections(em); - const roles = roleFactory.buildList(1, { permissions: [] }); const school = schoolEntityFactory.build(); - const user = userFactory.build({ roles, school }); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); await em.persistAndFlush([user]); em.clear(); - currentUser = mapUserToCurrentUser(user); - validId = user.school.id; - }); + const validId = user.school.id; + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + return { validId, apiClient }; + }; it('should return status 400 for invalid schoolId', async () => { - const response = await api.restore(`/school/123/users/${validId}`); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId } = await setup(); + + const result = await apiClient.post(`/restore/school/123/users/${validId}`); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['storageLocationId must be a mongodb id'], field: ['storageLocationId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for invalid parentId', async () => { - const response = await api.restore(`/school/${validId}/users/123`); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId } = await setup(); + + const result = await apiClient.post(`/restore/school/${validId}/users/123`); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['parentId must be a mongodb id'], field: ['parentId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); it('should return status 400 for invalid parentType', async () => { - const response = await api.restore(`/school/${validId}/cookies/${validId}`); - expect(response.error.validationErrors).toEqual([ + const { apiClient, validId } = await setup(); + + const result = await apiClient.post(`/restore/school/${validId}/cookies/${validId}`); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: [`parentType must be one of the following values: ${availableParentTypes}`], field: ['parentType'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); }); describe(`with valid request data`, () => { - let validId: string; - - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -208,30 +147,56 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); - validId = user.school.id; + const validId = user.school.id; jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); - }); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + return { validId, apiClient }; + }; + + const uploadFile = async (apiClient: TestApiClient, path: string, fileName: string) => { + const result = await apiClient + .post(path) + .attach('file', Buffer.from('abcd'), fileName) + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20'); + + return result.body as FileRecordResponse; + }; it('should return status 200 for successful request', async () => { - await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test1.txt'); - await api.delete(`/school/${validId}/schools/${validId}`); + const { validId, apiClient } = await setup(); + await uploadFile(apiClient, `/upload/school/${validId}/schools/${validId}`, 'test1.txt'); - const response = await api.restore(`/school/${validId}/schools/${validId}`); + await apiClient.delete(`/school/${validId}/schools/${validId}`); + + const response = await apiClient.post(`/restore/school/${validId}/schools/${validId}`); expect(response.status).toEqual(201); }); it('should return right type of data', async () => { - await api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test1.txt'); - await api.delete(`/school/${validId}/schools/${validId}`); + const { validId, apiClient } = await setup(); + await uploadFile(apiClient, `/upload/school/${validId}/schools/${validId}`, 'test1.txt'); + + await apiClient.delete(`/delete/school/${validId}/schools/${validId}`); - const { result } = await api.restore(`/school/${validId}/schools/${validId}`); + const result = await apiClient.post(`/restore/school/${validId}/schools/${validId}`); + const response = result.body as FileRecordListResponse; - expect(Array.isArray(result.data)).toBe(true); - expect(result.data[0]).toBeDefined(); - expect(result.data[0]).toStrictEqual({ + expect(Array.isArray(response.data)).toBe(true); + expect(response.data[0]).toBeDefined(); + expect(response.data[0]).toStrictEqual({ creatorId: expect.any(String), id: expect.any(String), name: expect.any(String), @@ -248,25 +213,27 @@ describe(`${baseRouteName} (api)`, () => { }); it('should return elements of requested scope', async () => { + const { validId, apiClient } = await setup(); + const otherParentId = new ObjectId().toHexString(); - const uploadResponse = await Promise.all([ - api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test1.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test2.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${validId}`, 'test3.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${otherParentId}`, 'other1.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${otherParentId}`, 'other2.txt'), - api.postUploadFile(`/file/upload/school/${validId}/schools/${otherParentId}`, 'other3.txt'), + const fileRecords = await Promise.all([ + uploadFile(apiClient, `/upload/school/${validId}/schools/${validId}`, 'test1.txt'), + uploadFile(apiClient, `/upload/school/${validId}/schools/${validId}`, 'test2.txt'), + uploadFile(apiClient, `/upload/school/${validId}/schools/${validId}`, 'test3.txt'), + uploadFile(apiClient, `/upload/school/${validId}/schools/${otherParentId}`, 'other1.txt'), + uploadFile(apiClient, `/upload/school/${validId}/schools/${otherParentId}`, 'other3.txt'), + uploadFile(apiClient, `/upload/school/${validId}/schools/${otherParentId}`, 'other2.txt'), ]); - const fileRecords = uploadResponse.map(({ result }) => result); - await api.delete(`/school/${validId}/schools/${validId}`); + await apiClient.delete(`/delete/school/${validId}/schools/${validId}`); - const { result } = await api.restore(`/school/${validId}/schools/${validId}`); + const result = await apiClient.post(`/restore/school/${validId}/schools/${validId}`); + const response = result.body as FileRecordListResponse; - const resultData: FileRecordResponse[] = result.data; + const resultData: FileRecordResponse[] = response.data; const ids: EntityId[] = resultData.map((o) => o.id); - expect(result.total).toEqual(3); + expect(response.total).toEqual(3); expect(ids.sort()).toEqual([fileRecords[0].id, fileRecords[1].id, fileRecords[2].id].sort()); }); }); @@ -274,32 +241,47 @@ describe(`${baseRouteName} (api)`, () => { describe('restore single file', () => { describe('with bad request data', () => { - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); - const roles = roleFactory.buildList(1, { permissions: [] }); const school = schoolEntityFactory.build(); - const user = userFactory.build({ roles, school }); + const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); await em.persistAndFlush([user]); em.clear(); - }); + + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); + + return { apiClient }; + }; it('should return status 400 for invalid fileRecordId', async () => { - const response = await api.restoreFile(`/123`); - expect(response.error.validationErrors).toEqual([ + const { apiClient } = await setup(); + + const result = await apiClient.post(`/restore/123`); + const { validationErrors } = result.body as ApiValidationError; + + expect(validationErrors).toEqual([ { errors: ['fileRecordId must be a mongodb id'], field: ['fileRecordId'], }, ]); - expect(response.status).toEqual(400); + expect(result.status).toEqual(400); }); }); describe(`with valid request data`, () => { let fileRecordId: string; - beforeEach(async () => { + const setup = async () => { await cleanupCollections(em); const school = schoolEntityFactory.build(); const { studentUser: user, studentAccount: account } = UserAndAccountTestFactory.buildStudent({ school }); @@ -307,30 +289,50 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush([user, account]); em.clear(); - currentUser = mapUserToCurrentUser(user); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: account.id, + userId: user.id, + schoolId: user.school.id, + roles: [user.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, baseRouteName, authValue); - const { result } = await api.postUploadFile( - `/file/upload/school/${school.id}/schools/${school.id}`, - 'test1.txt' - ); + const result = ( + await apiClient + .post(`/upload/school/${school.id}/schools/${school.id}`) + .attach('file', Buffer.from('abcd'), 'test1.txt') + .set('connection', 'keep-alive') + .set('content-type', 'multipart/form-data; boundary=----WebKitFormBoundaryiBMuOC0HyZ3YnA20') + ).body as FileRecordResponse; fileRecordId = result.id; jest.spyOn(FileType, 'fileTypeStream').mockImplementation((readable) => Promise.resolve(readable)); - }); + + return { apiClient }; + }; it('should return status 200 for successful request', async () => { - await api.deleteFile(`/${fileRecordId}`); - const response = await api.restoreFile(`/${fileRecordId}`); + const { apiClient } = await setup(); + + await apiClient.delete(`/delete/${fileRecordId}`); + + const response = await apiClient.post(`/restore/${fileRecordId}`); expect(response.status).toEqual(201); }); it('should return right type of data', async () => { - await api.deleteFile(`/${fileRecordId}`); - const { result } = await api.restoreFile(`/${fileRecordId}`); + const { apiClient } = await setup(); + + await apiClient.delete(`/delete/${fileRecordId}`); - expect(result).toStrictEqual({ + const result = await apiClient.post(`/restore/${fileRecordId}`); + const response = result.body as FileRecordResponse; + + expect(response).toStrictEqual({ creatorId: expect.any(String), id: expect.any(String), name: expect.any(String), @@ -347,6 +349,7 @@ describe(`${baseRouteName} (api)`, () => { }); it('should return elements of requested scope', async () => { + const { apiClient } = await setup(); const otherFileRecords = fileRecordFactory.buildList(3, { parentType: FileRecordParentType.School, }); @@ -354,10 +357,12 @@ describe(`${baseRouteName} (api)`, () => { await em.persistAndFlush(otherFileRecords); em.clear(); - await api.deleteFile(`/${fileRecordId}`); - const { result } = await api.restoreFile(`/${fileRecordId}`); + await apiClient.delete(`/delete/${fileRecordId}`); + + const result = await apiClient.post(`/restore/${fileRecordId}`); + const response = result.body as FileRecordResponse; - expect(result.id).toEqual(fileRecordId); + expect(response.id).toEqual(fileRecordId); }); }); }); diff --git a/apps/server/src/modules/files-storage/controller/api-test/files-storage.config.api.spec.ts b/apps/server/src/modules/files-storage/controller/api-test/files-storage.config.api.spec.ts index d84d50e520f..494a7986d94 100644 --- a/apps/server/src/modules/files-storage/controller/api-test/files-storage.config.api.spec.ts +++ b/apps/server/src/modules/files-storage/controller/api-test/files-storage.config.api.spec.ts @@ -3,8 +3,8 @@ import { AntivirusService } from '@infra/antivirus'; import { S3ClientAdapter } from '@infra/s3-client'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; +import { TestApiClient } from '@testing/test-api-client'; import NodeClam from 'clamscan'; -import { TestApiClient } from '@shared/testing'; import { FilesStorageTestModule } from '../../files-storage-test.module'; import { FILES_STORAGE_S3_CONNECTION } from '../../files-storage.config'; diff --git a/apps/server/src/modules/files-storage/controller/files-storage.consumer.spec.ts b/apps/server/src/modules/files-storage/controller/files-storage.consumer.spec.ts index bdbe80d7f49..c00d9dd432e 100644 --- a/apps/server/src/modules/files-storage/controller/files-storage.consumer.spec.ts +++ b/apps/server/src/modules/files-storage/controller/files-storage.consumer.spec.ts @@ -4,8 +4,10 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { ALL_ENTITIES } from '@shared/domain/entity'; import { EntityId } from '@shared/domain/types'; -import { courseFactory, fileRecordFactory, setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { courseFactory } from '@testing/factory/course.factory'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecord } from '../entity'; import { FileRecordParentType, StorageLocation } from '../interface'; import { FilesStorageService } from '../service/files-storage.service'; diff --git a/apps/server/src/modules/files-storage/entity/filerecord.entity.spec.ts b/apps/server/src/modules/files-storage/entity/filerecord.entity.spec.ts index 40ae6e81847..7b56434c053 100644 --- a/apps/server/src/modules/files-storage/entity/filerecord.entity.spec.ts +++ b/apps/server/src/modules/files-storage/entity/filerecord.entity.spec.ts @@ -1,7 +1,8 @@ import { PreviewInputMimeTypes } from '@infra/preview-generator'; import { ObjectId } from '@mikro-orm/mongodb'; import { BadRequestException } from '@nestjs/common'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ErrorType } from '../error'; import { FileRecordParentType, StorageLocation } from '../interface'; import { diff --git a/apps/server/src/modules/files-storage/helper/file-name.spec.ts b/apps/server/src/modules/files-storage/helper/file-name.spec.ts index 6c1e776ec44..2631f75d0fc 100644 --- a/apps/server/src/modules/files-storage/helper/file-name.spec.ts +++ b/apps/server/src/modules/files-storage/helper/file-name.spec.ts @@ -1,6 +1,7 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { EntityId } from '@shared/domain/types'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import crypto from 'crypto'; import { createPreviewNameHash, hasDuplicateName, resolveFileNameDuplicates } from '.'; import { FileRecord } from '../entity'; diff --git a/apps/server/src/modules/files-storage/helper/file-record.spec.ts b/apps/server/src/modules/files-storage/helper/file-record.spec.ts index 9636bf41303..b0b58c68f06 100644 --- a/apps/server/src/modules/files-storage/helper/file-record.spec.ts +++ b/apps/server/src/modules/files-storage/helper/file-record.spec.ts @@ -1,6 +1,7 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { EntityId } from '@shared/domain/types'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { createFileRecord, getFormat, getPreviewName, markForDelete, unmarkForDelete } from '.'; import { FileRecordParams } from '../controller/dto'; import { FileRecord } from '../entity'; diff --git a/apps/server/src/modules/files-storage/helper/path.spec.ts b/apps/server/src/modules/files-storage/helper/path.spec.ts index 862cef3ed24..f480b6b16b0 100644 --- a/apps/server/src/modules/files-storage/helper/path.spec.ts +++ b/apps/server/src/modules/files-storage/helper/path.spec.ts @@ -1,6 +1,7 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { EntityId } from '@shared/domain/types'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { createCopyFiles, createPath, createPreviewDirectoryPath, createPreviewFilePath, getPaths } from '.'; import { FileRecord } from '../entity'; import { ErrorType } from '../error'; diff --git a/apps/server/src/modules/files-storage/mapper/file-dto.builder.spec.ts b/apps/server/src/modules/files-storage/mapper/file-dto.builder.spec.ts index 884c1afe47f..10f4846c35b 100644 --- a/apps/server/src/modules/files-storage/mapper/file-dto.builder.spec.ts +++ b/apps/server/src/modules/files-storage/mapper/file-dto.builder.spec.ts @@ -1,5 +1,5 @@ import { createMock } from '@golevelup/ts-jest'; -import { fileRecordFactory } from '@shared/testing'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; import { AxiosResponse } from 'axios'; import { Readable } from 'stream'; import { FileDto } from '../dto'; diff --git a/apps/server/src/modules/files-storage/mapper/file-record.mapper.spec.ts b/apps/server/src/modules/files-storage/mapper/file-record.mapper.spec.ts index 2de136cdc55..9aaf3983eb9 100644 --- a/apps/server/src/modules/files-storage/mapper/file-record.mapper.spec.ts +++ b/apps/server/src/modules/files-storage/mapper/file-record.mapper.spec.ts @@ -1,4 +1,5 @@ -import { fileRecordFactory, setupEntities } from '@shared/testing'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordListResponse, FileRecordResponse, ScanResultDto, ScanResultParams } from '../controller/dto'; import { FileRecord, ScanStatus } from '../entity'; import { FileRecordMapper } from './file-record.mapper'; diff --git a/apps/server/src/modules/files-storage/mapper/files-storage.mapper.spec.ts b/apps/server/src/modules/files-storage/mapper/files-storage.mapper.spec.ts index 5ec8f2553d2..de3ee3e9b46 100644 --- a/apps/server/src/modules/files-storage/mapper/files-storage.mapper.spec.ts +++ b/apps/server/src/modules/files-storage/mapper/files-storage.mapper.spec.ts @@ -1,6 +1,7 @@ import { AuthorizableReferenceType } from '@modules/authorization/domain'; import { NotImplementedException } from '@nestjs/common'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { DownloadFileParams, FileRecordListResponse, diff --git a/apps/server/src/modules/files-storage/mapper/preview.builder.spec.ts b/apps/server/src/modules/files-storage/mapper/preview.builder.spec.ts index 1a3cc843f86..c1397560df3 100644 --- a/apps/server/src/modules/files-storage/mapper/preview.builder.spec.ts +++ b/apps/server/src/modules/files-storage/mapper/preview.builder.spec.ts @@ -1,4 +1,4 @@ -import { fileRecordFactory } from '@shared/testing'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; import { PreviewOutputMimeTypes } from '../interface'; import { PreviewBuilder } from './preview.builder'; diff --git a/apps/server/src/modules/files-storage/repo/filerecord.repo.integration.spec.ts b/apps/server/src/modules/files-storage/repo/filerecord.repo.integration.spec.ts index 11ee5294ceb..a3dabda4447 100644 --- a/apps/server/src/modules/files-storage/repo/filerecord.repo.integration.spec.ts +++ b/apps/server/src/modules/files-storage/repo/filerecord.repo.integration.spec.ts @@ -1,7 +1,8 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, fileRecordFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; import { FileRecord } from '../entity'; import { FileRecordParentType, StorageLocation } from '../interface'; diff --git a/apps/server/src/modules/files-storage/service/files-storage-copy.service.spec.ts b/apps/server/src/modules/files-storage/service/files-storage-copy.service.spec.ts index 43293736796..36fe2584833 100644 --- a/apps/server/src/modules/files-storage/service/files-storage-copy.service.spec.ts +++ b/apps/server/src/modules/files-storage/service/files-storage-copy.service.spec.ts @@ -4,8 +4,9 @@ import { S3ClientAdapter } from '@infra/s3-client'; import { ObjectId } from '@mikro-orm/mongodb'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams } from '../controller/dto'; import { FileRecord, ScanStatus } from '../entity'; import { FILES_STORAGE_S3_CONNECTION } from '../files-storage.config'; diff --git a/apps/server/src/modules/files-storage/service/files-storage-delete.service.spec.ts b/apps/server/src/modules/files-storage/service/files-storage-delete.service.spec.ts index a8e789568c5..7c5b2754a1f 100644 --- a/apps/server/src/modules/files-storage/service/files-storage-delete.service.spec.ts +++ b/apps/server/src/modules/files-storage/service/files-storage-delete.service.spec.ts @@ -5,8 +5,9 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { InternalServerErrorException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FILES_STORAGE_S3_CONNECTION } from '../files-storage.config'; diff --git a/apps/server/src/modules/files-storage/service/files-storage-download.service.spec.ts b/apps/server/src/modules/files-storage/service/files-storage-download.service.spec.ts index c7202bbf7d5..0b2c423f2d2 100644 --- a/apps/server/src/modules/files-storage/service/files-storage-download.service.spec.ts +++ b/apps/server/src/modules/files-storage/service/files-storage-download.service.spec.ts @@ -5,8 +5,9 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { NotAcceptableException, NotFoundException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams } from '../controller/dto'; import { FileRecord, ScanStatus } from '../entity'; import { ErrorType } from '../error'; diff --git a/apps/server/src/modules/files-storage/service/files-storage-get.service.spec.ts b/apps/server/src/modules/files-storage/service/files-storage-get.service.spec.ts index aedb99e7089..6b73b64af48 100644 --- a/apps/server/src/modules/files-storage/service/files-storage-get.service.spec.ts +++ b/apps/server/src/modules/files-storage/service/files-storage-get.service.spec.ts @@ -4,8 +4,9 @@ import { S3ClientAdapter } from '@infra/s3-client'; import { ObjectId } from '@mikro-orm/mongodb'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams, SingleFileParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FILES_STORAGE_S3_CONNECTION } from '../files-storage.config'; diff --git a/apps/server/src/modules/files-storage/service/files-storage-remove-creator.service.spec.ts b/apps/server/src/modules/files-storage/service/files-storage-remove-creator.service.spec.ts index 41dfcd95403..ddf4c050693 100644 --- a/apps/server/src/modules/files-storage/service/files-storage-remove-creator.service.spec.ts +++ b/apps/server/src/modules/files-storage/service/files-storage-remove-creator.service.spec.ts @@ -4,8 +4,9 @@ import { S3ClientAdapter } from '@infra/s3-client'; import { ObjectId } from '@mikro-orm/mongodb'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FILES_STORAGE_S3_CONNECTION } from '../files-storage.config'; diff --git a/apps/server/src/modules/files-storage/service/files-storage-restore.service.spec.ts b/apps/server/src/modules/files-storage/service/files-storage-restore.service.spec.ts index b1a2c91eedf..c50ed14d720 100644 --- a/apps/server/src/modules/files-storage/service/files-storage-restore.service.spec.ts +++ b/apps/server/src/modules/files-storage/service/files-storage-restore.service.spec.ts @@ -4,8 +4,9 @@ import { S3ClientAdapter } from '@infra/s3-client'; import { ObjectId } from '@mikro-orm/mongodb'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FILES_STORAGE_S3_CONNECTION } from '../files-storage.config'; diff --git a/apps/server/src/modules/files-storage/service/files-storage-update.service.spec.ts b/apps/server/src/modules/files-storage/service/files-storage-update.service.spec.ts index 5b6e5be7095..5158396aa02 100644 --- a/apps/server/src/modules/files-storage/service/files-storage-update.service.spec.ts +++ b/apps/server/src/modules/files-storage/service/files-storage-update.service.spec.ts @@ -5,8 +5,9 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { ConflictException, NotFoundException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import _ from 'lodash'; import { FileRecordParams, RenameFileParams, ScanResultParams, SingleFileParams } from '../controller/dto'; import { FileRecord } from '../entity'; diff --git a/apps/server/src/modules/files-storage/service/files-storage-upload.service.spec.ts b/apps/server/src/modules/files-storage/service/files-storage-upload.service.spec.ts index 9a24c975c13..b16bcf8f850 100644 --- a/apps/server/src/modules/files-storage/service/files-storage-upload.service.spec.ts +++ b/apps/server/src/modules/files-storage/service/files-storage-upload.service.spec.ts @@ -5,9 +5,10 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { BadRequestException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; -import { readableStreamWithFileTypeFactory } from '@shared/testing/factory/readable-stream-with-file-type.factory'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { readableStreamWithFileTypeFactory } from '@testing/factory/readable-stream-with-file-type.factory'; +import { setupEntities } from '@testing/setup-entities'; import { MimeType } from 'file-type'; import FileType from 'file-type-cjs/file-type-cjs-index'; import { PassThrough, Readable } from 'stream'; diff --git a/apps/server/src/modules/files-storage/service/preview.service.spec.ts b/apps/server/src/modules/files-storage/service/preview.service.spec.ts index b96213f170d..365ead83505 100644 --- a/apps/server/src/modules/files-storage/service/preview.service.spec.ts +++ b/apps/server/src/modules/files-storage/service/preview.service.spec.ts @@ -4,8 +4,9 @@ import { S3ClientAdapter } from '@infra/s3-client'; import { ObjectId } from '@mikro-orm/mongodb'; import { NotFoundException, UnprocessableEntityException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams } from '../controller/dto'; import { FileRecord, ScanStatus } from '../entity'; import { ErrorType } from '../error'; diff --git a/apps/server/src/modules/files-storage/uc/files-storage-copy.uc.spec.ts b/apps/server/src/modules/files-storage/uc/files-storage-copy.uc.spec.ts index e3b623e11db..3339ff0b25d 100644 --- a/apps/server/src/modules/files-storage/uc/files-storage-copy.uc.spec.ts +++ b/apps/server/src/modules/files-storage/uc/files-storage-copy.uc.spec.ts @@ -8,9 +8,10 @@ import { HttpService } from '@nestjs/axios'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { EntityId } from '@shared/domain/types'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { DomainErrorHandler } from '@src/core'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CopyFilesOfParentParams, FileRecordParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FileStorageAuthorizationContext } from '../files-storage.const'; diff --git a/apps/server/src/modules/files-storage/uc/files-storage-delete.uc.spec.ts b/apps/server/src/modules/files-storage/uc/files-storage-delete.uc.spec.ts index 8213b6132a8..8d10e3c187f 100644 --- a/apps/server/src/modules/files-storage/uc/files-storage-delete.uc.spec.ts +++ b/apps/server/src/modules/files-storage/uc/files-storage-delete.uc.spec.ts @@ -8,9 +8,10 @@ import { HttpService } from '@nestjs/axios'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Counted, EntityId } from '@shared/domain/types'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { DomainErrorHandler } from '@src/core'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FileStorageAuthorizationContext } from '../files-storage.const'; diff --git a/apps/server/src/modules/files-storage/uc/files-storage-download-preview.uc.spec.ts b/apps/server/src/modules/files-storage/uc/files-storage-download-preview.uc.spec.ts index eeede8b551e..55ca0f819ad 100644 --- a/apps/server/src/modules/files-storage/uc/files-storage-download-preview.uc.spec.ts +++ b/apps/server/src/modules/files-storage/uc/files-storage-download-preview.uc.spec.ts @@ -7,9 +7,10 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { HttpService } from '@nestjs/axios'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { DomainErrorHandler } from '@src/core'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SingleFileParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FileStorageAuthorizationContext } from '../files-storage.const'; diff --git a/apps/server/src/modules/files-storage/uc/files-storage-download.uc.spec.ts b/apps/server/src/modules/files-storage/uc/files-storage-download.uc.spec.ts index c2597e11b6a..3936cdc1b21 100644 --- a/apps/server/src/modules/files-storage/uc/files-storage-download.uc.spec.ts +++ b/apps/server/src/modules/files-storage/uc/files-storage-download.uc.spec.ts @@ -7,9 +7,10 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { HttpService } from '@nestjs/axios'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { DomainErrorHandler } from '@src/core'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SingleFileParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FileStorageAuthorizationContext } from '../files-storage.const'; diff --git a/apps/server/src/modules/files-storage/uc/files-storage-get.uc.spec.ts b/apps/server/src/modules/files-storage/uc/files-storage-get.uc.spec.ts index 6305938c159..c28369d875e 100644 --- a/apps/server/src/modules/files-storage/uc/files-storage-get.uc.spec.ts +++ b/apps/server/src/modules/files-storage/uc/files-storage-get.uc.spec.ts @@ -6,9 +6,10 @@ import { EntityManager } from '@mikro-orm/core'; import { ObjectId } from '@mikro-orm/mongodb'; import { HttpService } from '@nestjs/axios'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { DomainErrorHandler } from '@src/core'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FileStorageAuthorizationContext } from '../files-storage.const'; diff --git a/apps/server/src/modules/files-storage/uc/files-storage-restore.uc.spec.ts b/apps/server/src/modules/files-storage/uc/files-storage-restore.uc.spec.ts index d463f4b14a6..1e27767f9c8 100644 --- a/apps/server/src/modules/files-storage/uc/files-storage-restore.uc.spec.ts +++ b/apps/server/src/modules/files-storage/uc/files-storage-restore.uc.spec.ts @@ -7,9 +7,10 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { HttpService } from '@nestjs/axios'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { DomainErrorHandler } from '@src/core'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileRecordParams, SingleFileParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FileStorageAuthorizationContext } from '../files-storage.const'; diff --git a/apps/server/src/modules/files-storage/uc/files-storage-update.uc.spec.ts b/apps/server/src/modules/files-storage/uc/files-storage-update.uc.spec.ts index db8d340e11e..4d669f26252 100644 --- a/apps/server/src/modules/files-storage/uc/files-storage-update.uc.spec.ts +++ b/apps/server/src/modules/files-storage/uc/files-storage-update.uc.spec.ts @@ -6,9 +6,10 @@ import { EntityManager } from '@mikro-orm/core'; import { ObjectId } from '@mikro-orm/mongodb'; import { HttpService } from '@nestjs/axios'; import { Test, TestingModule } from '@nestjs/testing'; -import { fileRecordFactory, setupEntities } from '@shared/testing'; import { DomainErrorHandler } from '@src/core'; import { LegacyLogger } from '@src/core/logger'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { RenameFileParams, ScanResultParams, SingleFileParams } from '../controller/dto'; import { FileRecord } from '../entity'; import { FileStorageAuthorizationContext } from '../files-storage.const'; diff --git a/apps/server/src/modules/files-storage/uc/files-storage-upload.uc.spec.ts b/apps/server/src/modules/files-storage/uc/files-storage-upload.uc.spec.ts index cf395fa9752..ccb41b4e21b 100644 --- a/apps/server/src/modules/files-storage/uc/files-storage-upload.uc.spec.ts +++ b/apps/server/src/modules/files-storage/uc/files-storage-upload.uc.spec.ts @@ -9,9 +9,11 @@ import { HttpService } from '@nestjs/axios'; import { ForbiddenException, NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { AxiosHeadersKeyValue, axiosResponseFactory, fileRecordFactory, setupEntities } from '@shared/testing'; import { DomainErrorHandler } from '@src/core'; import { LegacyLogger } from '@src/core/logger'; +import { AxiosHeadersKeyValue, axiosResponseFactory } from '@testing/factory/axios-response.factory'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { setupEntities } from '@testing/setup-entities'; import { AxiosRequestConfig, AxiosResponse } from 'axios'; import { Request } from 'express'; import { of } from 'rxjs'; diff --git a/apps/server/src/modules/files/entity/file.entity.spec.ts b/apps/server/src/modules/files/entity/file.entity.spec.ts index bf52769f32b..0215bead157 100644 --- a/apps/server/src/modules/files/entity/file.entity.spec.ts +++ b/apps/server/src/modules/files/entity/file.entity.spec.ts @@ -1,9 +1,10 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { setupEntities, storageProviderFactory } from '@shared/testing'; import { FileOwnerModel } from '@modules/files/domain'; -import { fileEntityFactory, filePermissionEntityFactory } from './testing'; -import { FileEntity } from './file.entity'; +import { storageProviderFactory } from '@testing/factory/storageprovider.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FileSecurityCheckEntity } from './file-security-check.entity'; +import { FileEntity } from './file.entity'; +import { fileEntityFactory, filePermissionEntityFactory } from './testing'; describe(FileEntity.name, () => { const storageProvider = storageProviderFactory.buildWithId(); diff --git a/apps/server/src/modules/files/entity/testing/factory/file-entity.factory.ts b/apps/server/src/modules/files/entity/testing/factory/file-entity.factory.ts index 00f07dd04c7..11a90811d47 100644 --- a/apps/server/src/modules/files/entity/testing/factory/file-entity.factory.ts +++ b/apps/server/src/modules/files/entity/testing/factory/file-entity.factory.ts @@ -1,5 +1,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory, storageProviderFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; +import { storageProviderFactory } from '@testing/factory/storageprovider.factory'; import { FileEntity, FileEntityProps } from '../..'; import { FileOwnerModel } from '../../../domain'; import { filePermissionEntityFactory } from './file-permission-entity.factory'; diff --git a/apps/server/src/modules/files/entity/testing/factory/file-permission-entity.factory.ts b/apps/server/src/modules/files/entity/testing/factory/file-permission-entity.factory.ts index e0eebb815ff..fe3339b1949 100644 --- a/apps/server/src/modules/files/entity/testing/factory/file-permission-entity.factory.ts +++ b/apps/server/src/modules/files/entity/testing/factory/file-permission-entity.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { FilePermissionEntity, FilePermissionEntityProps } from '../..'; import { FilePermissionReferenceModel } from '../../../domain'; diff --git a/apps/server/src/modules/files/service/files.service.spec.ts b/apps/server/src/modules/files/service/files.service.spec.ts index 7473170636d..362b1badd54 100644 --- a/apps/server/src/modules/files/service/files.service.spec.ts +++ b/apps/server/src/modules/files/service/files.service.spec.ts @@ -11,8 +11,8 @@ import { import { deletionRequestFactory } from '@modules/deletion/domain/testing'; import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { setupEntities } from '@testing/setup-entities'; import { FileEntity } from '../entity'; import { fileEntityFactory, filePermissionEntityFactory } from '../entity/testing'; import { FilesRepo } from '../repo'; diff --git a/apps/server/src/modules/files/uc/delete-files.uc.spec.ts b/apps/server/src/modules/files/uc/delete-files.uc.spec.ts index f3a22162355..2362748861f 100644 --- a/apps/server/src/modules/files/uc/delete-files.uc.spec.ts +++ b/apps/server/src/modules/files/uc/delete-files.uc.spec.ts @@ -1,12 +1,12 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { Test, TestingModule } from '@nestjs/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { Test, TestingModule } from '@nestjs/testing'; import { StorageProviderRepo } from '@shared/repo/storageprovider'; -import { storageProviderFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; -import { DeleteFilesUc } from './delete-files.uc'; -import { FilesRepo } from '../repo'; +import { storageProviderFactory } from '@testing/factory/storageprovider.factory'; import { fileEntityFactory, filePermissionEntityFactory } from '../entity/testing'; +import { FilesRepo } from '../repo'; +import { DeleteFilesUc } from './delete-files.uc'; describe(DeleteFilesUc.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/fwu-learning-contents/controller/api-test/fwu-learning-contents.api.spec.ts b/apps/server/src/modules/fwu-learning-contents/controller/api-test/fwu-learning-contents.api.spec.ts index 62f4955edab..f7f3018f7d9 100644 --- a/apps/server/src/modules/fwu-learning-contents/controller/api-test/fwu-learning-contents.api.spec.ts +++ b/apps/server/src/modules/fwu-learning-contents/controller/api-test/fwu-learning-contents.api.spec.ts @@ -1,43 +1,24 @@ -import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Configuration } from '@hpi-schul-cloud/commons/lib'; -import { JwtAuthGuard } from '@infra/auth-guard'; import { S3ClientAdapter } from '@infra/s3-client'; import { INestApplication, NotFoundException } from '@nestjs/common'; import { Test } from '@nestjs/testing'; +import { JwtAuthenticationFactory } from '@testing/factory/jwt-authentication.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { Readable } from 'stream'; -import request from 'supertest'; import { FwuLearningContentsTestModule } from '../../fwu-learning-contents-test.module'; import { FWU_CONTENT_S3_CONNECTION } from '../../fwu-learning-contents.config'; -class API { - constructor(private app: INestApplication) { - this.app = app; - } - - async get(path: string) { - return request(this.app.getHttpServer()).get(`/fwu/${path}`); - } - - async getBytesRange(path: string, bytesRange: string) { - return request(this.app.getHttpServer()).get(`/fwu/${path}`).set('Range', bytesRange); - } -} - describe('FwuLearningContents Controller (api)', () => { let app: INestApplication; - let api: API; let s3ClientAdapter: DeepMocked; beforeAll(async () => { const module = await Test.createTestingModule({ imports: [FwuLearningContentsTestModule], }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate() { - return true; - }, - }) .overrideProvider(FWU_CONTENT_S3_CONNECTION) .useValue(createMock()) .compile(); @@ -45,8 +26,6 @@ describe('FwuLearningContents Controller (api)', () => { app = module.createNestApplication(); await app.init(); s3ClientAdapter = module.get(FWU_CONTENT_S3_CONNECTION); - - api = new API(app); }); afterAll(async () => { @@ -55,6 +34,23 @@ describe('FwuLearningContents Controller (api)', () => { describe('requestFwuContent', () => { Configuration.set('FEATURE_FWU_CONTENT_ENABLED', true); + + describe('when user is not authenticated', () => { + const setup = () => { + const apiClient = new TestApiClient(app, '/fwu'); + + return { apiClient }; + }; + + it('should return 401 status', async () => { + const { apiClient } = setup(); + + const response = await apiClient.get('12345/example.txt'); + + expect(response.status).toEqual(401); + }); + }); + describe('when the file has a file-extension', () => { const setup = () => { const path = '12345/example.txt'; @@ -71,59 +67,109 @@ describe('FwuLearningContents Controller (api)', () => { s3ClientAdapter.get.mockResolvedValueOnce(fileResponse); - return { path, fileResponse, text }; + const school = schoolEntityFactory.build(); + const { studentUser, studentAccount } = UserAndAccountTestFactory.buildStudent({ school }); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: studentAccount.id, + userId: studentUser.id, + schoolId: studentUser.school.id, + roles: [studentUser.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, '/fwu', authValue); + + return { path, fileResponse, text, apiClient }; }; it('should return 200 status', async () => { - const { path } = setup(); + const { path, apiClient } = setup(); + + const response = await apiClient.get(path); - const response = await api.get(path); expect(response.status).toEqual(200); }); it('should return 206 status (bytesRange)', async () => { - const { path } = setup(); + const { path, apiClient } = setup(); + + const response = await apiClient.get(path).set('Range', '12345'); - const response = await api.getBytesRange(path, '12345'); expect(response.status).toEqual(206); }); it('should return file content', async () => { - const { path, text } = setup(); + const { path, text, apiClient } = setup(); - const response = await api.get(path); + const response = await apiClient.get(path); expect(response.text).toEqual(text); }); it('should have the correct content-type', async () => { - const { path, fileResponse } = setup(); + const { path, fileResponse, apiClient } = setup(); - const response = await api.get(path); + const response = await apiClient.get(path); expect(response.type).toEqual(fileResponse.contentType); }); }); + describe('when the file does not exist', () => { const setup = () => { const error = new NotFoundException('NoSuchKey'); s3ClientAdapter.get.mockRejectedValueOnce(error); + + const school = schoolEntityFactory.build(); + const { studentUser, studentAccount } = UserAndAccountTestFactory.buildStudent({ school }); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: studentAccount.id, + userId: studentUser.id, + schoolId: studentUser.school.id, + roles: [studentUser.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, '/fwu', authValue); + + return { apiClient }; }; it('should return 404 error', async () => { - setup(); + const { apiClient } = setup(); - const response = await api.get('1234/NotAValidKey.html'); + const response = await apiClient.get('1234/NotAValidKey.html'); expect(response.status).toEqual(404); }); }); describe('when the feature is disabled', () => { + const setup = () => { + const error = new NotFoundException('NoSuchKey'); + s3ClientAdapter.get.mockRejectedValueOnce(error); + + const school = schoolEntityFactory.build(); + const { studentUser, studentAccount } = UserAndAccountTestFactory.buildStudent({ school }); + const authValue = JwtAuthenticationFactory.createJwt({ + accountId: studentAccount.id, + userId: studentUser.id, + schoolId: studentUser.school.id, + roles: [studentUser.roles[0].id], + support: false, + isExternalUser: false, + }); + const apiClient = new TestApiClient(app, '/fwu', authValue); + + return { apiClient }; + }; + it('should return InternalServerErrorException', async () => { + const { apiClient } = setup(); + Configuration.set('FEATURE_FWU_CONTENT_ENABLED', false); - const response = await api.get('12345/example.txt'); + const response = await apiClient.get('12345/example.txt'); expect(response.status).toEqual(500); }); diff --git a/apps/server/src/modules/fwu-learning-contents/fwu-learning-contents-test.module.ts b/apps/server/src/modules/fwu-learning-contents/fwu-learning-contents-test.module.ts index e8c02d83ba9..a68bebc5cbc 100644 --- a/apps/server/src/modules/fwu-learning-contents/fwu-learning-contents-test.module.ts +++ b/apps/server/src/modules/fwu-learning-contents/fwu-learning-contents-test.module.ts @@ -1,3 +1,4 @@ +import { AuthGuardModule, AuthGuardOptions } from '@infra/auth-guard'; import { MongoMemoryDatabaseModule } from '@infra/database'; import { MongoDatabaseModuleOptions } from '@infra/database/mongo-memory-database/types'; import { RabbitMQWrapperTestModule } from '@infra/rabbitmq'; @@ -27,6 +28,7 @@ const imports = [ LoggerModule, RabbitMQWrapperTestModule, S3ClientModule.register([s3Config]), + AuthGuardModule.register([AuthGuardOptions.JWT]), ]; const controllers = [FwuLearningContentsController]; const providers = [FwuLearningContentsUc]; diff --git a/apps/server/src/modules/group/controller/api-test/group.api.spec.ts b/apps/server/src/modules/group/controller/api-test/group.api.spec.ts index be8bc94c718..9b682507254 100644 --- a/apps/server/src/modules/group/controller/api-test/group.api.spec.ts +++ b/apps/server/src/modules/group/controller/api-test/group.api.spec.ts @@ -6,17 +6,15 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Course as CourseEntity, Role, SchoolEntity, SchoolYearEntity, User } from '@shared/domain/entity'; import { RoleName, SortOrder } from '@shared/domain/interface'; -import { - courseFactory as courseEntityFactory, - groupEntityFactory, - roleFactory, - schoolEntityFactory, - schoolYearFactory, - systemEntityFactory, - TestApiClient, - UserAndAccountTestFactory, - userFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { GroupEntity, GroupEntityTypes } from '../../entity'; import { ClassRootType } from '../../uc/dto/class-root-type'; import { ClassInfoSearchListResponse } from '../dto'; @@ -78,7 +76,7 @@ describe('Group (API)', () => { }, ], }); - const course: CourseEntity = courseEntityFactory.buildWithId({ syncedWithGroup: group }); + const course: CourseEntity = courseFactory.buildWithId({ syncedWithGroup: group }); await em.persistAndFlush([ school, @@ -305,7 +303,7 @@ describe('Group (API)', () => { type: GroupEntityTypes.COURSE, }); - const syncedCourse: CourseEntity = courseEntityFactory.build({ + const syncedCourse: CourseEntity = courseFactory.build({ school, syncedWithGroup: groupInSchool, }); @@ -482,7 +480,7 @@ describe('Group (API)', () => { type: GroupEntityTypes.COURSE, }); - const syncedCourse: CourseEntity = courseEntityFactory.build({ + const syncedCourse: CourseEntity = courseFactory.build({ school, syncedWithGroup: teachersGroup, }); diff --git a/apps/server/src/modules/group/domain/group.spec.ts b/apps/server/src/modules/group/domain/group.spec.ts index 7c78a3ab022..8f781c7a876 100644 --- a/apps/server/src/modules/group/domain/group.spec.ts +++ b/apps/server/src/modules/group/domain/group.spec.ts @@ -1,6 +1,8 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { RoleReference, UserDO } from '@shared/domain/domainobject'; -import { groupFactory, roleFactory, userDoFactory } from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { Group } from './group'; import { GroupUser } from './group-user'; diff --git a/apps/server/src/modules/group/repo/group.repo.spec.ts b/apps/server/src/modules/group/repo/group.repo.spec.ts index cb0221217a5..c405b2538ed 100644 --- a/apps/server/src/modules/group/repo/group.repo.spec.ts +++ b/apps/server/src/modules/group/repo/group.repo.spec.ts @@ -6,16 +6,14 @@ import { ExternalSource, Page } from '@shared/domain/domainobject'; import { SchoolEntity, User } from '@shared/domain/entity'; import { RoleName, SortOrder } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; -import { - cleanupCollections, - courseFactory, - groupEntityFactory, - groupFactory, - roleFactory, - schoolEntityFactory, - systemEntityFactory, - userFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { groupFactory } from '@testing/factory/domainobject'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userFactory } from '@testing/factory/user.factory'; import { Group, GroupAggregateScope, GroupProps, GroupTypes, GroupUser } from '../domain'; import { GroupEntity, GroupEntityTypes, GroupUserEmbeddable } from '../entity'; import { GroupRepo } from './group.repo'; diff --git a/apps/server/src/modules/group/service/group.service.spec.ts b/apps/server/src/modules/group/service/group.service.spec.ts index 1b35463de26..8ed3186838a 100644 --- a/apps/server/src/modules/group/service/group.service.spec.ts +++ b/apps/server/src/modules/group/service/group.service.spec.ts @@ -8,16 +8,14 @@ import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { Page } from '@shared/domain/domainobject'; import { IFindOptions, RoleName, SortOrder } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; -import { - groupFactory, - roleDtoFactory, - schoolEntityFactory, - setupEntities, - userDoFactory, - userFactory, -} from '@shared/testing'; import { RoleDto, RoleService } from '@src/modules/role'; import { UserService } from '@src/modules/user'; +import { groupFactory } from '@testing/factory/domainobject'; +import { roleDtoFactory } from '@testing/factory/role-dto.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Group, GroupAggregateScope, GroupDeletedEvent, GroupTypes, GroupVisibilityPermission } from '../domain'; import { GroupRepo } from '../repo'; import { GroupService } from './group.service'; diff --git a/apps/server/src/modules/group/uc/class-group.uc.spec.ts b/apps/server/src/modules/group/uc/class-group.uc.spec.ts index 71f5bc26df1..6bc94557924 100644 --- a/apps/server/src/modules/group/uc/class-group.uc.spec.ts +++ b/apps/server/src/modules/group/uc/class-group.uc.spec.ts @@ -28,15 +28,13 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Page, UserDO } from '@shared/domain/domainobject'; import { SchoolYearEntity, User } from '@shared/domain/entity'; import { Permission, SortOrder } from '@shared/domain/interface'; -import { - groupFactory, - roleDtoFactory, - schoolYearFactory as schoolYearEntityFactory, - setupEntities, - UserAndAccountTestFactory, - userDoFactory, - userFactory, -} from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; +import { roleDtoFactory } from '@testing/factory/role-dto.factory'; +import { schoolYearFactory as schoolYearEntityFactory } from '@testing/factory/schoolyear.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SchoolYearQueryType } from '../controller/dto/interface'; import { Group, GroupFilter, GroupTypes } from '../domain'; import { UnknownQueryTypeLoggableException } from '../loggable'; diff --git a/apps/server/src/modules/group/uc/group.uc.spec.ts b/apps/server/src/modules/group/uc/group.uc.spec.ts index 52f8d019699..55688d6325e 100644 --- a/apps/server/src/modules/group/uc/group.uc.spec.ts +++ b/apps/server/src/modules/group/uc/group.uc.spec.ts @@ -11,17 +11,15 @@ import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { Page, UserDO } from '@shared/domain/domainobject'; import { Role, User } from '@shared/domain/entity'; import { Permission, SortOrder } from '@shared/domain/interface'; -import { - groupFactory, - roleDtoFactory, - roleFactory, - schoolEntityFactory, - setupEntities, - UserAndAccountTestFactory, - userDoFactory, - userFactory, -} from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { groupFactory } from '@testing/factory/domainobject'; +import { roleDtoFactory } from '@testing/factory/role-dto.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Group, GroupTypes, GroupVisibilityPermission } from '../domain'; import { GroupService } from '../service'; import { ResolvedGroupDto } from './dto'; diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-ajax.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-ajax.api.spec.ts index 333982d889d..03ac25418b1 100644 --- a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-ajax.api.spec.ts +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-ajax.api.spec.ts @@ -5,7 +5,8 @@ import { H5PAjaxEndpoint } from '@lumieducation/h5p-server'; import { EntityManager } from '@mikro-orm/core'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { H5PEditorTestModule } from '../../h5p-editor-test.module'; import { H5P_CONTENT_S3_CONNECTION, H5P_LIBRARIES_S3_CONNECTION } from '../../h5p-editor.config'; diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-delete.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-delete.api.spec.ts index 8f532cb1285..f8203b4fb6a 100644 --- a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-delete.api.spec.ts +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-delete.api.spec.ts @@ -5,13 +5,11 @@ import { H5PEditor } from '@lumieducation/h5p-server'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { - cleanupCollections, - h5pContentFactory, - lessonFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { H5PEditorTestModule } from '../../h5p-editor-test.module'; import { H5P_CONTENT_S3_CONNECTION, H5P_LIBRARIES_S3_CONNECTION } from '../../h5p-editor.config'; diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-files.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-files.api.spec.ts index 5ff8fa2f3d4..1ea581f2fd4 100644 --- a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-files.api.spec.ts +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-files.api.spec.ts @@ -6,13 +6,11 @@ import { ContentMetadata } from '@lumieducation/h5p-server/build/src/ContentMeta import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { - courseFactory, - h5pContentFactory, - lessonFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { Readable } from 'stream'; import { H5PContent, H5PContentParentType, H5PContentProperties } from '../../entity'; import { H5PEditorTestModule } from '../../h5p-editor-test.module'; diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-editor.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-editor.api.spec.ts index e7a575f4a3f..fc826f4bfcc 100644 --- a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-editor.api.spec.ts +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-editor.api.spec.ts @@ -5,13 +5,11 @@ import { H5PEditor, IContentMetadata } from '@lumieducation/h5p-server'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { - cleanupCollections, - h5pContentFactory, - lessonFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { H5PEditorTestModule } from '../../h5p-editor-test.module'; import { H5P_CONTENT_S3_CONNECTION, H5P_LIBRARIES_S3_CONNECTION } from '../../h5p-editor.config'; diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-player.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-player.api.spec.ts index 36012a5bd32..513e9944c1d 100644 --- a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-player.api.spec.ts +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-get-player.api.spec.ts @@ -5,13 +5,11 @@ import { H5PPlayer, IPlayerModel } from '@lumieducation/h5p-server'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { - cleanupCollections, - h5pContentFactory, - lessonFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { H5PEditorTestModule } from '../../h5p-editor-test.module'; import { H5P_CONTENT_S3_CONNECTION, H5P_LIBRARIES_S3_CONNECTION } from '../../h5p-editor.config'; diff --git a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-save-create.api.spec.ts b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-save-create.api.spec.ts index 8da4914e2ae..b01c72aba40 100644 --- a/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-save-create.api.spec.ts +++ b/apps/server/src/modules/h5p-editor/controller/api-test/h5p-editor-save-create.api.spec.ts @@ -5,7 +5,9 @@ import { H5PEditor, IContentMetadata } from '@lumieducation/h5p-server'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { cleanupCollections, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { H5PContentParentType } from '../../entity'; import { H5PEditorTestModule } from '../../h5p-editor-test.module'; import { H5P_CONTENT_S3_CONNECTION, H5P_LIBRARIES_S3_CONNECTION } from '../../h5p-editor.config'; diff --git a/apps/server/src/modules/h5p-editor/repo/h5p-content.repo.integration.spec.ts b/apps/server/src/modules/h5p-editor/repo/h5p-content.repo.integration.spec.ts index f9672ffb3ce..74c0c76fbab 100644 --- a/apps/server/src/modules/h5p-editor/repo/h5p-content.repo.integration.spec.ts +++ b/apps/server/src/modules/h5p-editor/repo/h5p-content.repo.integration.spec.ts @@ -1,7 +1,8 @@ +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { MongoMemoryDatabaseModule } from '@infra/database'; -import { cleanupCollections, h5pContentFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; import { H5PContent } from '../entity'; import { H5PContentRepo } from './h5p-content.repo'; diff --git a/apps/server/src/modules/h5p-editor/repo/library.repo.spec.ts b/apps/server/src/modules/h5p-editor/repo/library.repo.spec.ts index 79bcde09fe9..53767ef231b 100644 --- a/apps/server/src/modules/h5p-editor/repo/library.repo.spec.ts +++ b/apps/server/src/modules/h5p-editor/repo/library.repo.spec.ts @@ -1,11 +1,11 @@ +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections } from '@shared/testing'; -import { MongoMemoryDatabaseModule } from '@infra/database'; import { ILibraryMetadata } from '@lumieducation/h5p-server'; -import { LibraryRepo } from './library.repo'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { FileMetadata, InstalledLibrary } from '../entity'; +import { LibraryRepo } from './library.repo'; describe('LibraryRepo', () => { let module: TestingModule; diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-ajax.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-ajax.uc.spec.ts index 6e59f257342..35a177f6cc0 100644 --- a/apps/server/src/modules/h5p-editor/uc/h5p-ajax.uc.spec.ts +++ b/apps/server/src/modules/h5p-editor/uc/h5p-ajax.uc.spec.ts @@ -6,8 +6,8 @@ import { HttpException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { UserDO } from '@shared/domain/domainobject'; import { LanguageType } from '@shared/domain/interface'; -import { setupEntities } from '@shared/testing'; import { UserService } from '@src/modules/user'; +import { setupEntities } from '@testing/setup-entities'; import { H5PContentRepo } from '../repo'; import { LibraryStorage } from '../service'; import { H5PEditorUc } from './h5p.uc'; diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-delete.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-delete.uc.spec.ts index 70f1a833b8f..4378f170392 100644 --- a/apps/server/src/modules/h5p-editor/uc/h5p-delete.uc.spec.ts +++ b/apps/server/src/modules/h5p-editor/uc/h5p-delete.uc.spec.ts @@ -4,8 +4,9 @@ import { AuthorizationClientAdapter, AuthorizationContextBuilder } from '@infra/ import { H5PEditor, H5PPlayer } from '@lumieducation/h5p-server'; import { ForbiddenException, NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { h5pContentFactory, setupEntities } from '@shared/testing'; import { UserService } from '@src/modules/user'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; +import { setupEntities } from '@testing/setup-entities'; import { H5PAjaxEndpointProvider } from '../provider'; import { H5PContentRepo } from '../repo'; import { LibraryStorage } from '../service'; diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-files.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-files.uc.spec.ts index 700c65437e9..29f9a917a1a 100644 --- a/apps/server/src/modules/h5p-editor/uc/h5p-files.uc.spec.ts +++ b/apps/server/src/modules/h5p-editor/uc/h5p-files.uc.spec.ts @@ -4,8 +4,9 @@ import { AuthorizationClientAdapter, AuthorizationContextBuilder } from '@infra/ import { H5PAjaxEndpoint, H5PEditor, IPlayerModel } from '@lumieducation/h5p-server'; import { ForbiddenException, NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { h5pContentFactory, setupEntities } from '@shared/testing'; import { UserService } from '@src/modules/user'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Request } from 'express'; import { Readable } from 'stream'; import { H5PEditorProvider, H5PPlayerProvider } from '../provider'; diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-get-editor.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-get-editor.uc.spec.ts index 5d3a247670f..b34eac8fd78 100644 --- a/apps/server/src/modules/h5p-editor/uc/h5p-get-editor.uc.spec.ts +++ b/apps/server/src/modules/h5p-editor/uc/h5p-get-editor.uc.spec.ts @@ -6,8 +6,9 @@ import { ForbiddenException, NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { LanguageType } from '@shared/domain/interface'; import { UserRepo } from '@shared/repo'; -import { h5pContentFactory, setupEntities } from '@shared/testing'; import { UserService } from '@src/modules/user'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; +import { setupEntities } from '@testing/setup-entities'; import { H5PAjaxEndpointProvider } from '../provider'; import { H5PContentRepo } from '../repo'; import { LibraryStorage } from '../service'; diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-get-player.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-get-player.uc.spec.ts index 385910d5798..232fae763e9 100644 --- a/apps/server/src/modules/h5p-editor/uc/h5p-get-player.uc.spec.ts +++ b/apps/server/src/modules/h5p-editor/uc/h5p-get-player.uc.spec.ts @@ -4,8 +4,9 @@ import { AuthorizationClientAdapter, AuthorizationContextBuilder } from '@infra/ import { H5PEditor, H5PPlayer, IPlayerModel } from '@lumieducation/h5p-server'; import { ForbiddenException, NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { h5pContentFactory, setupEntities } from '@shared/testing'; import { UserService } from '@src/modules/user'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; +import { setupEntities } from '@testing/setup-entities'; import { H5PAjaxEndpointProvider } from '../provider'; import { H5PContentRepo } from '../repo'; import { LibraryStorage } from '../service'; diff --git a/apps/server/src/modules/h5p-editor/uc/h5p-save-create.uc.spec.ts b/apps/server/src/modules/h5p-editor/uc/h5p-save-create.uc.spec.ts index 9bfb0edd965..a6f0214c81a 100644 --- a/apps/server/src/modules/h5p-editor/uc/h5p-save-create.uc.spec.ts +++ b/apps/server/src/modules/h5p-editor/uc/h5p-save-create.uc.spec.ts @@ -5,8 +5,9 @@ import { H5PEditor, H5PPlayer } from '@lumieducation/h5p-server'; import { ObjectId } from '@mikro-orm/mongodb'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { h5pContentFactory, setupEntities } from '@shared/testing'; import { UserService } from '@src/modules/user'; +import { h5pContentFactory } from '@testing/factory/h5p-content.factory'; +import { setupEntities } from '@testing/setup-entities'; import { H5PContentParentType } from '../entity'; import { H5PAjaxEndpointProvider } from '../provider'; import { H5PContentRepo } from '../repo'; diff --git a/apps/server/src/modules/health/controller/api-test/health-checks.api.spec.ts b/apps/server/src/modules/health/controller/api-test/health-checks.api.spec.ts index ac5f6d815bc..9d60587607f 100644 --- a/apps/server/src/modules/health/controller/api-test/health-checks.api.spec.ts +++ b/apps/server/src/modules/health/controller/api-test/health-checks.api.spec.ts @@ -1,12 +1,12 @@ +import { EntityManager } from '@mikro-orm/mongodb'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { EntityManager } from '@mikro-orm/mongodb'; import request from 'supertest'; -import { cleanupCollections } from '@shared/testing'; import { InternalServerTestModule } from '@src/modules/internal-server/internal-server-test.module'; -import { HealthStatusResponse } from '../dto'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { HealthStatuses } from '../../domain'; +import { HealthStatusResponse } from '../dto'; class API { app: INestApplication; diff --git a/apps/server/src/modules/health/controller/health.controller.spec.ts b/apps/server/src/modules/health/controller/health.controller.spec.ts index 1e24f0768ff..26c623419a0 100644 --- a/apps/server/src/modules/health/controller/health.controller.spec.ts +++ b/apps/server/src/modules/health/controller/health.controller.spec.ts @@ -1,12 +1,12 @@ -import { Test, TestingModule } from '@nestjs/testing'; +import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { HttpStatus } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; import { Response } from 'express'; -import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { HealthUC } from '@src/modules/health/uc'; -import { setupEntities } from '@shared/testing'; -import { HealthController } from './health.controller'; +import { setupEntities } from '@testing/setup-entities'; import { HealthStatus, HealthStatuses } from '../domain'; +import { HealthController } from './health.controller'; describe(HealthController.name, () => { const contentTypeApplicationHealthJSON = 'application/health+json'; diff --git a/apps/server/src/modules/health/repo/health-check.repo.spec.ts b/apps/server/src/modules/health/repo/health-check.repo.spec.ts index 5deaf084c24..14f5162daf9 100644 --- a/apps/server/src/modules/health/repo/health-check.repo.spec.ts +++ b/apps/server/src/modules/health/repo/health-check.repo.spec.ts @@ -1,8 +1,8 @@ import { EntityManager } from '@mikro-orm/mongodb'; -import { TestingModule, Test } from '@nestjs/testing'; +import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections } from '@shared/testing'; import { MongoMemoryDatabaseModule } from '@infra/database'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { HealthCheckEntity } from './entity'; import { HealthCheckRepo } from './health-check.repo'; diff --git a/apps/server/src/modules/health/service/health.service.spec.ts b/apps/server/src/modules/health/service/health.service.spec.ts index 4cff871a433..843b4a014c9 100644 --- a/apps/server/src/modules/health/service/health.service.spec.ts +++ b/apps/server/src/modules/health/service/health.service.spec.ts @@ -1,11 +1,11 @@ -import { Test, TestingModule } from '@nestjs/testing'; import { createMock, DeepMocked } from '@golevelup/ts-jest'; +import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; -import { HealthService } from './health.service'; -import { HealthCheckRepo } from '../repo'; +import { setupEntities } from '@testing/setup-entities'; import { HealthCheck } from '../domain'; +import { HealthCheckRepo } from '../repo'; import { HealthCheckEntity } from '../repo/entity'; +import { HealthService } from './health.service'; describe(HealthService.name, () => { const testId = 'test_health_check_id'; diff --git a/apps/server/src/modules/idp-console/api/synchronization.uc.spec.ts b/apps/server/src/modules/idp-console/api/synchronization.uc.spec.ts index 2cce1678f53..09e8c835965 100644 --- a/apps/server/src/modules/idp-console/api/synchronization.uc.spec.ts +++ b/apps/server/src/modules/idp-console/api/synchronization.uc.spec.ts @@ -2,20 +2,20 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { SchulconnexResponse, SchulconnexRestClient } from '@infra/schulconnex-client'; import { schulconnexResponseFactory } from '@infra/schulconnex-client/testing'; import { Synchronization, SynchronizationService, SynchronizationStatusModel } from '@modules/synchronization'; +import { synchronizationFactory } from '@modules/synchronization/domain/testing'; import { UserService } from '@modules/user'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { Logger } from '@src/core/logger'; import { AccountService } from '@src/modules/account'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; -import { synchronizationFactory } from '@modules/synchronization/domain/testing'; +import { IdpConsoleConfig } from '../idp-console.config'; import { FailedUpdateLastSyncedAtLoggableException, NoUsersToSynchronizationLoggableException, } from './loggable-exception'; import { SynchronizationUc } from './synchronization.uc'; -import { IdpConsoleConfig } from '../idp-console.config'; describe(SynchronizationUc.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/instance/testing/instance-entity.factory.ts b/apps/server/src/modules/instance/testing/instance-entity.factory.ts index 5e28b2e1b48..57635aa00f1 100644 --- a/apps/server/src/modules/instance/testing/instance-entity.factory.ts +++ b/apps/server/src/modules/instance/testing/instance-entity.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { InstanceEntity, InstanceEntityProps } from '../entity'; export const instanceEntityFactory = BaseFactory.define(InstanceEntity, () => { diff --git a/apps/server/src/modules/instance/testing/instance.factory.ts b/apps/server/src/modules/instance/testing/instance.factory.ts index b377ad78092..b4c0ab26d7a 100644 --- a/apps/server/src/modules/instance/testing/instance.factory.ts +++ b/apps/server/src/modules/instance/testing/instance.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { Instance, InstanceProps } from '../domain'; export const instanceFactory = BaseFactory.define(Instance, () => { diff --git a/apps/server/src/modules/learnroom/controller/api-test/course-info.api.spec.ts b/apps/server/src/modules/learnroom/controller/api-test/course-info.api.spec.ts index 602dd6c8461..dc847763f16 100644 --- a/apps/server/src/modules/learnroom/controller/api-test/course-info.api.spec.ts +++ b/apps/server/src/modules/learnroom/controller/api-test/course-info.api.spec.ts @@ -4,13 +4,11 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Course as CourseEntity } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { - cleanupCollections, - courseFactory, - schoolEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { CourseSortProps, CourseStatus } from '../../domain'; import { CourseInfoListResponse } from '../dto/response'; diff --git a/apps/server/src/modules/learnroom/controller/api-test/course-rooms-copy-timeout.api.spec.ts b/apps/server/src/modules/learnroom/controller/api-test/course-rooms-copy-timeout.api.spec.ts index 89439e9ba78..257489c3689 100644 --- a/apps/server/src/modules/learnroom/controller/api-test/course-rooms-copy-timeout.api.spec.ts +++ b/apps/server/src/modules/learnroom/controller/api-test/course-rooms-copy-timeout.api.spec.ts @@ -1,21 +1,14 @@ import { createMock } from '@golevelup/ts-jest'; import { Configuration } from '@hpi-schul-cloud/commons/lib'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { FilesStorageClientAdapterService } from '@modules/files-storage-client'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { Permission } from '@shared/domain/interface'; -import { - cleanupCollections, - courseFactory, - lessonFactory, - mapUserToCurrentUser, - roleFactory, - userFactory, -} from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; // config must be set outside before the server module is importat, otherwise the configuration is already set const configBefore = Configuration.toObject({ plainSecrets: true }); @@ -29,20 +22,12 @@ import { ServerTestModule } from '@modules/server'; describe('Course Rooms copy (API)', () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; + let apiClient: TestApiClient; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .overrideProvider(FilesStorageClientAdapterService) .useValue(createMock()) .compile(); @@ -50,6 +35,8 @@ describe('Course Rooms copy (API)', () => { app = moduleFixture.createNestApplication(); await app.init(); em = app.get(EntityManager); + + apiClient = new TestApiClient(app, '/course-rooms'); }); afterAll(async () => { @@ -58,43 +45,48 @@ describe('Course Rooms copy (API)', () => { Configuration.reset(configBefore); }); - const setup = () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.COURSE_CREATE, Permission.TOPIC_CREATE] }); - const user = userFactory.build({ roles }); + describe('when copying course', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ name: 'course #1', teachers: [teacherUser] }); + + await em.persistAndFlush([course, teacherAccount, teacherUser]); + em.clear(); - return user; - }; + const loggedInClient = await apiClient.login(teacherAccount); - it('should respond with 408 on timeout when copying course', async () => { - const teacher = setup(); - const course = courseFactory.build({ name: 'course #1', teachers: [teacher] }); - await em.persistAndFlush(course); - em.clear(); + return { loggedInClient, course }; + }; - currentUser = mapUserToCurrentUser(teacher); + it('should respond with 408 on timeout', async () => { + const { loggedInClient, course } = await setup(); - const response = await request(app.getHttpServer()) - .post(`/course-rooms/${course.id}/copy`) - .set('Authorization', 'jwt') - .send(); + const response = await loggedInClient.post(`/${course.id}/copy`); - expect(response.status).toEqual(408); + expect(response.status).toEqual(408); + }); }); - it('should respond with 408 on timeout when copying lesson', async () => { - const teacher = setup(); - const course = courseFactory.build({ name: 'course #1', teachers: [teacher] }); - const lesson = lessonFactory.build({ name: 'lesson #1', course }); - await em.persistAndFlush([lesson, course]); - em.clear(); + describe('when copying lesson', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ name: 'course #1', teachers: [teacherUser] }); + const lesson = lessonFactory.build({ name: 'lesson #1', course }); + + await em.persistAndFlush([course, lesson, teacherAccount, teacherUser]); + em.clear(); + + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, lesson }; + }; - currentUser = mapUserToCurrentUser(teacher); + it('should respond with 408 on timeout', async () => { + const { loggedInClient, lesson } = await setup(); - const response = await request(app.getHttpServer()) - .post(`/course-rooms/lessons/${lesson.id}/copy`) - .set('Authorization', 'jwt') - .send(); + const response = await loggedInClient.post(`/lessons/${lesson.id}/copy`); - expect(response.status).toEqual(408); + expect(response.status).toEqual(408); + }); }); }); diff --git a/apps/server/src/modules/learnroom/controller/api-test/course-rooms.api.spec.ts b/apps/server/src/modules/learnroom/controller/api-test/course-rooms.api.spec.ts index d736023d32f..d43416c2eac 100644 --- a/apps/server/src/modules/learnroom/controller/api-test/course-rooms.api.spec.ts +++ b/apps/server/src/modules/learnroom/controller/api-test/course-rooms.api.spec.ts @@ -1,33 +1,25 @@ -import { createMock, DeepMocked } from '@golevelup/ts-jest'; +import { createMock } from '@golevelup/ts-jest'; import { Configuration } from '@hpi-schul-cloud/commons'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { CopyApiResponse } from '@modules/copy-helper'; import { FilesStorageClientAdapterService } from '@modules/files-storage-client'; import { SingleColumnBoardResponse } from '@modules/learnroom/controller/dto'; import { ServerTestModule } from '@modules/server/server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Course, LegacyBoard, Task } from '@shared/domain/entity'; -import { Permission } from '@shared/domain/interface'; -import { - boardFactory, - cleanupCollections, - courseFactory, - lessonFactory, - mapUserToCurrentUser, - roleFactory, - taskFactory, - userFactory, -} from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { boardFactory } from '@testing/factory/board.factory'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; describe('Course Rooms Controller (API)', () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let filesStorageClientAdapterService: DeepMocked; + let apiClient: TestApiClient; const setConfig = () => { Configuration.set('FEATURE_COPY_SERVICE_ENABLED', true); @@ -39,21 +31,14 @@ describe('Course Rooms Controller (API)', () => { }) .overrideProvider(FilesStorageClientAdapterService) .useValue(createMock()) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .compile(); app = moduleFixture.createNestApplication(); await app.init(); em = app.get(EntityManager); - filesStorageClientAdapterService = app.get(FilesStorageClientAdapterService); setConfig(); + + apiClient = new TestApiClient(app, '/course-rooms'); }); afterAll(async () => { @@ -61,222 +46,305 @@ describe('Course Rooms Controller (API)', () => { await app.close(); }); - it('[GET] board', async () => { - const roles = roleFactory.buildList(1, { permissions: [] }); - const student = userFactory.build({ roles }); - const course = courseFactory.build({ students: [student] }); - const task = taskFactory.build({ course }); + describe('[GET] board', () => { + describe('when user is loggedin', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const course = courseFactory.build({ students: [studentUser] }); + const task = taskFactory.build({ course }); + + await em.persistAndFlush([course, task, studentAccount, studentUser]); + em.clear(); + + const loggedInClient = await apiClient.login(studentAccount); + + return { loggedInClient, course }; + }; + + it('should return status 200 and courseId', async () => { + const { loggedInClient, course } = await setup(); + + const response = await loggedInClient.get(`${course.id}/board`); - await em.persistAndFlush([course, task]); - em.clear(); + expect(response.status).toEqual(200); + const body = response.body as SingleColumnBoardResponse; + expect(body.roomId).toEqual(course.id); + }); + }); + + describe('when user is not loggedin', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const course = courseFactory.build({ students: [studentUser] }); + const task = taskFactory.build({ course }); - currentUser = mapUserToCurrentUser(student); + await em.persistAndFlush([course, task, studentAccount, studentUser]); + em.clear(); + + return { course }; + }; - const response = await request(app.getHttpServer()).get(`/course-rooms/${course.id}/board`); + it('should return status 200 and courseId', async () => { + const { course } = await setup(); - expect(response.status).toEqual(200); - const body = response.body as SingleColumnBoardResponse; - expect(body.roomId).toEqual(course.id); + const response = await apiClient.get(`${course.id}/board`); + + expect(response.status).toEqual(401); + }); + }); }); describe('[PATCH] ElementVisibility', () => { - it('should return 200', async () => { - const roles = roleFactory.buildList(1, { permissions: [] }); - const teacher = userFactory.build({ roles }); - const course = courseFactory.build({ teachers: [teacher] }); - const board = boardFactory.buildWithId({ course }); - const task = taskFactory.draft().build({ course }); - board.syncBoardElementReferences([task]); + describe('when user is loggedin', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + const board = boardFactory.buildWithId({ course }); + const task = taskFactory.draft().build({ course }); + board.syncBoardElementReferences([task]); - await em.persistAndFlush([course, board, task]); - em.clear(); + await em.persistAndFlush([course, board, task, teacherAccount, teacherUser]); + em.clear(); - currentUser = mapUserToCurrentUser(teacher); - const params = { visibility: true }; + const params = { visibility: true }; - const response = await request(app.getHttpServer()) - .patch(`/course-rooms/${course.id}/elements/${task.id}/visibility`) - .send(params); + const loggedInClient = await apiClient.login(teacherAccount); - expect(response.status).toEqual(200); - }); + return { loggedInClient, course, task, params }; + }; + + it('should return 200', async () => { + const { loggedInClient, course, task, params } = await setup(); + + const response = await loggedInClient.patch(`${course.id}/elements/${task.id}/visibility`).send(params); + + expect(response.status).toEqual(200); + }); - it('should make task visible', async () => { - const roles = roleFactory.buildList(1, { permissions: [] }); - const teacher = userFactory.build({ roles }); - const course = courseFactory.build({ teachers: [teacher] }); - const board = boardFactory.buildWithId({ course }); - const task = taskFactory.draft().build({ course }); - board.syncBoardElementReferences([task]); + it('should make task visible', async () => { + const { loggedInClient, course, task, params } = await setup(); - await em.persistAndFlush([course, board, task]); - em.clear(); + await loggedInClient.patch(`${course.id}/elements/${task.id}/visibility`).send(params); + const updatedTask = await em.findOneOrFail(Task, task.id); - currentUser = mapUserToCurrentUser(teacher); - const params = { visibility: true }; + expect(updatedTask.isDraft()).toEqual(false); + }); - await request(app.getHttpServer()) - .patch(`/course-rooms/${course.id}/elements/${task.id}/visibility`) - .send(params); - const updatedTask = await em.findOneOrFail(Task, task.id); + it('should make task invisibible', async () => { + const { loggedInClient, course, task } = await setup(); - expect(updatedTask.isDraft()).toEqual(false); + const params = { visibility: false }; + + await loggedInClient.patch(`/course-rooms/${course.id}/elements/${task.id}/visibility`).send(params); + const updatedTask = await em.findOneOrFail(Task, task.id); + + expect(updatedTask.isDraft()).toEqual(true); + }); }); - it('should make task invisibible', async () => { - const roles = roleFactory.buildList(1, { permissions: [] }); - const teacher = userFactory.build({ roles }); - const course = courseFactory.build({ teachers: [teacher] }); - const board = boardFactory.buildWithId({ course }); - const task = taskFactory.build({ course }); - board.syncBoardElementReferences([task]); + describe('when user is not loggedin', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + const board = boardFactory.buildWithId({ course }); + const task = taskFactory.draft().build({ course }); + board.syncBoardElementReferences([task]); - await em.persistAndFlush([course, board, task]); - em.clear(); + await em.persistAndFlush([course, board, task, teacherAccount, teacherUser]); + em.clear(); - currentUser = mapUserToCurrentUser(teacher); - const params = { visibility: false }; + const params = { visibility: true }; - await request(app.getHttpServer()) - .patch(`/course-rooms/${course.id}/elements/${task.id}/visibility`) - .send(params); - const updatedTask = await em.findOneOrFail(Task, task.id); + return { course, task, params }; + }; - expect(updatedTask.isDraft()).toEqual(true); + it('should return 401', async () => { + const { course, task, params } = await setup(); + + const response = await apiClient.patch(`${course.id}/elements/${task.id}/visibility`).send(params); + + expect(response.status).toEqual(401); + }); }); }); describe('[PATCH] order', () => { - it('should return 200', async () => { - const roles = roleFactory.buildList(1, { permissions: [] }); - const teacher = userFactory.build({ roles }); - const course = courseFactory.build({ teachers: [teacher] }); - const board = boardFactory.buildWithId({ course }); - const tasks = taskFactory.buildList(3, { course }); - const lessons = lessonFactory.buildList(3, { course }); - board.syncBoardElementReferences([...tasks, ...lessons]); - - await em.persistAndFlush([course, board, ...tasks, ...lessons]); - em.clear(); - - currentUser = mapUserToCurrentUser(teacher); - const params = { - elements: [tasks[2], lessons[1], tasks[0], lessons[2], tasks[1], lessons[0]].map((el) => el.id), + describe('when user is logged in', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + const board = boardFactory.buildWithId({ course }); + const tasks = taskFactory.buildList(3, { course }); + const lessons = lessonFactory.buildList(3, { course }); + board.syncBoardElementReferences([...tasks, ...lessons]); + + await em.persistAndFlush([course, board, ...tasks, ...lessons, teacherAccount, teacherUser]); + em.clear(); + + const params = { + elements: [tasks[2], lessons[1], tasks[0], lessons[2], tasks[1], lessons[0]].map((el) => el.id), + }; + + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, course, params }; }; - const response = await request(app.getHttpServer()) - .patch(`/course-rooms/${course.id}/board/order`) - .set('Authorization', 'jwt') - .send(params); + it('should return 200', async () => { + const { loggedInClient, course, params } = await setup(); - expect(response.status).toEqual(200); + const response = await loggedInClient.patch(`${course.id}/board/order`).send(params); + + expect(response.status).toEqual(200); + }); + }); + + describe('when user is not logged in', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + const board = boardFactory.buildWithId({ course }); + const tasks = taskFactory.buildList(3, { course }); + const lessons = lessonFactory.buildList(3, { course }); + board.syncBoardElementReferences([...tasks, ...lessons]); + + await em.persistAndFlush([course, board, ...tasks, ...lessons, teacherAccount, teacherUser]); + em.clear(); + + const params = { + elements: [tasks[2], lessons[1], tasks[0], lessons[2], tasks[1], lessons[0]].map((el) => el.id), + }; + + return { course, params }; + }; + + it('should return 401', async () => { + const { course, params } = await setup(); + + const response = await apiClient.patch(`${course.id}/board/order`).send(params); + + expect(response.status).toEqual(401); + }); }); }); describe('[POST] copy', () => { - it('should return 201', async () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.COURSE_CREATE] }); - const teacher = userFactory.build({ roles }); - const course = courseFactory.build({ teachers: [teacher] }); + describe('when user is logged in', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + const board = boardFactory.build({ course }); + const tasks = taskFactory.buildList(3, { course }); + const lessons = lessonFactory.buildList(3, { course }); + board.syncBoardElementReferences([...tasks, ...lessons]); - await em.persistAndFlush([course]); - em.clear(); + await em.persistAndFlush([course, teacherAccount, teacherUser, board, ...tasks, ...lessons]); + em.clear(); - currentUser = mapUserToCurrentUser(teacher); + const loggedInClient = await apiClient.login(teacherAccount); - const response = await request(app.getHttpServer()) - .post(`/course-rooms/${course.id}/copy`) - .set('Authorization', 'jwt') - .send(); + return { loggedInClient, course }; + }; - expect(response.status).toEqual(201); - }); + it('should return 201', async () => { + const { loggedInClient, course } = await setup(); - it('should return id of copied element', async () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.COURSE_CREATE] }); - const teacher = userFactory.build({ roles }); - const course = courseFactory.build({ teachers: [teacher] }); + const response = await loggedInClient.post(`${course.id}/copy`); - await em.persistAndFlush([course]); - em.clear(); + expect(response.status).toEqual(201); + }); - currentUser = mapUserToCurrentUser(teacher); + it('should return id of copied element', async () => { + const { loggedInClient, course } = await setup(); - const response = await request(app.getHttpServer()) - .post(`/course-rooms/${course.id}/copy`) - .set('Authorization', 'jwt') - .send(); - const body = response.body as CopyApiResponse; - expect(body.id).toBeDefined(); + const response = await loggedInClient.post(`${course.id}/copy`); - expect(() => em.findOneOrFail(Course, body.id as string)).not.toThrow(); - }); + const body = response.body as CopyApiResponse; + expect(body.id).toBeDefined(); - it('should persist board of room copy', async () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.COURSE_CREATE] }); - const teacher = userFactory.build({ roles }); - const course = courseFactory.build({ teachers: [teacher] }); - const board = boardFactory.build({ course }); + expect(() => em.findOneOrFail(Course, body.id as string)).not.toThrow(); + }); - await em.persistAndFlush([course, board]); - em.clear(); + it('should persist board of room copy', async () => { + const { loggedInClient, course } = await setup(); - currentUser = mapUserToCurrentUser(teacher); + const response = await loggedInClient.post(`${course.id}/copy`); - const response = await request(app.getHttpServer()) - .post(`/course-rooms/${course.id}/copy`) - .set('Authorization', 'jwt') - .send(); - const body = response.body as CopyApiResponse; - expect(body.id).toBeDefined(); + const body = response.body as CopyApiResponse; + expect(body.id).toBeDefined(); - expect(() => em.findOneOrFail(LegacyBoard, { course: body.id as string })).not.toThrow(); + expect(() => em.findOneOrFail(LegacyBoard, { course: body.id as string })).not.toThrow(); + }); }); - it('complete example', async () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.COURSE_CREATE] }); - const teacher = userFactory.build({ roles }); - const course = courseFactory.build({ teachers: [teacher] }); + describe('when user is not logged in', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + const board = boardFactory.build({ course }); + const tasks = taskFactory.buildList(3, { course }); + const lessons = lessonFactory.buildList(3, { course }); + board.syncBoardElementReferences([...tasks, ...lessons]); - const board = boardFactory.buildWithId({ course }); - const tasks = taskFactory.buildList(3, { course }); - const lessons = lessonFactory.buildList(3, { course }); - board.syncBoardElementReferences([...tasks, ...lessons]); + await em.persistAndFlush([course, teacherAccount, teacherUser, board, ...tasks, ...lessons]); + em.clear(); - await em.persistAndFlush([course, board, ...tasks, ...lessons]); - em.clear(); - - currentUser = mapUserToCurrentUser(teacher); + return { course }; + }; - filesStorageClientAdapterService.copyFilesOfParent.mockResolvedValue([]); + it('should return 401', async () => { + const { course } = await setup(); - const response = await request(app.getHttpServer()) - .post(`/course-rooms/${course.id}/copy`) - .set('Authorization', 'jwt') - .send(); + const response = await apiClient.post(`${course.id}/copy`); - expect(response.status).toEqual(201); + expect(response.status).toEqual(401); + }); }); }); describe('[POST] lesson copy', () => { - it('should return 201', async () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.TOPIC_CREATE] }); - const teacher = userFactory.build({ roles }); - const course = courseFactory.build({ teachers: [teacher] }); - const lesson = lessonFactory.build({ course }); + describe('when user is logged in', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + const lesson = lessonFactory.build({ course }); + + await em.persistAndFlush([lesson, course, teacherAccount, teacherUser]); + em.clear(); + + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, course, lesson }; + }; + + it('should return 201', async () => { + const { loggedInClient, course, lesson } = await setup(); - await em.persistAndFlush([lesson]); - em.clear(); + const response = await loggedInClient.post(`lessons/${lesson.id}/copy`, { courseId: course.id }); + + expect(response.status).toEqual(201); + }); + }); + + describe('when user is not logged in', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + const lesson = lessonFactory.build({ course }); + + await em.persistAndFlush([lesson, course, teacherAccount, teacherUser]); + em.clear(); + + return { course, lesson }; + }; - currentUser = mapUserToCurrentUser(teacher); + it('should return 401', async () => { + const { course, lesson } = await setup(); - const response = await request(app.getHttpServer()) - .post(`/course-rooms/lessons/${lesson.id}/copy`) - .set('Authorization', 'jwt') - .send({ courseId: course.id }); + const response = await apiClient.post(`lessons/${lesson.id}/copy`, { courseId: course.id }); - expect(response.status).toEqual(201); + expect(response.status).toEqual(401); + }); }); }); }); diff --git a/apps/server/src/modules/learnroom/controller/api-test/course.api.spec.ts b/apps/server/src/modules/learnroom/controller/api-test/course.api.spec.ts index 3069fde5af1..52daa963783 100644 --- a/apps/server/src/modules/learnroom/controller/api-test/course.api.spec.ts +++ b/apps/server/src/modules/learnroom/controller/api-test/course.api.spec.ts @@ -5,13 +5,11 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Course as CourseEntity } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { - cleanupCollections, - courseFactory, - groupEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { readFile } from 'node:fs/promises'; import { CourseMetadataListResponse } from '../dto'; import { CourseCommonCartridgeMetadataResponse } from '../dto/course-cc-metadata.response'; diff --git a/apps/server/src/modules/learnroom/controller/api-test/dashboard.api.spec.ts b/apps/server/src/modules/learnroom/controller/api-test/dashboard.api.spec.ts index 2712c0e6c32..fef2cdc94f8 100644 --- a/apps/server/src/modules/learnroom/controller/api-test/dashboard.api.spec.ts +++ b/apps/server/src/modules/learnroom/controller/api-test/dashboard.api.spec.ts @@ -1,65 +1,37 @@ -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { DashboardResponse } from '@modules/learnroom/controller/dto'; import { ServerTestModule } from '@modules/server/server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { DashboardEntity, GridElement, User } from '@shared/domain/entity'; -import { Permission, RoleName } from '@shared/domain/interface'; import { IDashboardRepo } from '@shared/repo'; -import { courseFactory, mapUserToCurrentUser, roleFactory, userFactory } from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; describe('Dashboard Controller (API)', () => { let app: INestApplication; let em: EntityManager; let dashboardRepo: IDashboardRepo; - let currentUser: ICurrentUser; + let apiClient: TestApiClient; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); + }).compile(); app = moduleFixture.createNestApplication(); await app.init(); em = app.get(EntityManager); dashboardRepo = app.get('DASHBOARD_REPO'); + + apiClient = new TestApiClient(app, '/dashboard'); }); afterAll(async () => { await app.close(); }); - const setup = () => { - const roles = roleFactory.buildList(1, { - permissions: [Permission.TASK_DASHBOARD_TEACHER_VIEW_V3], - }); - const user = userFactory.build({ roles }); - - return user; - }; - - const setupWithRole = (roleName: RoleName) => { - const roles = roleFactory.buildList(1, { - permissions: [Permission.TASK_DASHBOARD_TEACHER_VIEW_V3], - name: roleName, - }); - const user = userFactory.build({ roles }); - - return user; - }; - const courseBuild = (student: User, teacher: User, time: number) => [ courseFactory.build({ name: 'should appear', students: [student] }), courseFactory.build({ name: 'should appear', substitutionTeachers: [teacher], students: [student] }), @@ -79,127 +51,156 @@ describe('Dashboard Controller (API)', () => { ]; describe('[GET] dashboard', () => { - it('should return dashboard with users active courses', async () => { - const user = setup(); - const twoDaysInMilliSeconds = 172800000; - const courses = courseBuild(user, user, twoDaysInMilliSeconds); - await em.persistAndFlush([user, ...courses]); - const { id: dashboardId } = await dashboardRepo.getUsersDashboard(user.id); - currentUser = mapUserToCurrentUser(user); + describe('with logged in teacher', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const { studentUser } = UserAndAccountTestFactory.buildStudent(); + const twoDaysInMilliSeconds = 172800000; + const courses = courseBuild(studentUser, teacherUser, twoDaysInMilliSeconds); + await em.persistAndFlush([teacherUser, teacherAccount, studentUser, ...courses]); + const { id: dashboardId } = await dashboardRepo.getUsersDashboard(teacherUser.id); - const response = await request(app.getHttpServer()).get('/dashboard'); + const loggedInClient = await apiClient.login(teacherAccount); - expect(response.status).toEqual(200); - const body = response.body as DashboardResponse; - expect(body.id).toEqual(dashboardId); - expect(body.gridElements.length).toEqual(4); - const elementNames = [...body.gridElements].map((gridElement) => gridElement.title); - elementNames.forEach((name) => { - expect(name).toEqual('should appear'); + return { teacherUser, dashboardId, loggedInClient }; + }; + + it('should return dashboard with teachers active courses', async () => { + const { dashboardId, loggedInClient } = await setup(); + + const response = await loggedInClient.get(); + + expect(response.status).toEqual(200); + const body = response.body as DashboardResponse; + expect(body.id).toEqual(dashboardId); + expect(body.gridElements.length).toEqual(3); + const elementNames = [...body.gridElements].map((gridElement) => gridElement.title); + elementNames.forEach((name) => { + expect(name).toEqual('should appear'); + }); }); }); - it('should return dashboard with teacher active courses', async () => { - const teacher = setupWithRole(RoleName.TEACHER); - const student = setupWithRole(RoleName.STUDENT); - const twoDaysInMilliSeconds = 172800000; - const courses = courseBuild(student, teacher, twoDaysInMilliSeconds); - await em.persistAndFlush([teacher, ...courses]); - const { id: dashboardId } = await dashboardRepo.getUsersDashboard(teacher.id); - currentUser = mapUserToCurrentUser(teacher); + describe('with not logged in teacher', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const { studentUser } = UserAndAccountTestFactory.buildStudent(); + const twoDaysInMilliSeconds = 172800000; + const courses = courseBuild(studentUser, teacherUser, twoDaysInMilliSeconds); + await em.persistAndFlush([teacherUser, teacherAccount, studentUser, ...courses]); + const { id: dashboardId } = await dashboardRepo.getUsersDashboard(teacherUser.id); - const response = await request(app.getHttpServer()).get('/dashboard'); + return { teacherUser, dashboardId }; + }; - expect(response.status).toEqual(200); - const body = response.body as DashboardResponse; - expect(body.id).toEqual(dashboardId); - expect(body.gridElements.length).toEqual(3); - const elementNames = [...body.gridElements].map((gridElement) => gridElement.title); - elementNames.forEach((name) => { - expect(name).toEqual('should appear'); + it('should return status 401', async () => { + await setup(); + + const response = await apiClient.get(); + + expect(response.status).toEqual(401); }); }); - it('should return dashboard with student active courses', async () => { - const student = setupWithRole(RoleName.STUDENT); - const teacher = setupWithRole(RoleName.TEACHER); - const twoDaysInMilliSeconds = 172800000; - const courses = courseBuild(student, teacher, twoDaysInMilliSeconds); - await em.persistAndFlush([student, ...courses]); - const { id: dashboardId } = await dashboardRepo.getUsersDashboard(student.id); - currentUser = mapUserToCurrentUser(student); + describe('with logged in student', () => { + const setup = async () => { + const { teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const twoDaysInMilliSeconds = 172800000; + const courses = courseBuild(studentUser, teacherUser, twoDaysInMilliSeconds); + await em.persistAndFlush([teacherUser, studentAccount, studentUser, ...courses]); + const { id: dashboardId } = await dashboardRepo.getUsersDashboard(studentUser.id); - const response = await request(app.getHttpServer()).get('/dashboard'); + const loggedInClient = await apiClient.login(studentAccount); - expect(response.status).toEqual(200); - const body = response.body as DashboardResponse; - expect(body.id).toEqual(dashboardId); - expect(body.gridElements.length).toEqual(4); - const elementNames = [...body.gridElements].map((gridElement) => gridElement.title); - elementNames.forEach((name) => { - expect(name).toEqual('should appear'); + return { teacherUser, dashboardId, loggedInClient }; + }; + + it('should return dashboard with student active courses', async () => { + const { dashboardId, loggedInClient } = await setup(); + + const response = await loggedInClient.get(); + + expect(response.status).toEqual(200); + const body = response.body as DashboardResponse; + expect(body.id).toEqual(dashboardId); + expect(body.gridElements.length).toEqual(4); + const elementNames = [...body.gridElements].map((gridElement) => gridElement.title); + elementNames.forEach((name) => { + expect(name).toEqual('should appear'); + }); }); }); }); describe('[PATCH] /:id/moveElement', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const { studentUser } = UserAndAccountTestFactory.buildStudent(); + const twoDaysInMilliSeconds = 172800000; + const courses = courseBuild(studentUser, teacherUser, twoDaysInMilliSeconds); + await em.persistAndFlush([teacherUser, teacherAccount, studentUser, ...courses]); + const { id: dashboardId } = await dashboardRepo.getUsersDashboard(teacherUser.id); + + const loggedInClient = await apiClient.login(teacherAccount); + + return { teacherUser, dashboardId, loggedInClient }; + }; + it('should update position of target element', async () => { - const user = setup(); - await em.persistAndFlush([user]); - const { id: dashboardId } = await dashboardRepo.getUsersDashboard(user.id); + const { loggedInClient, dashboardId, teacherUser } = await setup(); + const dashboard = new DashboardEntity(dashboardId, { grid: [ { pos: { x: 1, y: 3 }, gridElement: GridElement.FromPersistedReference( new ObjectId().toString(), - courseFactory.build({ students: [user], name: 'Mathe' }) + courseFactory.build({ students: [teacherUser], name: 'Mathe' }) ), }, ], - userId: user.id, + userId: teacherUser.id, }); await dashboardRepo.persistAndFlush(dashboard); - currentUser = mapUserToCurrentUser(user); const params = { from: { x: 1, y: 3 }, to: { x: 4, y: 2 }, }; - const resonse = await request(app.getHttpServer()).patch(`/dashboard/${dashboard.id}/moveElement`).send(params); + const resonse = await loggedInClient.patch(`${dashboardId}/moveElement`).send(params); expect(resonse.status).toEqual(200); }); it('should create groups', async () => { - const user = setup(); - await em.persistAndFlush([user]); - const { id: dashboardId } = await dashboardRepo.getUsersDashboard(user.id); + const { loggedInClient, dashboardId, teacherUser } = await setup(); + const dashboard = new DashboardEntity(dashboardId, { grid: [ { pos: { x: 1, y: 3 }, gridElement: GridElement.FromPersistedReference( new ObjectId().toString(), - courseFactory.build({ students: [user], name: 'Quantumphysics' }) + courseFactory.build({ students: [teacherUser], name: 'Quantumphysics' }) ), }, { pos: { x: 2, y: 2 }, gridElement: GridElement.FromPersistedReference( new ObjectId().toString(), - courseFactory.build({ students: [user], name: 'Astrophysics' }) + courseFactory.build({ students: [teacherUser], name: 'Astrophysics' }) ), }, ], - userId: user.id, + userId: teacherUser.id, }); await dashboardRepo.persistAndFlush(dashboard); - currentUser = mapUserToCurrentUser(user); const params = { from: { x: 1, y: 3 }, to: { x: 2, y: 2 }, }; - const response = await request(app.getHttpServer()).patch(`/dashboard/${dashboard.id}/moveElement`).send(params); + + const response = await loggedInClient.patch(`${dashboard.id}/moveElement`).send(params); expect(response.status).toEqual(200); const body = response.body as DashboardResponse; expect(body.gridElements.length).toEqual(1); @@ -207,35 +208,34 @@ describe('Dashboard Controller (API)', () => { }); it('should add element to group', async () => { - const user = setup(); - await em.persistAndFlush([user]); - const { id: dashboardId } = await dashboardRepo.getUsersDashboard(user.id); + const { loggedInClient, dashboardId, teacherUser } = await setup(); + const dashboard = new DashboardEntity(dashboardId, { grid: [ { pos: { x: 2, y: 2 }, gridElement: GridElement.FromPersistedReference( new ObjectId().toString(), - courseFactory.build({ students: [user], name: 'mannequinization' }) + courseFactory.build({ students: [teacherUser], name: 'mannequinization' }) ), }, { pos: { x: 3, y: 3 }, gridElement: GridElement.FromPersistedGroup(new ObjectId().toString(), 'drawing', [ - courseFactory.build({ students: [user], name: 'Perspective Drawing' }), - courseFactory.build({ students: [user], name: 'Shape Manipulation' }), + courseFactory.build({ students: [teacherUser], name: 'Perspective Drawing' }), + courseFactory.build({ students: [teacherUser], name: 'Shape Manipulation' }), ]), }, ], - userId: user.id, + userId: teacherUser.id, }); await dashboardRepo.persistAndFlush(dashboard); - currentUser = mapUserToCurrentUser(user); const params = { from: { x: 2, y: 2 }, to: { x: 3, y: 3 }, }; - const response = await request(app.getHttpServer()).patch(`/dashboard/${dashboard.id}/moveElement`).send(params); + + const response = await loggedInClient.patch(`${dashboard.id}/moveElement`).send(params); expect(response.status).toEqual(200); const body = response.body as DashboardResponse; expect(body.gridElements.length).toEqual(1); @@ -243,85 +243,91 @@ describe('Dashboard Controller (API)', () => { }); it('should remove element from group', async () => { - const user = setup(); - await em.persistAndFlush([user]); - const { id: dashboardId } = await dashboardRepo.getUsersDashboard(user.id); + const { loggedInClient, dashboardId, teacherUser } = await setup(); + const dashboard = new DashboardEntity(dashboardId, { grid: [ { pos: { x: 3, y: 3 }, gridElement: GridElement.FromPersistedGroup(new ObjectId().toString(), 'drawing', [ - courseFactory.build({ students: [user], name: 'Perspective Drawing' }), - courseFactory.build({ students: [user], name: 'Shape Manipulation' }), + courseFactory.build({ students: [teacherUser], name: 'Perspective Drawing' }), + courseFactory.build({ students: [teacherUser], name: 'Shape Manipulation' }), ]), }, ], - userId: user.id, + userId: teacherUser.id, }); await dashboardRepo.persistAndFlush(dashboard); - currentUser = mapUserToCurrentUser(user); const params = { from: { x: 3, y: 3, groupIndex: 0 }, to: { x: 2, y: 3 }, }; - const response = await request(app.getHttpServer()).patch(`/dashboard/${dashboard.id}/moveElement`).send(params); + + const response = await loggedInClient.patch(`${dashboard.id}/moveElement`).send(params); expect(response.status).toEqual(200); const body = response.body as DashboardResponse; expect(body.gridElements.length).toEqual(2); }); it('should fail with incomplete input', async () => { - const user = setup(); - await em.persistAndFlush([user]); - const { id: dashboardId } = await dashboardRepo.getUsersDashboard(user.id); + const { loggedInClient, dashboardId, teacherUser } = await setup(); + const dashboard = new DashboardEntity(dashboardId, { grid: [ { pos: { x: 1, y: 3 }, gridElement: GridElement.FromPersistedReference( new ObjectId().toString(), - courseFactory.build({ students: [user], name: 'Mathe' }) + courseFactory.build({ students: [teacherUser], name: 'Mathe' }) ), }, ], - userId: user.id, + userId: teacherUser.id, }); await dashboardRepo.persistAndFlush(dashboard); - currentUser = mapUserToCurrentUser(user); const params = { from: { x: 1, y: 3 }, to: { x: 4 }, }; - const resonse = await request(app.getHttpServer()).patch(`/dashboard/${dashboard.id}/moveElement`).send(params); + const resonse = await loggedInClient.patch(`${dashboard.id}/moveElement`).send(params); expect(resonse.status).toEqual(400); }); }); describe('PATCH /:id/element', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const { studentUser } = UserAndAccountTestFactory.buildStudent(); + const twoDaysInMilliSeconds = 172800000; + const courses = courseBuild(studentUser, teacherUser, twoDaysInMilliSeconds); + await em.persistAndFlush([teacherUser, teacherAccount, studentUser, ...courses]); + const { id: dashboardId } = await dashboardRepo.getUsersDashboard(teacherUser.id); + + const loggedInClient = await apiClient.login(teacherAccount); + + return { teacherUser, dashboardId, loggedInClient }; + }; + it('should be able to rename group', async () => { - const user = setup(); - await em.persistAndFlush([user]); - const { id: dashboardId } = await dashboardRepo.getUsersDashboard(user.id); + const { loggedInClient, dashboardId, teacherUser } = await setup(); + const dashboard = new DashboardEntity(dashboardId, { grid: [ { pos: { x: 3, y: 3 }, gridElement: GridElement.FromPersistedGroup(new ObjectId().toString(), 'drawing', [ - courseFactory.build({ students: [user], name: 'Perspective Drawing' }), - courseFactory.build({ students: [user], name: 'Shape Manipulation' }), + courseFactory.build({ students: [teacherUser], name: 'Perspective Drawing' }), + courseFactory.build({ students: [teacherUser], name: 'Shape Manipulation' }), ]), }, ], - userId: user.id, + userId: teacherUser.id, }); await dashboardRepo.persistAndFlush(dashboard); - currentUser = mapUserToCurrentUser(user); const params = { title: 'COURSESILOVE', }; - const response = await request(app.getHttpServer()) - .patch(`/dashboard/${dashboard.id}/element?x=3&y=3`) - .send(params); + const response = await loggedInClient.patch(`${dashboard.id}/element?x=3&y=3`).send(params); expect(response.status).toEqual(200); const body = response.body as DashboardResponse; expect(body.gridElements.length).toEqual(1); diff --git a/apps/server/src/modules/learnroom/controller/course-rooms.controller.spec.ts b/apps/server/src/modules/learnroom/controller/course-rooms.controller.spec.ts index 5a7a7df2667..cfe0160001f 100644 --- a/apps/server/src/modules/learnroom/controller/course-rooms.controller.spec.ts +++ b/apps/server/src/modules/learnroom/controller/course-rooms.controller.spec.ts @@ -2,14 +2,14 @@ import { createMock } from '@golevelup/ts-jest'; import { CopyApiResponse, CopyElementType, CopyStatus, CopyStatusEnum } from '@modules/copy-helper'; import { Test, TestingModule } from '@nestjs/testing'; import { EntityId } from '@shared/domain/types'; -import { currentUserFactory } from '@shared/testing'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; import { RoomBoardResponseMapper } from '../mapper/room-board-response.mapper'; import { RoomBoardDTO } from '../types'; import { CourseCopyUC } from '../uc/course-copy.uc'; -import { LessonCopyUC } from '../uc/lesson-copy.uc'; import { CourseRoomsUc } from '../uc/course-rooms.uc'; -import { SingleColumnBoardResponse } from './dto'; +import { LessonCopyUC } from '../uc/lesson-copy.uc'; import { CourseRoomsController } from './course-rooms.controller'; +import { SingleColumnBoardResponse } from './dto'; describe('course-rooms controller', () => { let controller: CourseRoomsController; diff --git a/apps/server/src/modules/learnroom/controller/dashboard.controller.spec.ts b/apps/server/src/modules/learnroom/controller/dashboard.controller.spec.ts index 9433419bde6..eb04eb55d3b 100644 --- a/apps/server/src/modules/learnroom/controller/dashboard.controller.spec.ts +++ b/apps/server/src/modules/learnroom/controller/dashboard.controller.spec.ts @@ -1,7 +1,7 @@ import { Test, TestingModule } from '@nestjs/testing'; import { DashboardEntity, GridElement, GridPosition } from '@shared/domain/entity'; import { EntityId, LearnroomMetadata, LearnroomTypes } from '@shared/domain/types'; -import { currentUserFactory } from '@shared/testing'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; import { DashboardUc } from '../uc/dashboard.uc'; import { DashboardController } from './dashboard.controller'; import { DashboardResponse } from './dto'; diff --git a/apps/server/src/modules/learnroom/domain/loggable/course-synchronization-stopped.loggable.spec.ts b/apps/server/src/modules/learnroom/domain/loggable/course-synchronization-stopped.loggable.spec.ts index e797ca0eb67..2f11e79dd83 100644 --- a/apps/server/src/modules/learnroom/domain/loggable/course-synchronization-stopped.loggable.spec.ts +++ b/apps/server/src/modules/learnroom/domain/loggable/course-synchronization-stopped.loggable.spec.ts @@ -1,4 +1,4 @@ -import { groupFactory } from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; import { courseFactory } from '../../testing'; import { CourseSynchronizationStoppedLoggable } from './course-synchronization-stopped.loggable'; diff --git a/apps/server/src/modules/learnroom/mapper/common-cartridge-export.mapper.spec.ts b/apps/server/src/modules/learnroom/mapper/common-cartridge-export.mapper.spec.ts index 0e4bdc92e82..858f349bba2 100644 --- a/apps/server/src/modules/learnroom/mapper/common-cartridge-export.mapper.spec.ts +++ b/apps/server/src/modules/learnroom/mapper/common-cartridge-export.mapper.spec.ts @@ -1,5 +1,6 @@ import { faker } from '@faker-js/faker'; import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { linkElementFactory, richTextElementFactory } from '@modules/board/testing'; import { CommonCartridgeElementProps, CommonCartridgeElementType, @@ -15,8 +16,11 @@ import { import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { ComponentProperties, ComponentType } from '@shared/domain/entity'; -import { courseFactory, lessonFactory, setupEntities, taskFactory, userFactory } from '@shared/testing'; -import { linkElementFactory, richTextElementFactory } from '@modules/board/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LearnroomConfig } from '../learnroom.config'; import { CommonCartridgeExportMapper } from './common-cartridge-export.mapper'; diff --git a/apps/server/src/modules/learnroom/mapper/rolename.mapper.spec.ts b/apps/server/src/modules/learnroom/mapper/rolename.mapper.spec.ts index b00a9fdc4be..62b79946b0f 100644 --- a/apps/server/src/modules/learnroom/mapper/rolename.mapper.spec.ts +++ b/apps/server/src/modules/learnroom/mapper/rolename.mapper.spec.ts @@ -1,6 +1,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { RoleName } from '@shared/domain/interface'; -import { UserAndAccountTestFactory, courseFactory, roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@src/testing/factory/course.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { RoleNameMapper } from './rolename.mapper'; describe('rolename mapper', () => { diff --git a/apps/server/src/modules/learnroom/mapper/room-board-response.mapper.spec.ts b/apps/server/src/modules/learnroom/mapper/room-board-response.mapper.spec.ts index 6b8803f8a90..87121637fb9 100644 --- a/apps/server/src/modules/learnroom/mapper/room-board-response.mapper.spec.ts +++ b/apps/server/src/modules/learnroom/mapper/room-board-response.mapper.spec.ts @@ -1,7 +1,9 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, setupEntities, taskFactory } from '@shared/testing'; import { BoardLayout } from '@src/modules/board'; +import { courseFactory } from '@src/testing/factory/course.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; import { BoardElementResponse, SingleColumnBoardResponse } from '../controller/dto'; import { ColumnBoardMetaData, RoomBoardDTO, RoomBoardElementTypes } from '../types'; import { RoomBoardResponseMapper } from './room-board-response.mapper'; diff --git a/apps/server/src/modules/learnroom/repo/mikro-orm/course.repo.integration.spec.ts b/apps/server/src/modules/learnroom/repo/mikro-orm/course.repo.integration.spec.ts index 958016f1d8d..adb9e0b05b3 100644 --- a/apps/server/src/modules/learnroom/repo/mikro-orm/course.repo.integration.spec.ts +++ b/apps/server/src/modules/learnroom/repo/mikro-orm/course.repo.integration.spec.ts @@ -15,15 +15,13 @@ import { User, } from '@shared/domain/entity'; import { SortOrder } from '@shared/domain/interface'; -import { - cleanupCollections, - courseFactory as courseEntityFactory, - courseGroupFactory as courseGroupEntityFactory, - groupEntityFactory, - groupFactory, - schoolEntityFactory, - userFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory as courseEntityFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory as courseGroupEntityFactory } from '@testing/factory/coursegroup.factory'; +import { groupFactory } from '@testing/factory/domainobject'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { Course, COURSE_REPO, CourseProps, CourseStatus } from '../../domain'; import { courseFactory } from '../../testing'; import { CourseMikroOrmRepo } from './course.repo'; diff --git a/apps/server/src/modules/learnroom/service/board-copy.service.spec.ts b/apps/server/src/modules/learnroom/service/board-copy.service.spec.ts index 376f89eec5d..1d71479fda6 100644 --- a/apps/server/src/modules/learnroom/service/board-copy.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/board-copy.service.spec.ts @@ -9,22 +9,22 @@ import { AuthorizableObject } from '@shared/domain/domain-object'; import { LegacyBoard } from '@shared/domain/entity'; import { EntityId } from '@shared/domain/types'; import { LegacyBoardRepo } from '@shared/repo'; -import { - boardFactory, - columnboardBoardElementFactory, - columnBoardNodeFactory, - courseFactory, - lessonBoardElementFactory, - lessonFactory, - setupEntities, - taskBoardElementFactory, - taskFactory, - userFactory, -} from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; import { CopyColumnBoardParams } from '@src/modules/board/service/internal'; import { columnBoardFactory } from '@src/modules/board/testing'; import { StorageLocation } from '@src/modules/files-storage/interface'; +import { boardFactory } from '@testing/factory/board.factory'; +import { + columnboardBoardElementFactory, + lessonBoardElementFactory, + taskBoardElementFactory, +} from '@testing/factory/boardelement.factory'; +import { columnBoardNodeFactory } from '@testing/factory/column-board-node.factory'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ColumnBoardNodeRepo } from '../repo'; import { BoardCopyService } from './board-copy.service'; diff --git a/apps/server/src/modules/learnroom/service/common-cartridge-export.service.spec.ts b/apps/server/src/modules/learnroom/service/common-cartridge-export.service.spec.ts index 4cd4ff7fab0..86ccf17fcda 100644 --- a/apps/server/src/modules/learnroom/service/common-cartridge-export.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/common-cartridge-export.service.spec.ts @@ -15,7 +15,10 @@ import { TaskService } from '@modules/task'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { ComponentType } from '@shared/domain/entity'; -import { courseFactory, lessonFactory, setupEntities, taskFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; import AdmZip from 'adm-zip'; import { CommonCartridgeExportMapper } from '../mapper/common-cartridge-export.mapper'; diff --git a/apps/server/src/modules/learnroom/service/common-cartridge-import.service.spec.ts b/apps/server/src/modules/learnroom/service/common-cartridge-import.service.spec.ts index 6607bcb5784..acdf1e53fe3 100644 --- a/apps/server/src/modules/learnroom/service/common-cartridge-import.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/common-cartridge-import.service.spec.ts @@ -2,9 +2,10 @@ import { DeepMocked, createMock } from '@golevelup/ts-jest'; import { MikroORM } from '@mikro-orm/core'; import { Test, TestingModule } from '@nestjs/testing'; import { InputFormat } from '@shared/domain/types'; -import { setupEntities, userFactory } from '@shared/testing'; import { BoardNodeFactory, BoardNodeService } from '@src/modules/board'; import { LinkElement, RichTextElement } from '@src/modules/board/domain'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { readFile } from 'fs/promises'; import { CommonCartridgeImportMapper } from '../mapper/common-cartridge-import.mapper'; import { CommonCartridgeImportService } from './common-cartridge-import.service'; diff --git a/apps/server/src/modules/learnroom/service/course-copy.service.spec.ts b/apps/server/src/modules/learnroom/service/course-copy.service.spec.ts index 41f9cf8e443..ca4cc870041 100644 --- a/apps/server/src/modules/learnroom/service/course-copy.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/course-copy.service.spec.ts @@ -2,23 +2,21 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { CopyElementType, CopyHelperService, CopyStatus, CopyStatusEnum } from '@modules/copy-helper'; import { LessonCopyService } from '@modules/lesson/service'; import { ToolContextType } from '@modules/tool/common/enum'; -import { SchoolExternalTool } from '@modules/tool/school-external-tool/domain'; import { ContextExternalTool, CopyContextExternalToolRejectData } from '@modules/tool/context-external-tool/domain'; import { ContextExternalToolService } from '@modules/tool/context-external-tool/service'; +import { SchoolExternalTool } from '@modules/tool/school-external-tool/domain'; import { schoolExternalToolFactory } from '@modules/tool/school-external-tool/testing'; import { ToolConfig } from '@modules/tool/tool-config'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { Course } from '@shared/domain/entity'; import { CourseRepo, LegacyBoardRepo, UserRepo } from '@shared/repo'; -import { - boardFactory, - courseFactory, - courseGroupFactory, - schoolEntityFactory, - setupEntities, - userFactory, -} from '@shared/testing'; +import { boardFactory } from '@testing/factory/board.factory'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { contextExternalToolFactory, copyContextExternalToolRejectDataFactory, diff --git a/apps/server/src/modules/learnroom/service/course-do.service.spec.ts b/apps/server/src/modules/learnroom/service/course-do.service.spec.ts index 4710ecc4aaa..61bebbe4be7 100644 --- a/apps/server/src/modules/learnroom/service/course-do.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/course-do.service.spec.ts @@ -6,7 +6,7 @@ import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { Page } from '@shared/domain/domainobject'; import { IFindOptions, SortOrder } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; -import { groupFactory } from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; import { Course, COURSE_REPO, CourseFilter, CourseRepo } from '../domain'; import { courseFactory } from '../testing'; import { CourseDoService } from './course-do.service'; diff --git a/apps/server/src/modules/learnroom/service/course-rooms.service.spec.ts b/apps/server/src/modules/learnroom/service/course-rooms.service.spec.ts index 17a70d49615..9c3b3b34709 100644 --- a/apps/server/src/modules/learnroom/service/course-rooms.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/course-rooms.service.spec.ts @@ -5,15 +5,13 @@ import { LessonService } from '@modules/lesson'; import { TaskService } from '@modules/task'; import { Test, TestingModule } from '@nestjs/testing'; import { LegacyBoardRepo } from '@shared/repo'; -import { - boardFactory, - columnBoardNodeFactory, - courseFactory, - lessonFactory, - setupEntities, - taskFactory, - userFactory, -} from '@shared/testing'; +import { boardFactory } from '@testing/factory/board.factory'; +import { columnBoardNodeFactory } from '@testing/factory/column-board-node.factory'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ColumnBoardNodeRepo } from '../repo'; import { CourseRoomsService } from './course-rooms.service'; diff --git a/apps/server/src/modules/learnroom/service/course-sync.service.spec.ts b/apps/server/src/modules/learnroom/service/course-sync.service.spec.ts index 71a0e446572..b75369d5051 100644 --- a/apps/server/src/modules/learnroom/service/course-sync.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/course-sync.service.spec.ts @@ -5,7 +5,10 @@ import { RoleDto, RoleService } from '@modules/role'; import { Test, TestingModule } from '@nestjs/testing'; import { SyncAttribute } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; -import { groupFactory, roleDtoFactory, setupEntities, userFactory } from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; +import { roleDtoFactory } from '@testing/factory/role-dto.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Course, COURSE_REPO, diff --git a/apps/server/src/modules/learnroom/service/course.service.spec.ts b/apps/server/src/modules/learnroom/service/course.service.spec.ts index c6c6d220e12..1b6dedb2f24 100644 --- a/apps/server/src/modules/learnroom/service/course.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/course.service.spec.ts @@ -12,8 +12,10 @@ import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; import { Course as CourseEntity } from '@shared/domain/entity'; import { CourseRepo as LegacyCourseRepo, UserRepo } from '@shared/repo'; -import { courseFactory as courseEntityFactory, setupEntities, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { CourseService } from './course.service'; @@ -89,9 +91,9 @@ describe('CourseService', () => { describe('when finding by userId', () => { const setup = () => { const user = userFactory.buildWithId(); - const course1 = courseEntityFactory.buildWithId({ students: [user] }); - const course2 = courseEntityFactory.buildWithId({ teachers: [user] }); - const course3 = courseEntityFactory.buildWithId({ substitutionTeachers: [user] }); + const course1 = courseFactory.buildWithId({ students: [user] }); + const course2 = courseFactory.buildWithId({ teachers: [user] }); + const course3 = courseFactory.buildWithId({ substitutionTeachers: [user] }); const allCourses = [course1, course2, course3]; userRepo.findById.mockResolvedValue(user); @@ -125,9 +127,9 @@ describe('CourseService', () => { describe('when deleting by userId', () => { const setup = () => { const user = userFactory.buildWithId(); - const course1 = courseEntityFactory.buildWithId({ students: [user] }); - const course2 = courseEntityFactory.buildWithId({ teachers: [user] }); - const course3 = courseEntityFactory.buildWithId({ substitutionTeachers: [user] }); + const course1 = courseFactory.buildWithId({ students: [user] }); + const course2 = courseFactory.buildWithId({ teachers: [user] }); + const course3 = courseFactory.buildWithId({ substitutionTeachers: [user] }); const allCourses = [course1, course2, course3]; userRepo.findById.mockResolvedValue(user); @@ -175,7 +177,7 @@ describe('CourseService', () => { describe('create', () => { const setup = () => { - const course = courseEntityFactory.buildWithId(); + const course = courseFactory.buildWithId(); legacyCourseRepo.createCourse.mockResolvedValueOnce(); return { course }; diff --git a/apps/server/src/modules/learnroom/service/coursegroup.service.spec.ts b/apps/server/src/modules/learnroom/service/coursegroup.service.spec.ts index eef83ec5fa9..32a5f793ef6 100644 --- a/apps/server/src/modules/learnroom/service/coursegroup.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/coursegroup.service.spec.ts @@ -11,8 +11,10 @@ import { deletionRequestFactory } from '@modules/deletion/domain/testing'; import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; import { CourseGroupRepo, UserRepo } from '@shared/repo'; -import { courseGroupFactory, setupEntities, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { CourseGroupService } from './coursegroup.service'; diff --git a/apps/server/src/modules/learnroom/service/dashboard.service.spec.ts b/apps/server/src/modules/learnroom/service/dashboard.service.spec.ts index d18cc8a8dfb..8a4179e790f 100644 --- a/apps/server/src/modules/learnroom/service/dashboard.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/dashboard.service.spec.ts @@ -13,8 +13,9 @@ import { Test, TestingModule } from '@nestjs/testing'; import { DashboardEntity, GridElement } from '@shared/domain/entity'; import { LearnroomMetadata, LearnroomTypes } from '@shared/domain/types'; import { DashboardElementRepo, IDashboardRepo, UserRepo } from '@shared/repo'; -import { setupEntities, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { DashboardService } from '.'; diff --git a/apps/server/src/modules/learnroom/service/group-deleted-handler.service.spec.ts b/apps/server/src/modules/learnroom/service/group-deleted-handler.service.spec.ts index 28b09c09108..7f1c824845e 100644 --- a/apps/server/src/modules/learnroom/service/group-deleted-handler.service.spec.ts +++ b/apps/server/src/modules/learnroom/service/group-deleted-handler.service.spec.ts @@ -3,8 +3,9 @@ import { MikroORM } from '@mikro-orm/core'; import { ObjectId } from '@mikro-orm/mongodb'; import { GroupDeletedEvent } from '@modules/group'; import { Test, TestingModule } from '@nestjs/testing'; -import { groupFactory, setupEntities } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { groupFactory } from '@testing/factory/domainobject'; +import { setupEntities } from '@testing/setup-entities'; import { Course } from '../domain'; import { courseFactory } from '../testing'; import { CourseDoService } from './course-do.service'; diff --git a/apps/server/src/modules/learnroom/testing/courseFactory.ts b/apps/server/src/modules/learnroom/testing/courseFactory.ts index 8f1f35e3dbe..c581b3caa61 100644 --- a/apps/server/src/modules/learnroom/testing/courseFactory.ts +++ b/apps/server/src/modules/learnroom/testing/courseFactory.ts @@ -1,4 +1,4 @@ -import { DomainObjectFactory } from '@shared/testing'; +import { DomainObjectFactory } from '@testing/factory/domainobject'; import { ObjectId } from 'bson'; import { Course, CourseProps } from '../domain'; diff --git a/apps/server/src/modules/learnroom/uc/course-copy.uc.spec.ts b/apps/server/src/modules/learnroom/uc/course-copy.uc.spec.ts index 826f1804bf3..92321cf72d1 100644 --- a/apps/server/src/modules/learnroom/uc/course-copy.uc.spec.ts +++ b/apps/server/src/modules/learnroom/uc/course-copy.uc.spec.ts @@ -6,7 +6,9 @@ import { CopyElementType, CopyStatusEnum } from '@modules/copy-helper'; import { ForbiddenException, InternalServerErrorException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { courseFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseCopyService } from '../service'; import { CourseCopyUC } from './course-copy.uc'; diff --git a/apps/server/src/modules/learnroom/uc/course-import.uc.spec.ts b/apps/server/src/modules/learnroom/uc/course-import.uc.spec.ts index fe50b3f5926..094b066d9c9 100644 --- a/apps/server/src/modules/learnroom/uc/course-import.uc.spec.ts +++ b/apps/server/src/modules/learnroom/uc/course-import.uc.spec.ts @@ -6,7 +6,9 @@ import { NotFoundException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { courseFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LearnroomConfig } from '../learnroom.config'; import { CommonCartridgeImportService } from '../service'; import { CourseImportUc } from './course-import.uc'; diff --git a/apps/server/src/modules/learnroom/uc/course-info.uc.spec.ts b/apps/server/src/modules/learnroom/uc/course-info.uc.spec.ts index 2369fc6404c..677061f33e2 100644 --- a/apps/server/src/modules/learnroom/uc/course-info.uc.spec.ts +++ b/apps/server/src/modules/learnroom/uc/course-info.uc.spec.ts @@ -11,7 +11,11 @@ import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Page } from '@shared/domain/domainobject'; import { IFindOptions, Permission, RoleName, SortOrder } from '@shared/domain/interface'; -import { groupFactory, setupEntities, UserAndAccountTestFactory, userDoFactory, userFactory } from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Course, CourseFilter, CourseSortProps, CourseStatus } from '../domain'; import { CourseDoService } from '../service'; import { courseFactory as courseDoFactory } from '../testing'; diff --git a/apps/server/src/modules/learnroom/uc/course-rooms.uc.spec.ts b/apps/server/src/modules/learnroom/uc/course-rooms.uc.spec.ts index 272144a9497..93e6bfceb2e 100644 --- a/apps/server/src/modules/learnroom/uc/course-rooms.uc.spec.ts +++ b/apps/server/src/modules/learnroom/uc/course-rooms.uc.spec.ts @@ -2,12 +2,17 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { CourseRepo, LegacyBoardRepo, TaskRepo, UserRepo } from '@shared/repo'; -import { boardFactory, courseFactory, lessonFactory, setupEntities, taskFactory, userFactory } from '@shared/testing'; +import { boardFactory } from '@testing/factory/board.factory'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseRoomsService } from '../service/course-rooms.service'; import { RoomBoardDTO } from '../types'; -import { RoomBoardDTOFactory } from './room-board-dto.factory'; import { CourseRoomsAuthorisationService } from './course-rooms.authorisation.service'; import { CourseRoomsUc } from './course-rooms.uc'; +import { RoomBoardDTOFactory } from './room-board-dto.factory'; describe('rooms usecase', () => { let uc: CourseRoomsUc; diff --git a/apps/server/src/modules/learnroom/uc/course-sync.uc.spec.ts b/apps/server/src/modules/learnroom/uc/course-sync.uc.spec.ts index 857f3c586f8..3418e62c7de 100644 --- a/apps/server/src/modules/learnroom/uc/course-sync.uc.spec.ts +++ b/apps/server/src/modules/learnroom/uc/course-sync.uc.spec.ts @@ -3,7 +3,9 @@ import { AuthorizationContextBuilder, AuthorizationService } from '@modules/auth import { GroupService } from '@modules/group'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { groupFactory, setupEntities, userFactory } from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseDoService } from '../service'; import { CourseSyncService } from '../service/course-sync.service'; import { courseFactory } from '../testing'; diff --git a/apps/server/src/modules/learnroom/uc/course.uc.spec.ts b/apps/server/src/modules/learnroom/uc/course.uc.spec.ts index b4bc0c86188..18b6f4ddb81 100644 --- a/apps/server/src/modules/learnroom/uc/course.uc.spec.ts +++ b/apps/server/src/modules/learnroom/uc/course.uc.spec.ts @@ -6,7 +6,10 @@ import { RoleDto, RoleService } from '@modules/role'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission, RoleName, SortOrder } from '@shared/domain/interface'; import { CourseRepo } from '@shared/repo'; -import { courseFactory, currentUserFactory, setupEntities, UserAndAccountTestFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseService } from '../service'; import { CourseUc } from './course.uc'; diff --git a/apps/server/src/modules/learnroom/uc/dashboard.uc.spec.ts b/apps/server/src/modules/learnroom/uc/dashboard.uc.spec.ts index 098482c143e..b7fa299d7aa 100644 --- a/apps/server/src/modules/learnroom/uc/dashboard.uc.spec.ts +++ b/apps/server/src/modules/learnroom/uc/dashboard.uc.spec.ts @@ -5,7 +5,7 @@ import { Course, DashboardEntity, GridElement } from '@shared/domain/entity'; import { SortOrder } from '@shared/domain/interface'; import { EntityId, LearnroomMetadata, LearnroomTypes } from '@shared/domain/types'; import { CourseRepo, IDashboardRepo } from '@shared/repo'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { DashboardUc } from './dashboard.uc'; const learnroomMock = (id: string, name: string) => { diff --git a/apps/server/src/modules/learnroom/uc/lesson-copy.uc.spec.ts b/apps/server/src/modules/learnroom/uc/lesson-copy.uc.spec.ts index a24643a8183..4f2cc62be7d 100644 --- a/apps/server/src/modules/learnroom/uc/lesson-copy.uc.spec.ts +++ b/apps/server/src/modules/learnroom/uc/lesson-copy.uc.spec.ts @@ -8,7 +8,10 @@ import { ForbiddenException, InternalServerErrorException } from '@nestjs/common import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; import { CourseRepo, UserRepo } from '@shared/repo'; -import { courseFactory, lessonFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LessonCopyUC } from './lesson-copy.uc'; describe('lesson copy uc', () => { diff --git a/apps/server/src/modules/learnroom/uc/room-board-dto.factory.spec.ts b/apps/server/src/modules/learnroom/uc/room-board-dto.factory.spec.ts index cb3bcbe26c5..0d2fe780f84 100644 --- a/apps/server/src/modules/learnroom/uc/room-board-dto.factory.spec.ts +++ b/apps/server/src/modules/learnroom/uc/room-board-dto.factory.spec.ts @@ -3,20 +3,17 @@ import { Configuration } from '@hpi-schul-cloud/commons/lib'; import { IConfig } from '@hpi-schul-cloud/commons/lib/interfaces/IConfig'; import { AuthorizationService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; -import { LegacyBoard, Course, LessonEntity, Task, TaskWithStatusVo, User } from '@shared/domain/entity'; -import { - boardFactory, - columnboardBoardElementFactory, - courseFactory, - lessonBoardElementFactory, - lessonFactory, - setupEntities, - taskFactory, - userFactory, -} from '@shared/testing'; +import { Course, LegacyBoard, LessonEntity, Task, TaskWithStatusVo, User } from '@shared/domain/entity'; +import { boardFactory } from '@testing/factory/board.factory'; +import { columnboardBoardElementFactory, lessonBoardElementFactory } from '@testing/factory/boardelement.factory'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LessonMetaData } from '../types'; -import { RoomBoardDTOFactory } from './room-board-dto.factory'; import { CourseRoomsAuthorisationService } from './course-rooms.authorisation.service'; +import { RoomBoardDTOFactory } from './room-board-dto.factory'; describe(RoomBoardDTOFactory.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/learnroom/uc/rooms.authorisation.service.spec.ts b/apps/server/src/modules/learnroom/uc/rooms.authorisation.service.spec.ts index 763a54d13cf..505f9059c8c 100644 --- a/apps/server/src/modules/learnroom/uc/rooms.authorisation.service.spec.ts +++ b/apps/server/src/modules/learnroom/uc/rooms.authorisation.service.spec.ts @@ -1,6 +1,10 @@ import { NotImplementedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, lessonFactory, setupEntities, taskFactory, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseRoomsAuthorisationService } from './course-rooms.authorisation.service'; describe('rooms authorisation service', () => { diff --git a/apps/server/src/modules/legacy-school/controller/api-test/school.administration.api.spec.ts b/apps/server/src/modules/legacy-school/controller/api-test/school.administration.api.spec.ts index 9fe7319cab6..4cb4d2e6e03 100644 --- a/apps/server/src/modules/legacy-school/controller/api-test/school.administration.api.spec.ts +++ b/apps/server/src/modules/legacy-school/controller/api-test/school.administration.api.spec.ts @@ -1,10 +1,12 @@ -import { XApiKeyGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; -import { TestApiClient, federalStateFactory, schoolYearFactory, storageProviderFactory } from '@shared/testing'; import { AdminApiServerTestModule } from '@src/modules/server/admin-api.server.module'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { storageProviderFactory } from '@testing/factory/storageprovider.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { AdminApiSchoolCreateResponseDto } from '../dto/response/admin-api-school-create.response.dto'; const baseRouteName = '/admin/schools'; @@ -13,20 +15,12 @@ describe('Admin API - Schools (API)', () => { let app: INestApplication; let testApiClient: TestApiClient; let em: EntityManager; - const API_KEY = '7ccd4e11-c6f6-48b0-81eb-cccf7922e7a4'; + const API_KEY = 'someotherkey'; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [AdminApiServerTestModule], - }) - .overrideGuard(XApiKeyGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - return req.headers['x-api-key'] === API_KEY; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); @@ -42,13 +36,17 @@ describe('Admin API - Schools (API)', () => { describe('without token', () => { it('should refuse with wrong token', async () => { const client = new TestApiClient(app, baseRouteName, 'thisisaninvalidapikey', true); + const response = await client.post(''); - expect(response.status).toEqual(403); + + expect(response.status).toEqual(401); }); it('should refuse without token', async () => { const client = new TestApiClient(app, baseRouteName, '', true); + const response = await client.post(''); - expect(response.status).toEqual(403); + + expect(response.status).toEqual(401); }); }); @@ -63,7 +61,9 @@ describe('Admin API - Schools (API)', () => { it('should return school', async () => { const { federalState } = await setup(); + const response = await testApiClient.post('', { name: 'schoolname', federalStateName: federalState.name }); + expect(response.status).toEqual(201); const result = response.body as AdminApiSchoolCreateResponseDto; expect(result.id).toBeDefined(); diff --git a/apps/server/src/modules/legacy-school/controller/api-test/school.api.spec.ts b/apps/server/src/modules/legacy-school/controller/api-test/school.api.spec.ts index 42eebe94443..2411bc7c4b5 100644 --- a/apps/server/src/modules/legacy-school/controller/api-test/school.api.spec.ts +++ b/apps/server/src/modules/legacy-school/controller/api-test/school.api.spec.ts @@ -5,14 +5,12 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { - cleanupCollections, - schoolEntityFactory, - schoolSystemOptionsEntityFactory, - systemEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolSystemOptionsEntityFactory } from '@testing/factory/school-system-options-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { SchoolSystemOptionsEntity } from '../../entity'; import { ProvisioningOptionsInterface } from '../../interface'; import { SchulConneXProvisioningOptionsResponse } from '../dto'; diff --git a/apps/server/src/modules/legacy-school/repo/school-system-options.repo.spec.ts b/apps/server/src/modules/legacy-school/repo/school-system-options.repo.spec.ts index 618b56a4773..582306b6a9c 100644 --- a/apps/server/src/modules/legacy-school/repo/school-system-options.repo.spec.ts +++ b/apps/server/src/modules/legacy-school/repo/school-system-options.repo.spec.ts @@ -4,12 +4,10 @@ import { SystemEntity } from '@modules/system/entity'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { - schoolEntityFactory, - schoolSystemOptionsEntityFactory, - schoolSystemOptionsFactory, - systemEntityFactory, -} from '@shared/testing'; +import { schoolSystemOptionsFactory } from '@testing/factory/domainobject'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolSystemOptionsEntityFactory } from '@testing/factory/school-system-options-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; import { SchoolSystemOptions, SchulConneXProvisioningOptions } from '../domain'; import { SchoolSystemOptionsEntity } from '../entity'; import { ProvisioningStrategyMissingLoggableException } from '../loggable'; diff --git a/apps/server/src/modules/legacy-school/repo/schoolyear.repo.integration.spec.ts b/apps/server/src/modules/legacy-school/repo/schoolyear.repo.integration.spec.ts index 0d2f510f467..17af7ebf673 100644 --- a/apps/server/src/modules/legacy-school/repo/schoolyear.repo.integration.spec.ts +++ b/apps/server/src/modules/legacy-school/repo/schoolyear.repo.integration.spec.ts @@ -2,8 +2,8 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolYearEntity } from '@shared/domain/entity'; -import { cleanupCollections } from '@shared/testing'; -import { schoolYearFactory } from '@shared/testing/factory/schoolyear.factory'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; import { SchoolYearRepo } from './schoolyear.repo'; describe('schoolyear repo', () => { diff --git a/apps/server/src/modules/legacy-school/service/federal-state.service.spec.ts b/apps/server/src/modules/legacy-school/service/federal-state.service.spec.ts index 96ca86ce3a5..af43f827058 100644 --- a/apps/server/src/modules/legacy-school/service/federal-state.service.spec.ts +++ b/apps/server/src/modules/legacy-school/service/federal-state.service.spec.ts @@ -2,7 +2,8 @@ import { DeepMocked, createMock } from '@golevelup/ts-jest'; import { Test, TestingModule } from '@nestjs/testing'; import { FederalStateEntity } from '@shared/domain/entity'; import { FederalStateRepo } from '@shared/repo'; -import { federalStateFactory, setupEntities } from '@shared/testing'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FederalStateNames } from '../types/federal-state-names.enum'; import { FederalStateService } from './federal-state.service'; diff --git a/apps/server/src/modules/legacy-school/service/legacy-school.service.spec.ts b/apps/server/src/modules/legacy-school/service/legacy-school.service.spec.ts index ff30ad2d7ec..820efa27fee 100644 --- a/apps/server/src/modules/legacy-school/service/legacy-school.service.spec.ts +++ b/apps/server/src/modules/legacy-school/service/legacy-school.service.spec.ts @@ -4,13 +4,11 @@ import { LegacySchoolDo } from '@shared/domain/domainobject'; import { SchoolFeature } from '@shared/domain/types'; import { LegacySchoolRepo } from '@shared/repo'; import { StorageProviderRepo } from '@shared/repo/storageprovider'; -import { - federalStateFactory, - legacySchoolDoFactory, - schoolYearFactory, - setupEntities, - storageProviderFactory, -} from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { storageProviderFactory } from '@testing/factory/storageprovider.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FederalStateService } from './federal-state.service'; import { LegacySchoolService } from './legacy-school.service'; import { SchoolYearService } from './school-year.service'; diff --git a/apps/server/src/modules/legacy-school/service/school-system-options.service.spec.ts b/apps/server/src/modules/legacy-school/service/school-system-options.service.spec.ts index 0bbcf5c46f8..d0ec6e12af7 100644 --- a/apps/server/src/modules/legacy-school/service/school-system-options.service.spec.ts +++ b/apps/server/src/modules/legacy-school/service/school-system-options.service.spec.ts @@ -1,7 +1,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { schoolSystemOptionsFactory } from '@shared/testing'; +import { schoolSystemOptionsFactory } from '@testing/factory/domainobject'; import { SchoolSystemOptions, SchulConneXProvisioningOptions } from '../domain'; import { SchulConneXProvisioningOptionsInterface } from '../interface'; import { ProvisioningOptionsInvalidTypeLoggableException } from '../loggable'; diff --git a/apps/server/src/modules/legacy-school/service/school-year.service.spec.ts b/apps/server/src/modules/legacy-school/service/school-year.service.spec.ts index e2ba8097c36..b6a0f9e728d 100644 --- a/apps/server/src/modules/legacy-school/service/school-year.service.spec.ts +++ b/apps/server/src/modules/legacy-school/service/school-year.service.spec.ts @@ -1,8 +1,8 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolYearEntity } from '@shared/domain/entity'; -import { setupEntities } from '@shared/testing'; -import { schoolYearFactory } from '@shared/testing/factory/schoolyear.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SchoolYearRepo } from '../repo'; import { SchoolYearService } from './school-year.service'; diff --git a/apps/server/src/modules/legacy-school/service/schulconnex-provisioning-options-update.service.spec.ts b/apps/server/src/modules/legacy-school/service/schulconnex-provisioning-options-update.service.spec.ts index 3e3b1f37f29..a4210ea8128 100644 --- a/apps/server/src/modules/legacy-school/service/schulconnex-provisioning-options-update.service.spec.ts +++ b/apps/server/src/modules/legacy-school/service/schulconnex-provisioning-options-update.service.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Group, GroupService, GroupTypes } from '@modules/group'; import { Test, TestingModule } from '@nestjs/testing'; import { Page } from '@shared/domain/domainobject'; -import { groupFactory, schoolSystemOptionsFactory } from '@shared/testing'; +import { groupFactory, schoolSystemOptionsFactory } from '@testing/factory/domainobject'; import { SchoolSystemOptions, SchulConneXProvisioningOptions } from '../domain'; import { SchulconnexProvisioningOptionsUpdateService } from './schulconnex-provisioning-options-update.service'; diff --git a/apps/server/src/modules/legacy-school/service/validation/school-validation.service.spec.ts b/apps/server/src/modules/legacy-school/service/validation/school-validation.service.spec.ts index e6d56b75c6e..08acc6cd0d0 100644 --- a/apps/server/src/modules/legacy-school/service/validation/school-validation.service.spec.ts +++ b/apps/server/src/modules/legacy-school/service/validation/school-validation.service.spec.ts @@ -3,7 +3,7 @@ import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo } from '@shared/domain/domainobject'; import { LegacySchoolRepo } from '@shared/repo'; -import { legacySchoolDoFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; import { SchoolNumberDuplicateLoggableException } from '../../loggable'; import { SchoolValidationService } from './school-validation.service'; diff --git a/apps/server/src/modules/legacy-school/uc/school-system-options.uc.spec.ts b/apps/server/src/modules/legacy-school/uc/school-system-options.uc.spec.ts index 1699dccdb8a..d986f830e82 100644 --- a/apps/server/src/modules/legacy-school/uc/school-system-options.uc.spec.ts +++ b/apps/server/src/modules/legacy-school/uc/school-system-options.uc.spec.ts @@ -7,7 +7,9 @@ import { Test, TestingModule } from '@nestjs/testing'; import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { Permission } from '@shared/domain/interface'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { schoolSystemOptionsFactory, setupEntities, userFactory } from '@shared/testing'; +import { schoolSystemOptionsFactory } from '@testing/factory/domainobject'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { AnyProvisioningOptions, SchoolSystemOptions, SchulConneXProvisioningOptions } from '../domain'; import { ProvisioningStrategyMissingLoggableException } from '../loggable'; import { ProvisioningOptionsUpdateService, SchoolSystemOptionsService } from '../service'; diff --git a/apps/server/src/modules/lesson/controller/api-test/lesson-delete.api.spec.ts b/apps/server/src/modules/lesson/controller/api-test/lesson-delete.api.spec.ts index 0dc0a82d606..0bf5ac67c57 100644 --- a/apps/server/src/modules/lesson/controller/api-test/lesson-delete.api.spec.ts +++ b/apps/server/src/modules/lesson/controller/api-test/lesson-delete.api.spec.ts @@ -1,18 +1,16 @@ import { createMock } from '@golevelup/ts-jest'; import { EntityManager } from '@mikro-orm/core'; +import { ObjectId } from '@mikro-orm/mongodb'; import { FilesStorageClientAdapterService } from '@modules/files-storage-client'; import { ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { LessonEntity } from '@shared/domain/entity'; -import { - TestApiClient, - UserAndAccountTestFactory, - courseFactory, - courseGroupFactory, - lessonFactory, -} from '@shared/testing'; -import { ObjectId } from '@mikro-orm/mongodb'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; describe('Lesson Controller (API) - delete', () => { let app: INestApplication; diff --git a/apps/server/src/modules/lesson/controller/api-test/lesson-get.api.spec.ts b/apps/server/src/modules/lesson/controller/api-test/lesson-get.api.spec.ts index 632a2e6fc65..d52ceeab967 100644 --- a/apps/server/src/modules/lesson/controller/api-test/lesson-get.api.spec.ts +++ b/apps/server/src/modules/lesson/controller/api-test/lesson-get.api.spec.ts @@ -2,14 +2,6 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { - TestApiClient, - UserAndAccountTestFactory, - courseFactory, - courseGroupFactory, - lessonFactory, - materialFactory, -} from '@shared/testing'; import { ComponentEtherpadProperties, ComponentGeogebraProperties, @@ -20,6 +12,12 @@ import { ComponentTextProperties, ComponentType, } from '@shared/domain/entity'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { materialFactory } from '@testing/factory/material.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { LessonResponse } from '../dto'; describe('Lesson Controller (API) - GET /lessons/:lessonId', () => { diff --git a/apps/server/src/modules/lesson/controller/api-test/lesson-list.api.spec.ts b/apps/server/src/modules/lesson/controller/api-test/lesson-list.api.spec.ts index 0caf82fe949..8068df334fe 100644 --- a/apps/server/src/modules/lesson/controller/api-test/lesson-list.api.spec.ts +++ b/apps/server/src/modules/lesson/controller/api-test/lesson-list.api.spec.ts @@ -2,7 +2,10 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, courseFactory, lessonFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { LessonMetadataListResponse } from '../dto'; describe('Lesson Controller (API) - GET list of lessons from course /lessons/course/:courseId', () => { diff --git a/apps/server/src/modules/lesson/controller/api-test/lesson-tasks.api.spec.ts b/apps/server/src/modules/lesson/controller/api-test/lesson-tasks.api.spec.ts index b2115060a46..f21aae879c8 100644 --- a/apps/server/src/modules/lesson/controller/api-test/lesson-tasks.api.spec.ts +++ b/apps/server/src/modules/lesson/controller/api-test/lesson-tasks.api.spec.ts @@ -1,8 +1,12 @@ import { EntityManager } from '@mikro-orm/core'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, lessonFactory, taskFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; import { ServerTestModule } from '@src/modules/server'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; describe('Lesson Controller (API) - GET list of lesson tasks /lessons/:lessonId/tasks', () => { let module: TestingModule; diff --git a/apps/server/src/modules/lesson/controller/mapper/lesson.mapper.spec.ts b/apps/server/src/modules/lesson/controller/mapper/lesson.mapper.spec.ts index 73a1c8cc796..3c064811305 100644 --- a/apps/server/src/modules/lesson/controller/mapper/lesson.mapper.spec.ts +++ b/apps/server/src/modules/lesson/controller/mapper/lesson.mapper.spec.ts @@ -1,5 +1,8 @@ import { MikroORM } from '@mikro-orm/core'; -import { setupEntities, submissionFactory, taskFactory, userFactory } from '@shared/testing'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LessonLinkedTaskResponse } from '../dto/lesson-linked-task.response'; import { LessonMapper } from './lesson.mapper'; diff --git a/apps/server/src/modules/lesson/repository/lesson.repo.integration.spec.ts b/apps/server/src/modules/lesson/repository/lesson.repo.integration.spec.ts index 3a5d979aa95..b968ea0e776 100644 --- a/apps/server/src/modules/lesson/repository/lesson.repo.integration.spec.ts +++ b/apps/server/src/modules/lesson/repository/lesson.repo.integration.spec.ts @@ -1,7 +1,11 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { ComponentProperties, ComponentType, LessonEntity } from '@shared/domain/entity'; -import { cleanupCollections, courseFactory, lessonFactory, materialFactory, taskFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { materialFactory } from '@testing/factory/material.factory'; +import { taskFactory } from '@testing/factory/task.factory'; import { MongoMemoryDatabaseModule } from '@infra/database'; diff --git a/apps/server/src/modules/lesson/service/lesson-copy.service.spec.ts b/apps/server/src/modules/lesson/service/lesson-copy.service.spec.ts index 0804e123d4b..8b986b59352 100644 --- a/apps/server/src/modules/lesson/service/lesson-copy.service.spec.ts +++ b/apps/server/src/modules/lesson/service/lesson-copy.service.spec.ts @@ -18,14 +18,12 @@ import { Material, } from '@shared/domain/entity'; import { EntityId } from '@shared/domain/types'; -import { - courseFactory, - lessonFactory, - materialFactory, - setupEntities, - taskFactory, - userFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { materialFactory } from '@testing/factory/material.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LessonRepo } from '../repository'; import { EtherpadService } from './etherpad.service'; import { LessonCopyService } from './lesson-copy.service'; diff --git a/apps/server/src/modules/lesson/service/lesson.service.spec.ts b/apps/server/src/modules/lesson/service/lesson.service.spec.ts index 95aa50bc708..739eae3666e 100644 --- a/apps/server/src/modules/lesson/service/lesson.service.spec.ts +++ b/apps/server/src/modules/lesson/service/lesson.service.spec.ts @@ -14,8 +14,9 @@ import { FilesStorageClientAdapterService } from '@modules/files-storage-client' import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; import { ComponentProperties, ComponentType } from '@shared/domain/entity'; -import { lessonFactory, setupEntities } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LessonRepo } from '../repository'; import { LessonService } from './lesson.service'; diff --git a/apps/server/src/modules/lesson/uc/lesson.uc.spec.ts b/apps/server/src/modules/lesson/uc/lesson.uc.spec.ts index ff436d84a1d..fd7fce96edd 100644 --- a/apps/server/src/modules/lesson/uc/lesson.uc.spec.ts +++ b/apps/server/src/modules/lesson/uc/lesson.uc.spec.ts @@ -3,7 +3,10 @@ import { AuthorizationContextBuilder, AuthorizationService } from '@modules/auth import { CourseService } from '@modules/learnroom/service'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { courseFactory, lessonFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { LessonService } from '../service'; import { LessonUC } from './lesson.uc'; diff --git a/apps/server/src/modules/lti-tool/service/lti-tool.service.spec.ts b/apps/server/src/modules/lti-tool/service/lti-tool.service.spec.ts index dc3a44e280c..b5d887f4d7b 100644 --- a/apps/server/src/modules/lti-tool/service/lti-tool.service.spec.ts +++ b/apps/server/src/modules/lti-tool/service/lti-tool.service.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Test, TestingModule } from '@nestjs/testing'; import { LtiToolDO } from '@shared/domain/domainobject'; import { LtiToolRepo } from '@shared/repo'; -import { ltiToolDOFactory } from '@shared/testing'; +import { ltiToolDOFactory } from '@testing/factory/domainobject'; import { LtiToolService } from './lti-tool.service'; describe('LtiToolService', () => { diff --git a/apps/server/src/modules/management/controller/api-test/database-management.api.spec.ts b/apps/server/src/modules/management/controller/api-test/database-management.api.spec.ts index c80ae7bc58f..6bcfb20f416 100644 --- a/apps/server/src/modules/management/controller/api-test/database-management.api.spec.ts +++ b/apps/server/src/modules/management/controller/api-test/database-management.api.spec.ts @@ -6,7 +6,7 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ManagementServerTestModule } from '@modules/management/management-server.module'; import { ExpressAdapter, NestExpressApplication } from '@nestjs/platform-express'; import { Test, TestingModule } from '@nestjs/testing'; -import { createCollections } from '@shared/testing'; +import { createCollections } from '@testing/create-collections'; import request from 'supertest'; describe('Database Management Controller (API)', () => { diff --git a/apps/server/src/modules/management/seed-data/federalstates.ts b/apps/server/src/modules/management/seed-data/federalstates.ts index 403814e9c0e..c9e69566e6c 100644 --- a/apps/server/src/modules/management/seed-data/federalstates.ts +++ b/apps/server/src/modules/management/seed-data/federalstates.ts @@ -1,6 +1,6 @@ -import { CountyEmbeddable, FederalStateProperties } from '@shared/domain/entity/federal-state.entity'; -import { federalStateFactory } from '@shared/testing/factory/federal-state.factory'; import { ObjectId } from '@mikro-orm/mongodb'; +import { CountyEmbeddable, FederalStateProperties } from '@shared/domain/entity/federal-state.entity'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; import { DeepPartial } from 'fishery'; type SeedFederalStateProperties = Omit & { diff --git a/apps/server/src/modules/management/seed-data/generateSeedData.spec.ts b/apps/server/src/modules/management/seed-data/generateSeedData.spec.ts index 7d60f7b5e8f..ed250716451 100644 --- a/apps/server/src/modules/management/seed-data/generateSeedData.spec.ts +++ b/apps/server/src/modules/management/seed-data/generateSeedData.spec.ts @@ -1,4 +1,4 @@ -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { generateSeedData } from './generateSeedData'; import * as roleModule from './roles'; diff --git a/apps/server/src/modules/management/seed-data/roles.spec.ts b/apps/server/src/modules/management/seed-data/roles.spec.ts index 43f74d7d7e8..74d80568c73 100644 --- a/apps/server/src/modules/management/seed-data/roles.spec.ts +++ b/apps/server/src/modules/management/seed-data/roles.spec.ts @@ -1,5 +1,5 @@ import { RoleName } from '@shared/domain/interface'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import * as roleModule from './roles'; describe('Role seed data generation', () => { diff --git a/apps/server/src/modules/management/seed-data/roles.ts b/apps/server/src/modules/management/seed-data/roles.ts index 810533204fa..200fc609451 100644 --- a/apps/server/src/modules/management/seed-data/roles.ts +++ b/apps/server/src/modules/management/seed-data/roles.ts @@ -2,7 +2,7 @@ import { Role, RoleProperties } from '@shared/domain/entity'; import { Permission, RoleName } from '@shared/domain/interface'; -import { roleFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; import { DeepPartial } from 'fishery'; type SeedRoleProperties = Omit & { diff --git a/apps/server/src/modules/management/seed-data/schools.ts b/apps/server/src/modules/management/seed-data/schools.ts index 3a6e6ce4bb6..105255bedd9 100644 --- a/apps/server/src/modules/management/seed-data/schools.ts +++ b/apps/server/src/modules/management/seed-data/schools.ts @@ -4,8 +4,9 @@ import { SystemEntity } from '@modules/system/entity'; import { FederalStateEntity, SchoolProperties, SchoolRoles, SchoolYearEntity } from '@shared/domain/entity'; import { LanguageType } from '@shared/domain/interface'; import { SchoolFeature, SchoolPurpose } from '@shared/domain/types'; -import { federalStateFactory, schoolEntityFactory } from '@shared/testing'; import { FileStorageType } from '@src/modules/school/domain/type/file-storage-type.enum'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; import { DeepPartial } from 'fishery'; import { EFederalState } from './federalstates'; import { SeedSchoolYearEnum } from './schoolyears'; diff --git a/apps/server/src/modules/management/seed-data/schoolyears.ts b/apps/server/src/modules/management/seed-data/schoolyears.ts index 0198a00a5bd..228bccf60c8 100644 --- a/apps/server/src/modules/management/seed-data/schoolyears.ts +++ b/apps/server/src/modules/management/seed-data/schoolyears.ts @@ -1,5 +1,5 @@ import { SchoolYearProperties } from '@shared/domain/entity'; -import { schoolYearFactory } from '@shared/testing/factory/schoolyear.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; import { DeepPartial } from 'fishery'; type SeedSchoolYearProperties = Pick & { diff --git a/apps/server/src/modules/management/seed-data/systems.ts b/apps/server/src/modules/management/seed-data/systems.ts index 1a9c531d870..01744f7ed0e 100644 --- a/apps/server/src/modules/management/seed-data/systems.ts +++ b/apps/server/src/modules/management/seed-data/systems.ts @@ -1,7 +1,7 @@ /* eslint-disable no-template-curly-in-string */ import { SystemEntityProps } from '@modules/system/entity'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { systemEntityFactory } from '@shared/testing'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; import { DeepPartial } from 'fishery'; type SystemPartial = DeepPartial & { diff --git a/apps/server/src/modules/management/uc/database-management.uc.spec.ts b/apps/server/src/modules/management/uc/database-management.uc.spec.ts index 13ba1d9b3ba..ea048d083ca 100644 --- a/apps/server/src/modules/management/uc/database-management.uc.spec.ts +++ b/apps/server/src/modules/management/uc/database-management.uc.spec.ts @@ -8,8 +8,8 @@ import { SystemEntity } from '@modules/system/entity'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { StorageProviderEntity } from '@shared/domain/entity'; -import { setupEntities } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { setupEntities } from '@testing/setup-entities'; import { BsonConverter } from '../converter/bson.converter'; import { generateSeedData } from '../seed-data/generateSeedData'; import { DatabaseManagementUc } from './database-management.uc'; diff --git a/apps/server/src/modules/me/api/test/me.controller.api.spec.ts b/apps/server/src/modules/me/api/test/me.controller.api.spec.ts index 8ca39c6dc8f..ae7f2a0296f 100644 --- a/apps/server/src/modules/me/api/test/me.controller.api.spec.ts +++ b/apps/server/src/modules/me/api/test/me.controller.api.spec.ts @@ -1,17 +1,15 @@ +import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; -import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { ExecutionContext, HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import type { User } from '@shared/domain/entity'; -import { - currentUserFactory, - schoolEntityFactory, - systemEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { ServerTestModule } from '@src/modules/server'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { Request } from 'express'; import { MeResponse } from '../dto'; diff --git a/apps/server/src/modules/media-source/repo/media-source.repo.spec.ts b/apps/server/src/modules/media-source/repo/media-source.repo.spec.ts index 068c40102da..4f950f11523 100644 --- a/apps/server/src/modules/media-source/repo/media-source.repo.spec.ts +++ b/apps/server/src/modules/media-source/repo/media-source.repo.spec.ts @@ -1,14 +1,14 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { MediaSource } from '../domain'; import { MediaSourceEntity, MediaSourceOauthConfigEmbeddable } from '../entity'; import { MediaSourceDataFormat } from '../enum'; -import { mediaSourceFactory, mediaSourceEntityFactory, mediaSourceOAuthConfigEmbeddableFactory } from '../testing'; -import { MediaSourceRepo } from './media-source.repo'; +import { mediaSourceEntityFactory, mediaSourceFactory, mediaSourceOAuthConfigEmbeddableFactory } from '../testing'; import { MediaSourceConfigMapper } from './media-source-config.mapper'; import { MediaSourceMapper } from './media-source.mapper'; +import { MediaSourceRepo } from './media-source.repo'; describe(MediaSourceRepo.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/media-source/testing/media-source-basic-auth-config.embeddable.factory.ts b/apps/server/src/modules/media-source/testing/media-source-basic-auth-config.embeddable.factory.ts index 989ca3c0512..249d76db207 100644 --- a/apps/server/src/modules/media-source/testing/media-source-basic-auth-config.embeddable.factory.ts +++ b/apps/server/src/modules/media-source/testing/media-source-basic-auth-config.embeddable.factory.ts @@ -1,4 +1,4 @@ -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaSourceBasicAuthConfigEmbeddable } from '../entity'; export const mediaSourceBasicConfigEmbeddableFactory = BaseFactory.define< diff --git a/apps/server/src/modules/media-source/testing/media-source-basic-auth-config.factory.ts b/apps/server/src/modules/media-source/testing/media-source-basic-auth-config.factory.ts index 6aa967d2a72..90a6209021c 100644 --- a/apps/server/src/modules/media-source/testing/media-source-basic-auth-config.factory.ts +++ b/apps/server/src/modules/media-source/testing/media-source-basic-auth-config.factory.ts @@ -1,4 +1,4 @@ -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaSourceBasicAuthConfig } from '../domain'; export const mediaSourceBasicAuthConfigFactory = BaseFactory.define< diff --git a/apps/server/src/modules/media-source/testing/media-source-entity.factory.ts b/apps/server/src/modules/media-source/testing/media-source-entity.factory.ts index 92d401dcc2c..d0544198634 100644 --- a/apps/server/src/modules/media-source/testing/media-source-entity.factory.ts +++ b/apps/server/src/modules/media-source/testing/media-source-entity.factory.ts @@ -1,9 +1,9 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaSourceEntity, MediaSourceEntityProps } from '../entity'; import { MediaSourceDataFormat } from '../enum'; -import { mediaSourceOAuthConfigEmbeddableFactory } from './media-source-oauth-config.embeddable.factory'; import { mediaSourceBasicConfigEmbeddableFactory } from './media-source-basic-auth-config.embeddable.factory'; +import { mediaSourceOAuthConfigEmbeddableFactory } from './media-source-oauth-config.embeddable.factory'; export const mediaSourceEntityFactory = BaseFactory.define( MediaSourceEntity, diff --git a/apps/server/src/modules/media-source/testing/media-source-oauth-config.embeddable.factory.ts b/apps/server/src/modules/media-source/testing/media-source-oauth-config.embeddable.factory.ts index 09d0ce473a1..c67532d1f4c 100644 --- a/apps/server/src/modules/media-source/testing/media-source-oauth-config.embeddable.factory.ts +++ b/apps/server/src/modules/media-source/testing/media-source-oauth-config.embeddable.factory.ts @@ -1,6 +1,6 @@ -import { BaseFactory } from '@shared/testing'; -import { MediaSourceAuthMethod } from '../enum'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaSourceOauthConfigEmbeddable } from '../entity'; +import { MediaSourceAuthMethod } from '../enum'; export const mediaSourceOAuthConfigEmbeddableFactory = BaseFactory.define< MediaSourceOauthConfigEmbeddable, diff --git a/apps/server/src/modules/media-source/testing/media-source-oauth-config.factory.ts b/apps/server/src/modules/media-source/testing/media-source-oauth-config.factory.ts index 6766991d9b3..4cde7a2dd83 100644 --- a/apps/server/src/modules/media-source/testing/media-source-oauth-config.factory.ts +++ b/apps/server/src/modules/media-source/testing/media-source-oauth-config.factory.ts @@ -1,4 +1,4 @@ -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaSourceOauthConfig } from '../domain'; import { MediaSourceAuthMethod } from '../enum'; diff --git a/apps/server/src/modules/media-source/testing/media-source.factory.ts b/apps/server/src/modules/media-source/testing/media-source.factory.ts index 12a5ffa1bc0..755eec32d0f 100644 --- a/apps/server/src/modules/media-source/testing/media-source.factory.ts +++ b/apps/server/src/modules/media-source/testing/media-source.factory.ts @@ -1,10 +1,10 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { DeepPartial } from 'fishery'; -import { MediaSourceProps, MediaSource } from '../domain'; +import { MediaSource, MediaSourceProps } from '../domain'; import { MediaSourceDataFormat } from '../enum'; -import { mediaSourceOauthConfigFactory } from './media-source-oauth-config.factory'; import { mediaSourceBasicAuthConfigFactory } from './media-source-basic-auth-config.factory'; +import { mediaSourceOauthConfigFactory } from './media-source-oauth-config.factory'; class MediaSourceFactory extends BaseFactory { public withBasicAuthConfig(): this { diff --git a/apps/server/src/modules/meta-tag-extractor/controller/api-test/meta-tag-extractor-get-data.api.spec.ts b/apps/server/src/modules/meta-tag-extractor/controller/api-test/meta-tag-extractor-get-data.api.spec.ts index 2a6c2a93d90..87062dff8ee 100644 --- a/apps/server/src/modules/meta-tag-extractor/controller/api-test/meta-tag-extractor-get-data.api.spec.ts +++ b/apps/server/src/modules/meta-tag-extractor/controller/api-test/meta-tag-extractor-get-data.api.spec.ts @@ -2,7 +2,8 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { MetaTagExtractorService } from '../../service'; const URL = 'https://best-example.de/my-article'; diff --git a/apps/server/src/modules/meta-tag-extractor/service/meta-tag-external-url.service.spec.ts b/apps/server/src/modules/meta-tag-extractor/service/meta-tag-external-url.service.spec.ts index 241ac82de92..5445341a633 100644 --- a/apps/server/src/modules/meta-tag-extractor/service/meta-tag-external-url.service.spec.ts +++ b/apps/server/src/modules/meta-tag-extractor/service/meta-tag-external-url.service.spec.ts @@ -1,5 +1,5 @@ import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import axios, { CancelTokenSource } from 'axios'; import Stream from 'stream'; import { MetaTagExternalUrlService } from './meta-tag-external-url.service'; diff --git a/apps/server/src/modules/meta-tag-extractor/service/meta-tag-extractor.service.spec.ts b/apps/server/src/modules/meta-tag-extractor/service/meta-tag-extractor.service.spec.ts index b71567e85ed..3942d24ece5 100644 --- a/apps/server/src/modules/meta-tag-extractor/service/meta-tag-extractor.service.spec.ts +++ b/apps/server/src/modules/meta-tag-extractor/service/meta-tag-extractor.service.spec.ts @@ -1,7 +1,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Configuration } from '@hpi-schul-cloud/commons/lib'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { MetaTagExternalUrlService } from './meta-tag-external-url.service'; import { MetaTagExtractorService } from './meta-tag-extractor.service'; import { MetaTagInternalUrlService } from './meta-tag-internal-url.service'; diff --git a/apps/server/src/modules/meta-tag-extractor/service/meta-tag-internal-url.service.spec.ts b/apps/server/src/modules/meta-tag-extractor/service/meta-tag-internal-url.service.spec.ts index 5c290d58868..2bce0891797 100644 --- a/apps/server/src/modules/meta-tag-extractor/service/meta-tag-internal-url.service.spec.ts +++ b/apps/server/src/modules/meta-tag-extractor/service/meta-tag-internal-url.service.spec.ts @@ -1,7 +1,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Configuration } from '@hpi-schul-cloud/commons/lib'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { MetaData } from '../types'; import { MetaTagInternalUrlService } from './meta-tag-internal-url.service'; import { BoardUrlHandler, CourseUrlHandler, LessonUrlHandler, TaskUrlHandler } from './url-handler'; diff --git a/apps/server/src/modules/meta-tag-extractor/service/url-handler/board-url-handler.spec.ts b/apps/server/src/modules/meta-tag-extractor/service/url-handler/board-url-handler.spec.ts index 5160721477e..be2265d18e7 100644 --- a/apps/server/src/modules/meta-tag-extractor/service/url-handler/board-url-handler.spec.ts +++ b/apps/server/src/modules/meta-tag-extractor/service/url-handler/board-url-handler.spec.ts @@ -1,9 +1,9 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { ColumnBoardService, ColumnBoard } from '@modules/board'; +import { ColumnBoard, ColumnBoardService } from '@modules/board'; import { CourseService } from '@modules/learnroom'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { BoardUrlHandler } from './board-url-handler'; describe(BoardUrlHandler.name, () => { diff --git a/apps/server/src/modules/meta-tag-extractor/service/url-handler/course-url-handler.spec.ts b/apps/server/src/modules/meta-tag-extractor/service/url-handler/course-url-handler.spec.ts index 379a0eed424..e5446aa6a40 100644 --- a/apps/server/src/modules/meta-tag-extractor/service/url-handler/course-url-handler.spec.ts +++ b/apps/server/src/modules/meta-tag-extractor/service/url-handler/course-url-handler.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { CourseService } from '@modules/learnroom'; import { Test, TestingModule } from '@nestjs/testing'; import { Course } from '@shared/domain/entity'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { CourseUrlHandler } from './course-url-handler'; describe(CourseUrlHandler.name, () => { diff --git a/apps/server/src/modules/meta-tag-extractor/service/url-handler/lesson-url-handler.spec.ts b/apps/server/src/modules/meta-tag-extractor/service/url-handler/lesson-url-handler.spec.ts index aa77d0e6ef5..f028d0ad773 100644 --- a/apps/server/src/modules/meta-tag-extractor/service/url-handler/lesson-url-handler.spec.ts +++ b/apps/server/src/modules/meta-tag-extractor/service/url-handler/lesson-url-handler.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { LessonService } from '@modules/lesson'; import { Test, TestingModule } from '@nestjs/testing'; import { LessonEntity } from '@shared/domain/entity'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { LessonUrlHandler } from './lesson-url-handler'; describe(LessonUrlHandler.name, () => { diff --git a/apps/server/src/modules/meta-tag-extractor/service/url-handler/task-url-handler.spec.ts b/apps/server/src/modules/meta-tag-extractor/service/url-handler/task-url-handler.spec.ts index 52a3a8713a2..a5fc8f3d611 100644 --- a/apps/server/src/modules/meta-tag-extractor/service/url-handler/task-url-handler.spec.ts +++ b/apps/server/src/modules/meta-tag-extractor/service/url-handler/task-url-handler.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { TaskService } from '@modules/task'; import { Test, TestingModule } from '@nestjs/testing'; import { Task } from '@shared/domain/entity'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { TaskUrlHandler } from './task-url-handler'; describe(TaskUrlHandler.name, () => { diff --git a/apps/server/src/modules/meta-tag-extractor/uc/meta-tag-extractor.uc.spec.ts b/apps/server/src/modules/meta-tag-extractor/uc/meta-tag-extractor.uc.spec.ts index f5aa0c6cd72..5dba9e6e461 100644 --- a/apps/server/src/modules/meta-tag-extractor/uc/meta-tag-extractor.uc.spec.ts +++ b/apps/server/src/modules/meta-tag-extractor/uc/meta-tag-extractor.uc.spec.ts @@ -2,7 +2,8 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { AuthorizationService } from '@modules/authorization'; import { UnauthorizedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { MetaTagExtractorService } from '../service'; import { MetaTagExtractorUc } from './meta-tag-extractor.uc'; diff --git a/apps/server/src/modules/news/controller/api-test/news.api.spec.ts b/apps/server/src/modules/news/controller/api-test/news.api.spec.ts index db4c401a6cc..6415140a874 100644 --- a/apps/server/src/modules/news/controller/api-test/news.api.spec.ts +++ b/apps/server/src/modules/news/controller/api-test/news.api.spec.ts @@ -1,26 +1,22 @@ -import { JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { FeathersAuthorizationService } from '@modules/authorization'; import { CreateNewsParams, NewsListResponse, NewsResponse, UpdateNewsParams } from '@modules/news/controller/dto'; import { ServerTestModule } from '@modules/server/server.module'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { News } from '@shared/domain/entity'; +import { News, User } from '@shared/domain/entity'; import { EntityId, NewsTargetModel } from '@shared/domain/types'; import { API_VALIDATION_ERROR_TYPE } from '@src/core/error/server-error-types'; -import { Request } from 'express'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import moment from 'moment'; -import request from 'supertest'; describe('News Controller (API)', () => { let app: INestApplication; let em: EntityManager; - const user = { - userId: '0000d224816abba584714c9c', - roles: [], - schoolId: '5f2987e020834114b8efd6f8', - accountId: '0000d225816abba584714c9d', - }; + let newsApiClient: TestApiClient; + let teamsApiClient: TestApiClient; + const courseTargetId = new ObjectId().toHexString(); const unpublishedCourseTargetId = new ObjectId().toHexString(); const teamTargetId = new ObjectId().toHexString(); @@ -40,14 +36,6 @@ describe('News Controller (API)', () => { const module: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = user; - return true; - }, - }) .overrideProvider(FeathersAuthorizationService) .useValue({ checkEntityPermissions() {}, @@ -63,6 +51,9 @@ describe('News Controller (API)', () => { app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); + + newsApiClient = new TestApiClient(app, '/news'); + teamsApiClient = new TestApiClient(app, '/team'); }); beforeEach(async () => { @@ -73,159 +64,363 @@ describe('News Controller (API)', () => { await app.close(); }); - const newTestNews = (targetModel: NewsTargetModel, targetId: EntityId, unpublished = false): News => { + const newTestNews = (targetModel: NewsTargetModel, targetId: EntityId, user: User, unpublished = false): News => { const displayAt = unpublished ? moment().add(1, 'days').toDate() : moment().subtract(1, 'days').toDate(); const news = News.createInstance(targetModel, { - school: user.schoolId, + school: user.school, title: 'test course news', content: 'content', target: targetId, - displayAt, - creator: user.userId, + creator: user.id, }); + return news; }; - const createTestNews = async (targetModel: NewsTargetModel, targetId: EntityId, unpublished = false) => { - const news = newTestNews(targetModel, targetId, unpublished); + const createTestNews = async (targetModel: NewsTargetModel, targetId: EntityId, user: User, unpublished = false) => { + const news = newTestNews(targetModel, targetId, user, unpublished); await em.persistAndFlush(news); return news; }; + describe('GET /news', () => { - it('should get empty response if there is no news', async () => { - const response = await request(app.getHttpServer()).get(`/news`).expect(200); - const { data, total } = response.body as NewsListResponse; - expect(total).toBe(0); - expect(data).toHaveLength(0); - }); + describe('when user is authenticated', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); - it('should get for /news without parameters', async () => { - const news = await createTestNews(NewsTargetModel.Course, courseTargetId); - const expected = { - data: [news], - total: 1, - }; - const response = await request(app.getHttpServer()).get(`/news`).expect(200); - const { data, total } = response.body as NewsListResponse; - expect(total).toBe(expected.total); - expect(data.length).toBe(expected.data.length); - expect(data[0].id).toBe(expected.data[0]._id.toString()); - }); + await em.persistAndFlush([studentAccount, studentUser]); - it('should get for /news with unpublished params only unpublished news', async () => { - const unpublishedNews = await createTestNews(NewsTargetModel.Course, unpublishedCourseTargetId, true); - const expected = { - data: [unpublishedNews], - total: 1, + const loggedInClient = await newsApiClient.login(studentAccount); + + return { loggedInClient, studentUser }; }; - const response = await request(app.getHttpServer()).get(`/news?unpublished=true`).expect(200); - const { data, total } = response.body as NewsListResponse; - expect(total).toBe(expected.total); - expect(data.length).toBe(expected.data.length); - expect(data[0].id).toBe(expected.data[0]._id.toString()); + it('should get empty response if there is no news', async () => { + const { loggedInClient } = await setup(); + + const response = await loggedInClient.get(); + expect(response.status).toBe(200); + const { data, total } = response.body as NewsListResponse; + expect(total).toBe(0); + expect(data).toHaveLength(0); + }); + + it('should get for /news without parameters', async () => { + const { loggedInClient, studentUser } = await setup(); + const news = await createTestNews(NewsTargetModel.Course, courseTargetId, studentUser); + const expected = { + data: [news], + total: 1, + }; + const response = await loggedInClient.get().expect(200); + const { data, total } = response.body as NewsListResponse; + expect(total).toBe(expected.total); + expect(data.length).toBe(expected.data.length); + expect(data[0].id).toBe(expected.data[0]._id.toString()); + }); + + it('should get for /news with unpublished params only unpublished news', async () => { + const { loggedInClient, studentUser } = await setup(); + const unpublishedNews = await createTestNews( + NewsTargetModel.Course, + unpublishedCourseTargetId, + studentUser, + true + ); + const expected = { + data: [unpublishedNews], + total: 1, + }; + const response = await loggedInClient.get(`?unpublished=true`).expect(200); + const { data, total } = response.body as NewsListResponse; + + expect(total).toBe(expected.total); + expect(data.length).toBe(expected.data.length); + expect(data[0].id).toBe(expected.data[0]._id.toString()); + }); + }); + + describe('when user is not authenticated', () => { + it('should return 401 status', async () => { + await newsApiClient.get().expect(401); + }); }); }); describe('GET /news/{id}', () => { - it('should get news by id', async () => { - const news = await createTestNews(NewsTargetModel.Course, courseTargetId); - const response = await request(app.getHttpServer()).get(`/news/${news._id.toHexString()}`).expect(200); - const body = response.body as NewsResponse; - expect(body.id).toBe(news._id.toString()); + describe('when user is authenticated', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + + const loggedInClient = await newsApiClient.login(studentAccount); + + return { loggedInClient, studentUser }; + }; + + it('should get news by id', async () => { + const { loggedInClient, studentUser } = await setup(); + const news = await createTestNews(NewsTargetModel.Course, courseTargetId, studentUser); + const response = await loggedInClient.get(`${news._id.toHexString()}`).expect(200); + const body = response.body as NewsResponse; + expect(body.id).toBe(news._id.toString()); + }); + + it('should throw not found if news was not found', async () => { + const { loggedInClient } = await setup(); + const randomId = new ObjectId().toHexString(); + await loggedInClient.get(`${randomId}`).expect(404); + }); }); - it('should throw not found if news was not found', async () => { - const randomId = new ObjectId().toHexString(); - await request(app.getHttpServer()).get(`/news/${randomId}`).expect(404); + describe('when user is not authenticated', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + + const news = await createTestNews(NewsTargetModel.Course, courseTargetId, studentUser); + + await em.persistAndFlush([studentAccount, studentUser]); + + return { news }; + }; + + it('should return 401 status', async () => { + const { news } = await setup(); + + await newsApiClient.get(`${news._id.toHexString()}`).expect(401); + }); }); }); describe('GET /team/{teamId}/news', () => { - it('should get team-news by id', async () => { - const news = await createTestNews(NewsTargetModel.Team, teamTargetId); - const response = await request(app.getHttpServer()).get(`/team/${teamTargetId}/news`).expect(200); - const body = response.body as NewsListResponse; - expect(body.data.map((newsResponse) => newsResponse.id)).toContain(news.id); + describe('when user is authenticated', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const news = await createTestNews(NewsTargetModel.Team, teamTargetId, studentUser); + + await em.persistAndFlush([studentAccount, studentUser]); + + const loggedInClient = await teamsApiClient.login(studentAccount); + + return { loggedInClient, news }; + }; + + it('should get team-news by id', async () => { + const { loggedInClient, news } = await setup(); + + const response = await loggedInClient.get(`${teamTargetId}/news`).expect(200); + + const body = response.body as NewsListResponse; + expect(body.data.map((newsResponse) => newsResponse.id)).toContain(news.id); + }); + + it('should not throw if a team was not found', async () => { + const { loggedInClient } = await setup(); + + const randomId = new ObjectId().toHexString(); + await loggedInClient.get(`${randomId}/news`).expect(200).expect(emptyPaginationResponse); + }); }); - it('should not throw if a team was not found', async () => { - const randomId = new ObjectId().toHexString(); - await request(app.getHttpServer()).get(`/team/${randomId}/news`).expect(200).expect(emptyPaginationResponse); + describe('when user is not authenticated', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const news = await createTestNews(NewsTargetModel.Team, teamTargetId, studentUser); + + await em.persistAndFlush([studentAccount, studentUser]); + + return { news }; + }; + + it('should return 401 status', async () => { + await setup(); + + await teamsApiClient.get(`${teamTargetId}/news`).expect(401); + }); }); }); describe('POST /news/{id}', () => { - it('should create news by input params', async () => { - const courseId = new ObjectId().toString(); - - const params: CreateNewsParams = { - title: 'test course news', - content: 'content', - targetModel: NewsTargetModel.Course, - targetId: courseId, - displayAt: new Date(), + describe('when user is authenticated', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + + const loggedInClient = await newsApiClient.login(studentAccount); + + return { loggedInClient, studentUser }; }; - const response = await request(app.getHttpServer()).post(`/news`).send(params).expect(201); - const body = response.body as NewsResponse; - expect(body.id).toBeDefined(); - expect(body.title).toBe(params.title); - expect(body.targetId).toBe(params.targetId); - expect(body.displayAt).toBe(params.displayAt?.toISOString()); + it('should create news by input params', async () => { + const { loggedInClient } = await setup(); + const courseId = new ObjectId().toString(); + + const params: CreateNewsParams = { + title: 'test course news', + content: 'content', + targetModel: NewsTargetModel.Course, + targetId: courseId, + displayAt: new Date(), + }; + + const response = await loggedInClient.post().send(params).expect(201); + const body = response.body as NewsResponse; + expect(body.id).toBeDefined(); + expect(body.title).toBe(params.title); + expect(body.targetId).toBe(params.targetId); + expect(body.displayAt).toBe(params.displayAt?.toISOString()); + }); + + it('should throw ApiValidationError if input parameters dont match the required schema', async () => { + const { loggedInClient } = await setup(); + + const params = new CreateNewsParams(); + const res = await loggedInClient.post().send(params).expect(400); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + expect(res.body.type).toBe(API_VALIDATION_ERROR_TYPE.type); + }); }); - it('should throw ApiValidationError if input parameters dont match the required schema', async () => { - const params = new CreateNewsParams(); - const res = await request(app.getHttpServer()).post(`/news`).send(params).expect(400); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - expect(res.body.type).toBe(API_VALIDATION_ERROR_TYPE.type); + + describe('when user is not authenticated', () => { + const setup = () => { + const courseId = new ObjectId().toString(); + + const params: CreateNewsParams = { + title: 'test course news', + content: 'content', + targetModel: NewsTargetModel.Course, + targetId: courseId, + displayAt: new Date(), + }; + + return { params }; + }; + + it('should return 401 status', async () => { + const { params } = setup(); + + await newsApiClient.post().send(params).expect(401); + }); }); }); describe('PATCH /news/{id}', () => { - it('should update news by update params', async () => { - const news = await createTestNews(NewsTargetModel.Course, courseTargetId); - - const params = { - title: 'updated test news', - content: 'new content', - displayAt: new Date(), - } as UpdateNewsParams; - - const response = await request(app.getHttpServer()) - .patch(`/news/${news._id.toHexString()}`) - .send(params) - .expect(200); - const body = response.body as NewsResponse; - expect(body.id).toBe(news._id.toHexString()); - expect(body.title).toBe(params.title); - expect(body.content).toBe(params.content); - expect(body.displayAt).toBe(params.displayAt.toISOString()); - }); + describe('when user is authenticated', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + + const loggedInClient = await newsApiClient.login(studentAccount); + + return { loggedInClient, studentUser }; + }; + + it('should update news by update params', async () => { + const { loggedInClient, studentUser } = await setup(); + const news = await createTestNews(NewsTargetModel.Course, courseTargetId, studentUser); + + const params = { + title: 'updated test news', + content: 'new content', + displayAt: new Date(), + } as UpdateNewsParams; + + const response = await loggedInClient.patch(`${news._id.toHexString()}`).send(params).expect(200); + const body = response.body as NewsResponse; + expect(body.id).toBe(news._id.toHexString()); + expect(body.title).toBe(params.title); + expect(body.content).toBe(params.content); + expect(body.displayAt).toBe(params.displayAt.toISOString()); + }); + + it('should do nothing if path an empty object for update', async () => { + const { loggedInClient, studentUser } = await setup(); - it('should do nothing if path an empty object for update', async () => { - const news = await createTestNews(NewsTargetModel.Course, courseTargetId); - const params = {} as UpdateNewsParams; - await request(app.getHttpServer()).patch(`/news/${news._id.toString()}`).send(params).expect(200); + const news = await createTestNews(NewsTargetModel.Course, courseTargetId, studentUser); + const params = {} as UpdateNewsParams; + await loggedInClient.patch(`${news._id.toString()}`).send(params).expect(200); + }); + + it('should throw an error if trying to update of object which doesnt exists', async () => { + const { loggedInClient } = await setup(); + + const randomId = new ObjectId().toHexString(); + const params = {} as UpdateNewsParams; + await loggedInClient.patch(`${randomId}`).send(params).expect(404); + }); }); - it('should throw an error if trying to update of object which doesnt exists', async () => { - const randomId = new ObjectId().toHexString(); - const params = {} as UpdateNewsParams; - await request(app.getHttpServer()).patch(`/news/${randomId}`).send(params).expect(404); + describe('when user is not authenticated', () => { + const setup = async () => { + const { studentUser } = UserAndAccountTestFactory.buildStudent(); + const news = await createTestNews(NewsTargetModel.Course, courseTargetId, studentUser); + + const params = { + title: 'updated test news', + content: 'new content', + displayAt: new Date(), + } as UpdateNewsParams; + + return { params, news }; + }; + + it('should return 401 status', async () => { + const { params, news } = await setup(); + + await newsApiClient.patch(`${news._id.toHexString()}`).send(params).expect(401); + }); }); }); + describe('DELETE /news/{id}', () => { - it('should delete news', async () => { - const news = await createTestNews(NewsTargetModel.Course, courseTargetId); - const newsId = news._id.toHexString(); - await request(app.getHttpServer()).delete(`/news/${newsId}`).expect(200).expect(newsId); + describe('when user is authenticated', () => { + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + + const loggedInClient = await newsApiClient.login(studentAccount); + + return { loggedInClient, studentUser }; + }; + + it('should delete news', async () => { + const { loggedInClient, studentUser } = await setup(); + const news = await createTestNews(NewsTargetModel.Course, courseTargetId, studentUser); + const newsId = news._id.toHexString(); + + await loggedInClient.delete(`${newsId}`).expect(200).expect(newsId); + }); + + it('should throw not found error, if news doesnt exists', async () => { + const { loggedInClient } = await setup(); + + const randomId = new ObjectId().toHexString(); + await loggedInClient.delete(`${randomId}`).expect(404); + }); }); - it('should throw not found error, if news doesnt exists', async () => { - const randomId = new ObjectId().toHexString(); - await request(app.getHttpServer()).delete(`/news/${randomId}`).expect(404); + describe('when user is not authenticated', () => { + const setup = async () => { + const { studentUser } = UserAndAccountTestFactory.buildStudent(); + + await em.persistAndFlush([studentUser]); + + const news = await createTestNews(NewsTargetModel.Course, courseTargetId, studentUser); + const newsId = news._id.toHexString(); + + return { newsId }; + }; + + it('should return 401 status', async () => { + const { newsId } = await setup(); + + await newsApiClient.delete(`${newsId}`).expect(401); + }); }); }); }); diff --git a/apps/server/src/modules/news/mapper/news.mapper.spec.ts b/apps/server/src/modules/news/mapper/news.mapper.spec.ts index de81fae7dcd..7d342210942 100644 --- a/apps/server/src/modules/news/mapper/news.mapper.spec.ts +++ b/apps/server/src/modules/news/mapper/news.mapper.spec.ts @@ -10,7 +10,10 @@ import { User, } from '@shared/domain/entity'; import { CreateNews, INewsScope, IUpdateNews, NewsTarget, NewsTargetModel } from '@shared/domain/types'; -import { courseFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CreateNewsParams, FilterNewsParams, diff --git a/apps/server/src/modules/news/service/news.service.spec.ts b/apps/server/src/modules/news/service/news.service.spec.ts index faf21342b19..bef979335a7 100644 --- a/apps/server/src/modules/news/service/news.service.spec.ts +++ b/apps/server/src/modules/news/service/news.service.spec.ts @@ -12,8 +12,10 @@ import { deletionRequestFactory } from '@modules/deletion/domain/testing'; import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; import { NewsRepo } from '@shared/repo'; -import { setupEntities, teamNewsFactory, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { teamNewsFactory } from '@testing/factory/news.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { NewsService } from './news.service'; describe(NewsService.name, () => { diff --git a/apps/server/src/modules/oauth-provider/api/oauth-provider.client-crud.uc.spec.ts b/apps/server/src/modules/oauth-provider/api/oauth-provider.client-crud.uc.spec.ts index b18f69ad9a8..d42e368df43 100644 --- a/apps/server/src/modules/oauth-provider/api/oauth-provider.client-crud.uc.spec.ts +++ b/apps/server/src/modules/oauth-provider/api/oauth-provider.client-crud.uc.spec.ts @@ -3,7 +3,8 @@ import { AuthorizationService } from '@modules/authorization'; import { UnauthorizedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ProviderOauthClient } from '../domain'; import { OauthProviderService } from '../domain/service/oauth-provider.service'; import { providerOauthClientFactory } from '../testing'; diff --git a/apps/server/src/modules/oauth-provider/api/oauth-provider.login-flow.uc.spec.ts b/apps/server/src/modules/oauth-provider/api/oauth-provider.login-flow.uc.spec.ts index 7f091e69c98..15e314e37a2 100644 --- a/apps/server/src/modules/oauth-provider/api/oauth-provider.login-flow.uc.spec.ts +++ b/apps/server/src/modules/oauth-provider/api/oauth-provider.login-flow.uc.spec.ts @@ -8,7 +8,10 @@ import { InternalServerErrorException, UnprocessableEntityException } from '@nes import { Test, TestingModule } from '@nestjs/testing'; import { LtiToolDO, Pseudonym, UserDO } from '@shared/domain/domainobject'; import { Permission } from '@shared/domain/interface'; -import { ltiToolDOFactory, pseudonymFactory, setupEntities, userDoFactory, userFactory } from '@shared/testing'; +import { ltiToolDOFactory, pseudonymFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ProviderLoginResponse, ProviderRedirectResponse } from '../domain'; import { OauthProviderLoginFlowService } from '../domain/service/oauth-provider.login-flow.service'; import { OauthProviderService } from '../domain/service/oauth-provider.service'; diff --git a/apps/server/src/modules/oauth-provider/api/test/oauth-provider.controller.api.spec.ts b/apps/server/src/modules/oauth-provider/api/test/oauth-provider.controller.api.spec.ts index 911864a7622..c5bd663896b 100644 --- a/apps/server/src/modules/oauth-provider/api/test/oauth-provider.controller.api.spec.ts +++ b/apps/server/src/modules/oauth-provider/api/test/oauth-provider.controller.api.spec.ts @@ -4,15 +4,13 @@ import { ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { - cleanupCollections, - externalToolPseudonymEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; -import { ltiToolFactory } from '@shared/testing/factory/ltitool.factory'; -import { pseudonymEntityFactory } from '@shared/testing/factory/pseudonym.factory'; import { externalToolEntityFactory } from '@src/modules/tool/external-tool/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { externalToolPseudonymEntityFactory } from '@testing/factory/external-tool-pseudonym.factory'; +import { ltiToolFactory } from '@testing/factory/ltitool.factory'; +import { pseudonymEntityFactory } from '@testing/factory/pseudonym.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { diff --git a/apps/server/src/modules/oauth-provider/domain/error/hydra-oauth-failed-loggable-exception.spec.ts b/apps/server/src/modules/oauth-provider/domain/error/hydra-oauth-failed-loggable-exception.spec.ts index 987cf7f0016..91a77aa84b2 100644 --- a/apps/server/src/modules/oauth-provider/domain/error/hydra-oauth-failed-loggable-exception.spec.ts +++ b/apps/server/src/modules/oauth-provider/domain/error/hydra-oauth-failed-loggable-exception.spec.ts @@ -1,4 +1,4 @@ -import { axiosErrorFactory } from '@shared/testing/factory'; +import { axiosErrorFactory } from '@testing/factory/axios-error.factory'; import { AxiosError } from 'axios'; import { HydraOauthFailedLoggableException } from './hydra-oauth-failed-loggable-exception'; diff --git a/apps/server/src/modules/oauth-provider/domain/service/hydra.adapter.spec.ts b/apps/server/src/modules/oauth-provider/domain/service/hydra.adapter.spec.ts index c126c2e379a..e52616aa3c9 100644 --- a/apps/server/src/modules/oauth-provider/domain/service/hydra.adapter.spec.ts +++ b/apps/server/src/modules/oauth-provider/domain/service/hydra.adapter.spec.ts @@ -1,7 +1,8 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { HttpService } from '@nestjs/axios'; import { Test, TestingModule } from '@nestjs/testing'; -import { axiosErrorFactory, axiosResponseFactory } from '@shared/testing'; +import { axiosErrorFactory } from '@testing/factory/axios-error.factory'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { AxiosRequestConfig } from 'axios'; import { of, throwError } from 'rxjs'; import { OauthProviderFeatures } from '../../oauth-provider-config'; diff --git a/apps/server/src/modules/oauth-provider/domain/service/id-token.service.spec.ts b/apps/server/src/modules/oauth-provider/domain/service/id-token.service.spec.ts index 93fa63b0f38..f90d3833567 100644 --- a/apps/server/src/modules/oauth-provider/domain/service/id-token.service.spec.ts +++ b/apps/server/src/modules/oauth-provider/domain/service/id-token.service.spec.ts @@ -7,8 +7,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Pseudonym, UserDO } from '@shared/domain/domainobject'; import { TeamEntity } from '@shared/domain/entity'; import { TeamsRepo } from '@shared/repo'; -import { pseudonymFactory, setupEntities, userDoFactory } from '@shared/testing'; -import { teamFactory } from '@shared/testing/factory/team.factory'; +import { pseudonymFactory } from '@testing/factory/domainobject'; +import { teamFactory } from '@testing/factory/team.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { IdTokenCreationLoggableException } from '../error'; import { IdToken, OauthScope } from '../interface'; import { IdTokenService } from './id-token.service'; diff --git a/apps/server/src/modules/oauth-provider/domain/service/oauth-provider.login-flow.service.spec.ts b/apps/server/src/modules/oauth-provider/domain/service/oauth-provider.login-flow.service.spec.ts index fb308ebe962..eac5eb766d7 100644 --- a/apps/server/src/modules/oauth-provider/domain/service/oauth-provider.login-flow.service.spec.ts +++ b/apps/server/src/modules/oauth-provider/domain/service/oauth-provider.login-flow.service.spec.ts @@ -8,7 +8,8 @@ import { NotFoundException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { LtiToolDO } from '@shared/domain/domainobject'; -import { ltiToolDOFactory, setupEntities } from '@shared/testing'; +import { ltiToolDOFactory } from '@testing/factory/domainobject'; +import { setupEntities } from '@testing/setup-entities'; import { OauthProviderLoginFlowService } from './oauth-provider.login-flow.service'; describe(OauthProviderLoginFlowService.name, () => { diff --git a/apps/server/src/modules/oauth/controller/oauth-sso.controller.spec.ts b/apps/server/src/modules/oauth/controller/oauth-sso.controller.spec.ts index 33750bbef6d..0f8c80db5c9 100644 --- a/apps/server/src/modules/oauth/controller/oauth-sso.controller.spec.ts +++ b/apps/server/src/modules/oauth/controller/oauth-sso.controller.spec.ts @@ -3,8 +3,8 @@ import { Configuration } from '@hpi-schul-cloud/commons'; import { HydraOauthUc } from '@modules/oauth/uc/hydra-oauth.uc'; import { UnauthorizedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { currentUserFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; import { Request } from 'express'; import { StatelessAuthorizationParams } from './dto/stateless-authorization.params'; import { OauthSSOController } from './oauth-sso.controller'; diff --git a/apps/server/src/modules/oauth/domain/do/oauth-session-token.factory.spec.ts b/apps/server/src/modules/oauth/domain/do/oauth-session-token.factory.spec.ts index 6e899d6fea3..e5bc663db49 100644 --- a/apps/server/src/modules/oauth/domain/do/oauth-session-token.factory.spec.ts +++ b/apps/server/src/modules/oauth/domain/do/oauth-session-token.factory.spec.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { JwtTestFactory } from '@shared/testing'; +import { JwtTestFactory } from '@testing/factory/jwt.test.factory'; import { TokenInvalidLoggableException } from '../../loggable'; import { OauthSessionToken } from './oauth-session-token'; import { OauthSessionTokenFactory } from './oauth-session-token.factory'; diff --git a/apps/server/src/modules/oauth/loggable/token-request-loggable-exception.spec.ts b/apps/server/src/modules/oauth/loggable/token-request-loggable-exception.spec.ts index c63db6d9124..8c9adf9f229 100644 --- a/apps/server/src/modules/oauth/loggable/token-request-loggable-exception.spec.ts +++ b/apps/server/src/modules/oauth/loggable/token-request-loggable-exception.spec.ts @@ -1,4 +1,4 @@ -import { axiosErrorFactory } from '@shared/testing/factory'; +import { axiosErrorFactory } from '@testing/factory/axios-error.factory'; import { AxiosError } from 'axios'; import { TokenRequestLoggableException } from './token-request-loggable-exception'; diff --git a/apps/server/src/modules/oauth/repo/mikro-orm/oauth-session-token.repo.spec.ts b/apps/server/src/modules/oauth/repo/mikro-orm/oauth-session-token.repo.spec.ts index 0e290e193d5..b59119331be 100644 --- a/apps/server/src/modules/oauth/repo/mikro-orm/oauth-session-token.repo.spec.ts +++ b/apps/server/src/modules/oauth/repo/mikro-orm/oauth-session-token.repo.spec.ts @@ -1,7 +1,8 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, userFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { userFactory } from '@testing/factory/user.factory'; import { OauthSessionTokenEntity } from '../../entity'; import { oauthSessionTokenEntityFactory, oauthSessionTokenFactory } from '../../testing'; import { OAUTH_SESSION_TOKEN_REPO } from '../oauth-session-token.repo.interface'; diff --git a/apps/server/src/modules/oauth/service/hydra.service.spec.ts b/apps/server/src/modules/oauth/service/hydra.service.spec.ts index 60a66e706b2..6522d04b2d5 100644 --- a/apps/server/src/modules/oauth/service/hydra.service.spec.ts +++ b/apps/server/src/modules/oauth/service/hydra.service.spec.ts @@ -12,8 +12,8 @@ import { Test, TestingModule } from '@nestjs/testing'; import { LtiToolDO } from '@shared/domain/domainobject/ltitool.do'; import { LtiPrivacyPermission, LtiRoleType } from '@shared/domain/entity'; import { LtiToolRepo } from '@shared/repo'; -import { axiosResponseFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { AxiosResponse } from 'axios'; import { of } from 'rxjs'; import { StatelessAuthorizationParams } from '../controller/dto/stateless-authorization.params'; diff --git a/apps/server/src/modules/oauth/service/oauth-adapter.service.spec.ts b/apps/server/src/modules/oauth/service/oauth-adapter.service.spec.ts index 63319b859d4..cdfb191e88f 100644 --- a/apps/server/src/modules/oauth/service/oauth-adapter.service.spec.ts +++ b/apps/server/src/modules/oauth/service/oauth-adapter.service.spec.ts @@ -1,8 +1,8 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { HttpService } from '@nestjs/axios'; import { Test, TestingModule } from '@nestjs/testing'; -import { axiosResponseFactory } from '@shared/testing'; -import { axiosErrorFactory } from '@shared/testing/factory'; +import { axiosErrorFactory } from '@testing/factory/axios-error.factory'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { AxiosError } from 'axios'; import { of, throwError } from 'rxjs'; import { OAuthTokenDto } from '../interface'; diff --git a/apps/server/src/modules/oauth/service/oauth.service.spec.ts b/apps/server/src/modules/oauth/service/oauth.service.spec.ts index 308a96a0951..6f416f13b1d 100644 --- a/apps/server/src/modules/oauth/service/oauth.service.spec.ts +++ b/apps/server/src/modules/oauth/service/oauth.service.spec.ts @@ -13,10 +13,12 @@ import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, UserDO } from '@shared/domain/domainobject'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; import { SchoolFeature } from '@shared/domain/types'; -import { legacySchoolDoFactory, setupEntities, userDoFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; import { OauthDataDto } from '@src/modules/provisioning/dto'; import { System } from '@src/modules/system'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import jwt, { JwtPayload } from 'jsonwebtoken'; import { externalUserDtoFactory } from '../../provisioning/testing'; import { OAuthTokenDto } from '../interface'; diff --git a/apps/server/src/modules/oauth/testing/oauth-session-token-entity.factory.ts b/apps/server/src/modules/oauth/testing/oauth-session-token-entity.factory.ts index 816d96888a6..591674d4bc5 100644 --- a/apps/server/src/modules/oauth/testing/oauth-session-token-entity.factory.ts +++ b/apps/server/src/modules/oauth/testing/oauth-session-token-entity.factory.ts @@ -1,4 +1,7 @@ -import { BaseFactory, JwtTestFactory, systemEntityFactory, userFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; +import { JwtTestFactory } from '@testing/factory/jwt.test.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userFactory } from '@testing/factory/user.factory'; import { OauthSessionTokenEntity, OauthSessionTokenEntityProps } from '../entity'; export const oauthSessionTokenEntityFactory = BaseFactory.define( diff --git a/apps/server/src/modules/oauth/testing/oauth-session-token.factory.ts b/apps/server/src/modules/oauth/testing/oauth-session-token.factory.ts index 15bbe0304cc..860e287d94f 100644 --- a/apps/server/src/modules/oauth/testing/oauth-session-token.factory.ts +++ b/apps/server/src/modules/oauth/testing/oauth-session-token.factory.ts @@ -1,5 +1,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { DomainObjectFactory, JwtTestFactory } from '@shared/testing'; +import { DomainObjectFactory } from '@testing/factory/domainobject'; +import { JwtTestFactory } from '@testing/factory/jwt.test.factory'; import { OauthSessionToken, OauthSessionTokenProps } from '../domain'; export const oauthSessionTokenFactory = DomainObjectFactory.define( diff --git a/apps/server/src/modules/oauth/uc/hydra-oauth.uc.spec.ts b/apps/server/src/modules/oauth/uc/hydra-oauth.uc.spec.ts index 269c69753e9..56c92539a5b 100644 --- a/apps/server/src/modules/oauth/uc/hydra-oauth.uc.spec.ts +++ b/apps/server/src/modules/oauth/uc/hydra-oauth.uc.spec.ts @@ -6,8 +6,8 @@ import { OauthConfigEntity } from '@modules/system/entity'; import { HttpModule } from '@nestjs/axios'; import { InternalServerErrorException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { axiosResponseFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { AxiosResponse } from 'axios'; import { HydraOauthUc } from '.'; import { AuthorizationParams } from '../controller/dto'; diff --git a/apps/server/src/modules/provisioning/dto/external-user.dto.ts b/apps/server/src/modules/provisioning/dto/external-user.dto.ts index 013e8e370fa..4024be2d58e 100644 --- a/apps/server/src/modules/provisioning/dto/external-user.dto.ts +++ b/apps/server/src/modules/provisioning/dto/external-user.dto.ts @@ -5,6 +5,8 @@ export class ExternalUserDto { public firstName?: string; + public preferredName?: string; + public lastName?: string; public email?: string; @@ -16,6 +18,7 @@ export class ExternalUserDto { constructor(props: ExternalUserDto) { this.externalId = props.externalId; this.firstName = props.firstName; + this.preferredName = props.preferredName; this.lastName = props.lastName; this.email = props.email; this.roles = props.roles; diff --git a/apps/server/src/modules/provisioning/loggable/school-for-group-not-found.loggable.spec.ts b/apps/server/src/modules/provisioning/loggable/school-for-group-not-found.loggable.spec.ts index 888a6a58514..d888b56f11e 100644 --- a/apps/server/src/modules/provisioning/loggable/school-for-group-not-found.loggable.spec.ts +++ b/apps/server/src/modules/provisioning/loggable/school-for-group-not-found.loggable.spec.ts @@ -1,6 +1,6 @@ -import { externalSchoolDtoFactory } from '@shared/testing'; -import { externalGroupDtoFactory } from '@shared/testing/factory/external-group-dto.factory'; +import { externalSchoolDtoFactory } from '@testing/factory/external-school-dto.factory'; import { ExternalGroupDto, ExternalSchoolDto } from '../dto'; +import { externalGroupDtoFactory } from '../testing'; import { SchoolForGroupNotFoundLoggable } from './school-for-group-not-found.loggable'; describe('SchoolForGroupNotFoundLoggable', () => { diff --git a/apps/server/src/modules/provisioning/service/tsp-provisioning.service.spec.ts b/apps/server/src/modules/provisioning/service/tsp-provisioning.service.spec.ts index b42ff993b92..667edd5d6b0 100644 --- a/apps/server/src/modules/provisioning/service/tsp-provisioning.service.spec.ts +++ b/apps/server/src/modules/provisioning/service/tsp-provisioning.service.spec.ts @@ -4,7 +4,6 @@ import { Test, TestingModule } from '@nestjs/testing'; import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { RoleName } from '@shared/domain/interface'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { roleDtoFactory, roleFactory, userDoFactory } from '@shared/testing'; import { AccountService } from '@src/modules/account'; import { ClassService } from '@src/modules/class'; import { classFactory } from '@src/modules/class/domain/testing'; @@ -12,6 +11,9 @@ import { RoleService } from '@src/modules/role'; import { SchoolService } from '@src/modules/school'; import { schoolFactory } from '@src/modules/school/testing'; import { UserService } from '@src/modules/user'; +import { roleDtoFactory } from '@testing/factory/role-dto.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { ExternalClassDto, ExternalSchoolDto, ExternalUserDto, OauthDataDto, ProvisioningSystemDto } from '../dto'; import { BadDataLoggableException } from '../loggable'; import { TspProvisioningService } from './tsp-provisioning.service'; diff --git a/apps/server/src/modules/provisioning/strategy/iserv/iserv.strategy.spec.ts b/apps/server/src/modules/provisioning/strategy/iserv/iserv.strategy.spec.ts index 181a5b6971f..bd53104c9fe 100644 --- a/apps/server/src/modules/provisioning/strategy/iserv/iserv.strategy.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/iserv/iserv.strategy.spec.ts @@ -6,11 +6,12 @@ import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, UserDO } from '@shared/domain/domainobject'; import { RoleName } from '@shared/domain/interface'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { legacySchoolDoFactory, userDoFactory } from '@shared/testing'; import { IdTokenExtractionFailureLoggableException, IdTokenUserNotFoundLoggableException, } from '@src/modules/oauth/loggable'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import jwt from 'jsonwebtoken'; import { RoleDto } from '../../../role/service/dto/role.dto'; import { diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex-response-mapper.spec.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex-response-mapper.spec.ts index 1d413fd4aad..7af9e42aecd 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex-response-mapper.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex-response-mapper.spec.ts @@ -101,6 +101,7 @@ describe(SchulconnexResponseMapper.name, () => { expect(result).toEqual({ externalId: externalUserId, firstName: 'Hans', + preferredName: 'Hansi', lastName: 'Peter', email: 'hans.peter@muster-schule.de', roles: [RoleName.ADMINISTRATOR], diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex-response-mapper.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex-response-mapper.ts index 07ce885a1b9..196814b6850 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex-response-mapper.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex-response-mapper.ts @@ -89,6 +89,7 @@ export class SchulconnexResponseMapper { const mapped = new ExternalUserDto({ firstName: source.person.name.vorname, + preferredName: source.person.name.rufname, lastName: source.person.name.familienname, roles: role ? [role] : [], externalId: source.pid, diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex.strategy.spec.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex.strategy.spec.ts index f86346d37eb..f3a3d68664e 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex.strategy.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/schulconnex.strategy.spec.ts @@ -7,14 +7,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, UserDO } from '@shared/domain/domainobject'; import { RoleName } from '@shared/domain/interface'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { - externalGroupDtoFactory, - externalSchoolDtoFactory, - groupFactory, - legacySchoolDoFactory, - userDoFactory, -} from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { groupFactory, legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { externalSchoolDtoFactory } from '@testing/factory/external-school-dto.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { ExternalGroupDto, ExternalSchoolDto, @@ -24,7 +20,7 @@ import { ProvisioningSystemDto, } from '../../dto'; import { ProvisioningConfig } from '../../provisioning.config'; -import { externalUserDtoFactory } from '../../testing'; +import { externalGroupDtoFactory, externalUserDtoFactory } from '../../testing'; import { SchulconnexProvisioningStrategy } from './schulconnex.strategy'; import { SchulconnexCourseSyncService, diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-course-sync.service.spec.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-course-sync.service.spec.ts index 9ef64798b77..2aa418e97a5 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-course-sync.service.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-course-sync.service.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Group } from '@modules/group'; import { CourseSyncService } from '@modules/learnroom'; import { Test, TestingModule } from '@nestjs/testing'; -import { groupFactory } from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; import { SchulconnexCourseSyncService } from './schulconnex-course-sync.service'; describe(SchulconnexCourseSyncService.name, () => { diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-group-provisioning.service.spec.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-group-provisioning.service.spec.ts index f5d48e48d4f..43be0c95343 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-group-provisioning.service.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-group-provisioning.service.spec.ts @@ -3,12 +3,12 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { Group, GroupService, GroupTypes } from '@modules/group'; import { CourseDoService } from '@modules/learnroom'; import { Course } from '@modules/learnroom/domain'; -import { courseFactory } from '@modules/learnroom/testing'; import { LegacySchoolService, SchoolSystemOptionsService, SchulConneXProvisioningOptions, } from '@modules/legacy-school'; +import { externalGroupDtoFactory } from '@modules/provisioning/testing'; import { RoleDto, RoleService } from '@modules/role'; import { UserService } from '@modules/user'; import { Test, TestingModule } from '@nestjs/testing'; @@ -16,16 +16,13 @@ import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { ExternalSource, LegacySchoolDo, Page, RoleReference, UserDO } from '@shared/domain/domainobject'; import { RoleName } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; -import { - externalGroupDtoFactory, - externalSchoolDtoFactory, - groupFactory, - legacySchoolDoFactory, - roleDtoFactory, - roleFactory, - userDoFactory, -} from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { courseFactory } from '@src/modules/learnroom/testing'; +import { groupFactory, legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { externalSchoolDtoFactory } from '@testing/factory/external-school-dto.factory'; +import { roleDtoFactory } from '@testing/factory/role-dto.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { ExternalGroupDto, ExternalSchoolDto } from '../../../dto'; import { SchoolForGroupNotFoundLoggable, UserForGroupNotFoundLoggable } from '../../../loggable'; import { SchulconnexGroupProvisioningService } from './schulconnex-group-provisioning.service'; diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-license-provisioning.service.spec.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-license-provisioning.service.spec.ts index 045eff2b97e..c2d34c0dfd1 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-license-provisioning.service.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-license-provisioning.service.spec.ts @@ -1,15 +1,16 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; +import { MediaSource, MediaSourceService } from '@modules/media-source'; +import { mediaSourceFactory } from '@modules/media-source/testing'; import { MediaUserLicense, mediaUserLicenseFactory, MediaUserLicenseService, UserLicenseType, } from '@modules/user-license'; -import { MediaSource, MediaSourceService } from '@modules/media-source'; -import { mediaSourceFactory } from '@modules/media-source/testing'; import { Test, TestingModule } from '@nestjs/testing'; import { User as UserEntity } from '@shared/domain/entity'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ExternalLicenseDto } from '../../../dto'; import { SchulconnexLicenseProvisioningService } from './schulconnex-license-provisioning.service'; diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-school-provisioning.service.spec.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-school-provisioning.service.spec.ts index ba5995ff324..07ee95472e2 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-school-provisioning.service.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-school-provisioning.service.spec.ts @@ -4,7 +4,9 @@ import { FederalStateService, LegacySchoolService, SchoolYearService } from '@mo import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo } from '@shared/domain/domainobject'; import { SchoolFeature } from '@shared/domain/types'; -import { federalStateFactory, legacySchoolDoFactory, schoolYearFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; import { ExternalSchoolDto } from '../../../dto'; import { SchoolNameRequiredLoggableException } from '../../../loggable'; import { SchulconnexSchoolProvisioningService } from './schulconnex-school-provisioning.service'; diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-tool-provisioning.service.spec.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-tool-provisioning.service.spec.ts index 9492425822a..0d592366702 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-tool-provisioning.service.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-tool-provisioning.service.spec.ts @@ -9,8 +9,8 @@ import { SchoolExternalTool } from '@modules/tool/school-external-tool/domain'; import { schoolExternalToolFactory } from '@modules/tool/school-external-tool/testing'; import { MediaUserLicense, mediaUserLicenseFactory, MediaUserLicenseService } from '@modules/user-license'; import { Test, TestingModule } from '@nestjs/testing'; -import { schoolSystemOptionsFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { schoolSystemOptionsFactory } from '@testing/factory/domainobject'; import { SchulconnexToolProvisioningService } from './schulconnex-tool-provisioning.service'; describe(SchulconnexToolProvisioningService.name, () => { diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-user-provisioning.service.spec.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-user-provisioning.service.spec.ts index 4915119a983..33f57a7a9b8 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-user-provisioning.service.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-user-provisioning.service.spec.ts @@ -7,8 +7,8 @@ import { UserService } from '@modules/user'; import { Test, TestingModule } from '@nestjs/testing'; import { UserDO } from '@shared/domain/domainobject'; import { RoleName } from '@shared/domain/interface'; -import { userDoFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import CryptoJS from 'crypto-js'; import { ExternalUserDto } from '../../../dto'; import { SchoolMissingLoggableException, UserRoleUnknownLoggableException } from '../../../loggable'; @@ -70,6 +70,7 @@ describe(SchulconnexUserProvisioningService.name, () => { const existingUser: UserDO = userDoFactory.withRoles([{ id: 'existingRoleId', name: RoleName.USER }]).buildWithId( { firstName: 'existingFirstName', + preferredName: 'existingPreferredName', lastName: 'existingLastName', email: 'existingEmail', schoolId: 'existingSchoolId', @@ -81,6 +82,7 @@ describe(SchulconnexUserProvisioningService.name, () => { const savedUser: UserDO = userDoFactory.withRoles([{ id: 'roleId', name: RoleName.USER }]).buildWithId( { firstName: 'firstName', + preferredName: 'preferredName', lastName: 'lastName', email: 'email', schoolId, @@ -92,6 +94,7 @@ describe(SchulconnexUserProvisioningService.name, () => { const externalUser: ExternalUserDto = externalUserDtoFactory.build({ externalId: 'externalUserId', firstName: 'firstName', + preferredName: 'preferredName', lastName: 'lastName', email: 'email', roles: [RoleName.USER], diff --git a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-user-provisioning.service.ts b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-user-provisioning.service.ts index 3558cdad4f9..27eed0e9c73 100644 --- a/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-user-provisioning.service.ts +++ b/apps/server/src/modules/provisioning/strategy/schulconnex/service/schulconnex-user-provisioning.service.ts @@ -7,8 +7,7 @@ import { RoleName } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; import CryptoJS from 'crypto-js'; import { ExternalUserDto } from '../../../dto'; -import { UserRoleUnknownLoggableException } from '../../../loggable'; -import { SchoolMissingLoggableException } from '../../../loggable/school-missing.loggable-exception'; +import { SchoolMissingLoggableException, UserRoleUnknownLoggableException } from '../../../loggable'; @Injectable() export class SchulconnexUserProvisioningService { @@ -78,6 +77,7 @@ export class SchulconnexUserProvisioningService { ): UserDO { const user: UserDO = foundUser; user.firstName = externalUser.firstName ?? foundUser.firstName; + user.preferredName = externalUser.preferredName ?? foundUser.preferredName; user.lastName = externalUser.lastName ?? foundUser.lastName; user.email = externalUser.email ?? foundUser.email; user.roles = roleRefs ?? foundUser.roles; @@ -91,6 +91,7 @@ export class SchulconnexUserProvisioningService { const user: UserDO = new UserDO({ externalId: externalUser.externalId, firstName: externalUser.firstName ?? '', + preferredName: externalUser.preferredName, lastName: externalUser.lastName ?? '', email: externalUser.email ?? '', roles: roleRefs ?? [], diff --git a/apps/server/src/modules/provisioning/strategy/tsp/tsp.strategy.spec.ts b/apps/server/src/modules/provisioning/strategy/tsp/tsp.strategy.spec.ts index 444261b6236..ecb5314412c 100644 --- a/apps/server/src/modules/provisioning/strategy/tsp/tsp.strategy.spec.ts +++ b/apps/server/src/modules/provisioning/strategy/tsp/tsp.strategy.spec.ts @@ -4,8 +4,8 @@ import { schoolFactory } from '@modules/school/testing'; import { Test, TestingModule } from '@nestjs/testing'; import { RoleName } from '@shared/domain/interface'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { userDoFactory } from '@shared/testing'; import { IdTokenExtractionFailureLoggableException } from '@src/modules/oauth/loggable'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import jwt from 'jsonwebtoken'; import { ExternalClassDto, diff --git a/apps/server/src/modules/pseudonym/controller/api-test/pseudonym.api.spec.ts b/apps/server/src/modules/pseudonym/controller/api-test/pseudonym.api.spec.ts index 84359d9e131..7a7bf2e9778 100644 --- a/apps/server/src/modules/pseudonym/controller/api-test/pseudonym.api.spec.ts +++ b/apps/server/src/modules/pseudonym/controller/api-test/pseudonym.api.spec.ts @@ -5,13 +5,11 @@ import { externalToolEntityFactory } from '@modules/tool/external-tool/testing'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; -import { - cleanupCollections, - externalToolPseudonymEntityFactory, - schoolEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { externalToolPseudonymEntityFactory } from '@testing/factory/external-tool-pseudonym.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { UUID } from 'bson'; import { Response } from 'supertest'; import { ExternalToolPseudonymEntity } from '../../entity'; diff --git a/apps/server/src/modules/pseudonym/entity/external-tool-pseudonym.entity.spec.ts b/apps/server/src/modules/pseudonym/entity/external-tool-pseudonym.entity.spec.ts index a7ab8f1bf81..192890d04a6 100644 --- a/apps/server/src/modules/pseudonym/entity/external-tool-pseudonym.entity.spec.ts +++ b/apps/server/src/modules/pseudonym/entity/external-tool-pseudonym.entity.spec.ts @@ -1,6 +1,6 @@ -import { setupEntities } from '@shared/testing'; -import { externalToolPseudonymEntityFactory } from '@shared/testing/factory/external-tool-pseudonym.factory'; import { ObjectId } from '@mikro-orm/mongodb'; +import { externalToolPseudonymEntityFactory } from '@testing/factory/external-tool-pseudonym.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ExternalToolPseudonymEntity } from './external-tool-pseudonym.entity'; describe('ExternalToolPseudonymEntity', () => { diff --git a/apps/server/src/modules/pseudonym/entity/pseudonym.entity.spec.ts b/apps/server/src/modules/pseudonym/entity/pseudonym.entity.spec.ts index b1fb14f26be..db15ef9b903 100644 --- a/apps/server/src/modules/pseudonym/entity/pseudonym.entity.spec.ts +++ b/apps/server/src/modules/pseudonym/entity/pseudonym.entity.spec.ts @@ -1,6 +1,6 @@ -import { setupEntities } from '@shared/testing'; -import { pseudonymEntityFactory } from '@shared/testing/factory/pseudonym.factory'; import { ObjectId } from '@mikro-orm/mongodb'; +import { pseudonymEntityFactory } from '@testing/factory/pseudonym.factory'; +import { setupEntities } from '@testing/setup-entities'; import { PseudonymEntity } from './pseudonym.entity'; describe('Pseudonym Entity', () => { diff --git a/apps/server/src/modules/pseudonym/repo/external-tool-pseudonym.repo.integration.spec.ts b/apps/server/src/modules/pseudonym/repo/external-tool-pseudonym.repo.integration.spec.ts index bfd074b2599..5c946bb0d49 100644 --- a/apps/server/src/modules/pseudonym/repo/external-tool-pseudonym.repo.integration.spec.ts +++ b/apps/server/src/modules/pseudonym/repo/external-tool-pseudonym.repo.integration.spec.ts @@ -5,9 +5,12 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { Page, Pseudonym } from '@shared/domain/domainobject'; -import { cleanupCollections, externalToolPseudonymEntityFactory, pseudonymFactory, userFactory } from '@shared/testing'; -import { pseudonymEntityFactory } from '@shared/testing/factory/pseudonym.factory'; import { LegacyLogger } from '@src/core/logger'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { pseudonymFactory } from '@testing/factory/domainobject'; +import { externalToolPseudonymEntityFactory } from '@testing/factory/external-tool-pseudonym.factory'; +import { pseudonymEntityFactory } from '@testing/factory/pseudonym.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { v4 as uuidv4 } from 'uuid'; import { PseudonymSearchQuery } from '../domain'; import { ExternalToolPseudonymEntity } from '../entity'; diff --git a/apps/server/src/modules/pseudonym/repo/pseudonyms.repo.spec.ts b/apps/server/src/modules/pseudonym/repo/pseudonyms.repo.spec.ts index 404ada59a66..c9725320bf6 100644 --- a/apps/server/src/modules/pseudonym/repo/pseudonyms.repo.spec.ts +++ b/apps/server/src/modules/pseudonym/repo/pseudonyms.repo.spec.ts @@ -4,9 +4,11 @@ import { NotFoundError } from '@mikro-orm/core'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { Pseudonym } from '@shared/domain/domainobject'; -import { cleanupCollections, pseudonymFactory, userFactory } from '@shared/testing'; -import { pseudonymEntityFactory } from '@shared/testing/factory/pseudonym.factory'; import { LegacyLogger } from '@src/core/logger'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { pseudonymFactory } from '@testing/factory/domainobject'; +import { pseudonymEntityFactory } from '@testing/factory/pseudonym.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { v4 as uuidv4 } from 'uuid'; import { PseudonymEntity } from '../entity'; import { PseudonymsRepo } from './pseudonyms.repo'; diff --git a/apps/server/src/modules/pseudonym/service/pseudonym.service.spec.ts b/apps/server/src/modules/pseudonym/service/pseudonym.service.spec.ts index 67eb05a2045..8a84811d2ed 100644 --- a/apps/server/src/modules/pseudonym/service/pseudonym.service.spec.ts +++ b/apps/server/src/modules/pseudonym/service/pseudonym.service.spec.ts @@ -16,9 +16,10 @@ import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; import { LtiToolDO, Page, Pseudonym, UserDO } from '@shared/domain/domainobject'; import { IFindOptions } from '@shared/domain/interface'; -import { setupEntities } from '@shared/testing'; -import { ltiToolDOFactory, pseudonymFactory, userDoFactory } from '@shared/testing/factory'; import { Logger } from '@src/core/logger'; +import { ltiToolDOFactory, pseudonymFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { PseudonymSearchQuery } from '../domain'; import { ExternalToolPseudonymRepo, PseudonymsRepo } from '../repo'; diff --git a/apps/server/src/modules/pseudonym/uc/pseudonym.uc.spec.ts b/apps/server/src/modules/pseudonym/uc/pseudonym.uc.spec.ts index 8c8b6683b56..89c1df7d249 100644 --- a/apps/server/src/modules/pseudonym/uc/pseudonym.uc.spec.ts +++ b/apps/server/src/modules/pseudonym/uc/pseudonym.uc.spec.ts @@ -5,13 +5,10 @@ import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, Pseudonym } from '@shared/domain/domainobject'; import { SchoolEntity, User } from '@shared/domain/entity'; -import { - legacySchoolDoFactory, - pseudonymFactory, - schoolEntityFactory, - setupEntities, - userFactory, -} from '@shared/testing'; +import { legacySchoolDoFactory, pseudonymFactory } from '@testing/factory/domainobject'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { PseudonymService } from '../service'; import { PseudonymUc } from './pseudonym.uc'; diff --git a/apps/server/src/modules/registration-pin/entity/registration-pin.entity.spec.ts b/apps/server/src/modules/registration-pin/entity/registration-pin.entity.spec.ts index c8570e8d1b2..3c1debcebff 100644 --- a/apps/server/src/modules/registration-pin/entity/registration-pin.entity.spec.ts +++ b/apps/server/src/modules/registration-pin/entity/registration-pin.entity.spec.ts @@ -1,5 +1,5 @@ -import { setupEntities } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { setupEntities } from '@testing/setup-entities'; import { RegistrationPinEntity } from '.'; describe(RegistrationPinEntity.name, () => { diff --git a/apps/server/src/modules/registration-pin/entity/testing/factory/registration-pin.entity.factory.ts b/apps/server/src/modules/registration-pin/entity/testing/factory/registration-pin.entity.factory.ts index 9a162147bed..5d58ef34e63 100644 --- a/apps/server/src/modules/registration-pin/entity/testing/factory/registration-pin.entity.factory.ts +++ b/apps/server/src/modules/registration-pin/entity/testing/factory/registration-pin.entity.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { RegistrationPinEntity, RegistrationPinEntityProps } from '../../registration-pin.entity'; export const registrationPinEntityFactory = BaseFactory.define( diff --git a/apps/server/src/modules/registration-pin/repo/registration-pin.repo.spec.ts b/apps/server/src/modules/registration-pin/repo/registration-pin.repo.spec.ts index a91a6801db3..ad29b0af526 100644 --- a/apps/server/src/modules/registration-pin/repo/registration-pin.repo.spec.ts +++ b/apps/server/src/modules/registration-pin/repo/registration-pin.repo.spec.ts @@ -1,7 +1,8 @@ +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { MongoMemoryDatabaseModule } from '@infra/database'; -import { cleanupCollections, userFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { userFactory } from '@testing/factory/user.factory'; import { RegistrationPinRepo } from '.'; import { registrationPinEntityFactory } from '../entity/testing'; diff --git a/apps/server/src/modules/registration-pin/service/registration-pin.service.spec.ts b/apps/server/src/modules/registration-pin/service/registration-pin.service.spec.ts index 10f2d5231fc..3c80b4ccb1a 100644 --- a/apps/server/src/modules/registration-pin/service/registration-pin.service.spec.ts +++ b/apps/server/src/modules/registration-pin/service/registration-pin.service.spec.ts @@ -7,8 +7,9 @@ import { OperationType, } from '@modules/deletion'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities, userDoFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { RegistrationPinService } from '.'; import { registrationPinEntityFactory } from '../entity/testing'; import { RegistrationPinRepo } from '../repo'; diff --git a/apps/server/src/modules/rocketchat-user/domain/testing/rocket-chat-user.factory.ts b/apps/server/src/modules/rocketchat-user/domain/testing/rocket-chat-user.factory.ts index 3ad6432d1d5..1c6ac26dec1 100644 --- a/apps/server/src/modules/rocketchat-user/domain/testing/rocket-chat-user.factory.ts +++ b/apps/server/src/modules/rocketchat-user/domain/testing/rocket-chat-user.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { RocketChatUser, RocketChatUserProps } from '../rocket-chat-user.do'; export const rocketChatUserFactory = BaseFactory.define( diff --git a/apps/server/src/modules/rocketchat-user/entity/rocket-chat-user.entity.spec.ts b/apps/server/src/modules/rocketchat-user/entity/rocket-chat-user.entity.spec.ts index f8d5318c5bf..4de79b876fb 100644 --- a/apps/server/src/modules/rocketchat-user/entity/rocket-chat-user.entity.spec.ts +++ b/apps/server/src/modules/rocketchat-user/entity/rocket-chat-user.entity.spec.ts @@ -1,6 +1,6 @@ -import { setupEntities } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; import { RocketChatUserEntity } from '@src/modules/rocketchat-user/entity'; +import { setupEntities } from '@testing/setup-entities'; describe(RocketChatUserEntity.name, () => { beforeAll(async () => { diff --git a/apps/server/src/modules/rocketchat-user/entity/testing/rocket-chat-user.entity.factory.ts b/apps/server/src/modules/rocketchat-user/entity/testing/rocket-chat-user.entity.factory.ts index 302459a4eb6..8a0b9033596 100644 --- a/apps/server/src/modules/rocketchat-user/entity/testing/rocket-chat-user.entity.factory.ts +++ b/apps/server/src/modules/rocketchat-user/entity/testing/rocket-chat-user.entity.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { RocketChatUserEntity, RocketChatUserEntityProps } from '../rocket-chat-user.entity'; class RocketChatUserFactory extends BaseFactory {} diff --git a/apps/server/src/modules/rocketchat-user/repo/rocket-chat-user.repo.spec.ts b/apps/server/src/modules/rocketchat-user/repo/rocket-chat-user.repo.spec.ts index 4341a6f956a..491c2915257 100644 --- a/apps/server/src/modules/rocketchat-user/repo/rocket-chat-user.repo.spec.ts +++ b/apps/server/src/modules/rocketchat-user/repo/rocket-chat-user.repo.spec.ts @@ -1,11 +1,11 @@ +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { MongoMemoryDatabaseModule } from '@infra/database'; -import { cleanupCollections } from '@shared/testing'; -import { RocketChatUserMapper } from './mapper'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { RocketChatUserEntity } from '../entity'; -import { RocketChatUserRepo } from './rocket-chat-user.repo'; import { rocketChatUserEntityFactory } from '../entity/testing'; +import { RocketChatUserMapper } from './mapper'; +import { RocketChatUserRepo } from './rocket-chat-user.repo'; describe(RocketChatUserRepo.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/rocketchat-user/service/rocket-chat-user.service.spec.ts b/apps/server/src/modules/rocketchat-user/service/rocket-chat-user.service.spec.ts index 6fa6bcb85ea..5f32938838f 100644 --- a/apps/server/src/modules/rocketchat-user/service/rocket-chat-user.service.spec.ts +++ b/apps/server/src/modules/rocketchat-user/service/rocket-chat-user.service.spec.ts @@ -14,8 +14,8 @@ import { deletionRequestFactory } from '@modules/deletion/domain/testing'; import { RocketChatError, RocketChatService } from '@modules/rocketchat/rocket-chat.service'; import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; -import { setupEntities } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { setupEntities } from '@testing/setup-entities'; import { RocketChatUser } from '../domain'; import { rocketChatUserFactory } from '../domain/testing/rocket-chat-user.factory'; import { RocketChatUserRepo } from '../repo'; diff --git a/apps/server/src/modules/role/mapper/role.mapper.spec.ts b/apps/server/src/modules/role/mapper/role.mapper.spec.ts index 55fb3476e2d..ca0d9727989 100644 --- a/apps/server/src/modules/role/mapper/role.mapper.spec.ts +++ b/apps/server/src/modules/role/mapper/role.mapper.spec.ts @@ -2,7 +2,8 @@ import { RoleMapper } from '@modules/role/mapper/role.mapper'; import { RoleDto } from '@modules/role/service/dto/role.dto'; import { Role } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { roleFactory, setupEntities } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { setupEntities } from '@testing/setup-entities'; describe('RoleMapper', () => { beforeAll(async () => { diff --git a/apps/server/src/modules/role/service/role.service.spec.ts b/apps/server/src/modules/role/service/role.service.spec.ts index c088fadaf0b..74794113f72 100644 --- a/apps/server/src/modules/role/service/role.service.spec.ts +++ b/apps/server/src/modules/role/service/role.service.spec.ts @@ -4,7 +4,7 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Role } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; import { RoleRepo } from '@shared/repo'; -import { roleFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; import { RoleDto } from './dto'; import { RoleService } from './role.service'; diff --git a/apps/server/src/modules/room-membership/authorization/room-membership.rule.spec.ts b/apps/server/src/modules/room-membership/authorization/room-membership.rule.spec.ts index 24384cd6b2b..dd013489377 100644 --- a/apps/server/src/modules/room-membership/authorization/room-membership.rule.spec.ts +++ b/apps/server/src/modules/room-membership/authorization/room-membership.rule.spec.ts @@ -2,7 +2,11 @@ import { Action, AuthorizationHelper, AuthorizationInjectionService } from '@mod import { roomFactory } from '@modules/room/testing'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { roleDtoFactory, roleFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { roleDtoFactory } from '@testing/factory/role-dto.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { RoomMembershipAuthorizable } from '../do/room-membership-authorizable.do'; import { RoomMembershipRule } from './room-membership.rule'; diff --git a/apps/server/src/modules/room-membership/repo/room-membership.repo.spec.ts b/apps/server/src/modules/room-membership/repo/room-membership.repo.spec.ts index 5fb6b3a0932..b122c4e5b3f 100644 --- a/apps/server/src/modules/room-membership/repo/room-membership.repo.spec.ts +++ b/apps/server/src/modules/room-membership/repo/room-membership.repo.spec.ts @@ -2,7 +2,7 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { NotFoundError } from '@mikro-orm/core'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { RoomMembership } from '../do/room-membership.do'; import { roomMembershipEntityFactory, roomMembershipFactory } from '../testing'; import { RoomMembershipEntity } from './entity'; diff --git a/apps/server/src/modules/room-membership/service/room-membership.service.spec.ts b/apps/server/src/modules/room-membership/service/room-membership.service.spec.ts index 7ee7e21aac2..f3f440726f8 100644 --- a/apps/server/src/modules/room-membership/service/room-membership.service.spec.ts +++ b/apps/server/src/modules/room-membership/service/room-membership.service.spec.ts @@ -9,7 +9,11 @@ import { UserService } from '@modules/user'; import { BadRequestException } from '@nestjs/common/exceptions'; import { Test, TestingModule } from '@nestjs/testing'; import { RoleName } from '@shared/domain/interface'; -import { groupFactory, roleDtoFactory, roleFactory, userDoFactory, userFactory } from '@shared/testing'; +import { groupFactory } from '@testing/factory/domainobject'; +import { roleDtoFactory } from '@testing/factory/role-dto.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { RoomMembershipAuthorizable } from '../do/room-membership-authorizable.do'; import { RoomMembershipRepo } from '../repo/room-membership.repo'; import { roomMembershipFactory } from '../testing'; diff --git a/apps/server/src/modules/room-membership/testing/room-membership-entity.factory.ts b/apps/server/src/modules/room-membership/testing/room-membership-entity.factory.ts index 8ea19809b55..5b91cdbf121 100644 --- a/apps/server/src/modules/room-membership/testing/room-membership-entity.factory.ts +++ b/apps/server/src/modules/room-membership/testing/room-membership-entity.factory.ts @@ -1,7 +1,7 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { EntityFactory } from '@shared/testing/factory/entity.factory'; -import { RoomMembershipEntity } from '../repo/entity/room-membership.entity'; +import { EntityFactory } from '@testing/factory/entity.factory'; import { RoomMembershipProps } from '../do/room-membership.do'; +import { RoomMembershipEntity } from '../repo/entity/room-membership.entity'; export const roomMembershipEntityFactory = EntityFactory.define( RoomMembershipEntity, diff --git a/apps/server/src/modules/room-membership/testing/room-membership.factory.ts b/apps/server/src/modules/room-membership/testing/room-membership.factory.ts index 64c294187cb..8c6fc76e371 100644 --- a/apps/server/src/modules/room-membership/testing/room-membership.factory.ts +++ b/apps/server/src/modules/room-membership/testing/room-membership.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { RoomMembership, RoomMembershipProps } from '../do/room-membership.do'; export const roomMembershipFactory = BaseFactory.define(RoomMembership, () => { diff --git a/apps/server/src/modules/room/api/room.uc.spec.ts b/apps/server/src/modules/room/api/room.uc.spec.ts index 95cd6f7f6cd..f1fbc213a6c 100644 --- a/apps/server/src/modules/room/api/room.uc.spec.ts +++ b/apps/server/src/modules/room/api/room.uc.spec.ts @@ -1,14 +1,15 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { AuthorizationService } from '@modules/authorization'; -import { RoomMembershipRepo, RoomMembershipService } from '@src/modules/room-membership'; +import { ColumnBoardService } from '@modules/board'; import { UserService } from '@modules/user'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; import { FeatureDisabledLoggableException } from '@shared/common/loggable-exception'; import { Page } from '@shared/domain/domainobject'; import { IFindOptions } from '@shared/domain/interface'; -import { setupEntities, userFactory } from '@shared/testing'; -import { ColumnBoardService } from '@modules/board'; +import { RoomMembershipRepo, RoomMembershipService } from '@src/modules/room-membership'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Room, RoomService } from '../domain'; import { RoomColor } from '../domain/type'; import { roomFactory } from '../testing'; diff --git a/apps/server/src/modules/room/api/test/room-add-members.api.spec.ts b/apps/server/src/modules/room/api/test/room-add-members.api.spec.ts index a4a9a09f6e9..f8eb192c9ee 100644 --- a/apps/server/src/modules/room/api/test/room-add-members.api.spec.ts +++ b/apps/server/src/modules/room/api/test/room-add-members.api.spec.ts @@ -1,19 +1,17 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { GroupEntityTypes } from '@modules/group/entity/group.entity'; +import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface/permission.enum'; import { RoleName } from '@shared/domain/interface/rolename.enum'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, -} from '@shared/testing'; -import { GroupEntityTypes } from '@modules/group/entity/group.entity'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing/room-membership-entity.factory'; -import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { roomEntityFactory } from '../../testing/room-entity.factory'; describe('Room Controller (API)', () => { diff --git a/apps/server/src/modules/room/api/test/room-create.api.spec.ts b/apps/server/src/modules/room/api/test/room-create.api.spec.ts index 47cecf68d32..083095412a1 100644 --- a/apps/server/src/modules/room/api/test/room-create.api.spec.ts +++ b/apps/server/src/modules/room/api/test/room-create.api.spec.ts @@ -1,11 +1,14 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { GroupEntity } from '@modules/group/entity'; +import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory, cleanupCollections, roleFactory } from '@shared/testing'; -import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; -import { RoomMembershipEntity } from '@src/modules/room-membership'; -import { GroupEntity } from '@modules/group/entity'; import { Permission, RoleName } from '@shared/domain/interface'; +import { RoomMembershipEntity } from '@src/modules/room-membership'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { roleFactory } from '@testing/factory/role.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { RoomEntity } from '../../repo'; describe('Room Controller (API)', () => { diff --git a/apps/server/src/modules/room/api/test/room-delete.api.spec.ts b/apps/server/src/modules/room/api/test/room-delete.api.spec.ts index a088b76b872..26b42041738 100644 --- a/apps/server/src/modules/room/api/test/room-delete.api.spec.ts +++ b/apps/server/src/modules/room/api/test/room-delete.api.spec.ts @@ -4,16 +4,14 @@ import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/serv import { HttpStatus, INestApplication, NotFoundException } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, -} from '@shared/testing'; import { RoomMembershipEntity } from '@src/modules/room-membership'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing/room-membership-entity.factory'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { RoomEntity } from '../../repo'; import { roomEntityFactory } from '../../testing/room-entity.factory'; diff --git a/apps/server/src/modules/room/api/test/room-get-boards.api.spec.ts b/apps/server/src/modules/room/api/test/room-get-boards.api.spec.ts index 2f5dc502c70..8f536fce4b5 100644 --- a/apps/server/src/modules/room/api/test/room-get-boards.api.spec.ts +++ b/apps/server/src/modules/room/api/test/room-get-boards.api.spec.ts @@ -1,20 +1,18 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; -import { HttpStatus, INestApplication } from '@nestjs/common'; -import { Test } from '@nestjs/testing'; -import { Permission, RoleName } from '@shared/domain/interface'; -import { - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; import { BoardExternalReferenceType } from '@modules/board'; import { columnBoardEntityFactory } from '@modules/board/testing'; import { GroupEntityTypes } from '@modules/group/entity'; -import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; import { serverConfig, ServerConfig, ServerTestModule } from '@modules/server'; +import { HttpStatus, INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; +import { Permission, RoleName } from '@shared/domain/interface'; +import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { roomEntityFactory } from '../../testing'; describe('Room Controller (API)', () => { diff --git a/apps/server/src/modules/room/api/test/room-get.api.spec.ts b/apps/server/src/modules/room/api/test/room-get.api.spec.ts index b0aa9afcc68..a667a7ce9e1 100644 --- a/apps/server/src/modules/room/api/test/room-get.api.spec.ts +++ b/apps/server/src/modules/room/api/test/room-get.api.spec.ts @@ -1,18 +1,16 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; +import { GroupEntityTypes } from '@modules/group/entity/group.entity'; +import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, -} from '@shared/testing'; -import { GroupEntityTypes } from '@modules/group/entity/group.entity'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; -import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { roomEntityFactory } from '../../testing/room-entity.factory'; describe('Room Controller (API)', () => { diff --git a/apps/server/src/modules/room/api/test/room-index.api.spec.ts b/apps/server/src/modules/room/api/test/room-index.api.spec.ts index 162fb503a1b..713fee31b10 100644 --- a/apps/server/src/modules/room/api/test/room-index.api.spec.ts +++ b/apps/server/src/modules/room/api/test/room-index.api.spec.ts @@ -1,19 +1,17 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { GroupEntityTypes } from '@modules/group/entity/group.entity'; +import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface/permission.enum'; import { RoleName } from '@shared/domain/interface/rolename.enum'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, -} from '@shared/testing'; -import { GroupEntityTypes } from '@modules/group/entity/group.entity'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing/room-membership-entity.factory'; -import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { roomEntityFactory } from '../../testing/room-entity.factory'; import { RoomListResponse } from '../dto/response/room-list.response'; diff --git a/apps/server/src/modules/room/api/test/room-members.api.spec.ts b/apps/server/src/modules/room/api/test/room-members.api.spec.ts index 2543d750b9e..9ae1c37305d 100644 --- a/apps/server/src/modules/room/api/test/room-members.api.spec.ts +++ b/apps/server/src/modules/room/api/test/room-members.api.spec.ts @@ -1,20 +1,18 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { GroupEntityTypes } from '@modules/group/entity/group.entity'; +import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface/permission.enum'; import { RoleName } from '@shared/domain/interface/rolename.enum'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, - userFactory, -} from '@shared/testing'; -import { GroupEntityTypes } from '@modules/group/entity/group.entity'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing/room-membership-entity.factory'; -import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { roomEntityFactory } from '../../testing/room-entity.factory'; import { RoomMemberListResponse } from '../dto/response/room-member.response'; diff --git a/apps/server/src/modules/room/api/test/room-remove-members.api.spec.ts b/apps/server/src/modules/room/api/test/room-remove-members.api.spec.ts index f52dfc0bf2d..d34c6a78ae4 100644 --- a/apps/server/src/modules/room/api/test/room-remove-members.api.spec.ts +++ b/apps/server/src/modules/room/api/test/room-remove-members.api.spec.ts @@ -1,19 +1,17 @@ import { EntityManager } from '@mikro-orm/mongodb'; +import { GroupEntityTypes } from '@modules/group/entity/group.entity'; +import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface/permission.enum'; import { RoleName } from '@shared/domain/interface/rolename.enum'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, -} from '@shared/testing'; -import { GroupEntityTypes } from '@modules/group/entity/group.entity'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing/room-membership-entity.factory'; -import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { roomEntityFactory } from '../../testing/room-entity.factory'; describe('Room Controller (API)', () => { diff --git a/apps/server/src/modules/room/api/test/room-update.api.spec.ts b/apps/server/src/modules/room/api/test/room-update.api.spec.ts index bc505ddc6aa..2e23d47264a 100644 --- a/apps/server/src/modules/room/api/test/room-update.api.spec.ts +++ b/apps/server/src/modules/room/api/test/room-update.api.spec.ts @@ -1,17 +1,15 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; +import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, -} from '@shared/testing'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; -import { ServerTestModule, serverConfig, type ServerConfig } from '@modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { RoomEntity } from '../../repo'; import { roomEntityFactory } from '../../testing'; diff --git a/apps/server/src/modules/room/repo/room.repo.spec.ts b/apps/server/src/modules/room/repo/room.repo.spec.ts index d89fd630b4e..c074f03b364 100644 --- a/apps/server/src/modules/room/repo/room.repo.spec.ts +++ b/apps/server/src/modules/room/repo/room.repo.spec.ts @@ -3,7 +3,7 @@ import { NotFoundError } from '@mikro-orm/core'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { Page } from '@shared/domain/domainobject'; -import { cleanupCollections } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { Room } from '../domain/do/room.do'; import { roomEntityFactory, roomFactory } from '../testing'; import { RoomEntity } from './entity'; diff --git a/apps/server/src/modules/room/testing/room-entity.factory.ts b/apps/server/src/modules/room/testing/room-entity.factory.ts index ad2e979750e..6b6c1e2930b 100644 --- a/apps/server/src/modules/room/testing/room-entity.factory.ts +++ b/apps/server/src/modules/room/testing/room-entity.factory.ts @@ -1,8 +1,8 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { EntityFactory } from '@shared/testing/factory/entity.factory'; -import { RoomEntity } from '../repo/entity/room.entity'; +import { EntityFactory } from '@testing/factory/entity.factory'; import { RoomProps } from '../domain'; import { RoomColor } from '../domain/type'; +import { RoomEntity } from '../repo/entity/room.entity'; export const roomEntityFactory = EntityFactory.define(RoomEntity, ({ sequence }) => { return { diff --git a/apps/server/src/modules/room/testing/room.factory.ts b/apps/server/src/modules/room/testing/room.factory.ts index 7f1ef879488..6026812f9c5 100644 --- a/apps/server/src/modules/room/testing/room.factory.ts +++ b/apps/server/src/modules/room/testing/room.factory.ts @@ -1,5 +1,5 @@ -import { BaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { BaseFactory } from '@testing/factory/base.factory'; import { Room, RoomProps } from '../domain/do/room.do'; import { RoomColor } from '../domain/type'; diff --git a/apps/server/src/modules/roster/service/feathers-roster.service.spec.ts b/apps/server/src/modules/roster/service/feathers-roster.service.spec.ts index 2f14165bd7b..0b44350b7ed 100644 --- a/apps/server/src/modules/roster/service/feathers-roster.service.spec.ts +++ b/apps/server/src/modules/roster/service/feathers-roster.service.spec.ts @@ -23,15 +23,12 @@ import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { LegacySchoolDo, Pseudonym, UserDO } from '@shared/domain/domainobject'; import { Course, SchoolEntity } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; -import { - courseFactory, - legacySchoolDoFactory, - pseudonymFactory, - schoolEntityFactory, - setupEntities, - UserAndAccountTestFactory, - userDoFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { legacySchoolDoFactory, pseudonymFactory } from '@testing/factory/domainobject'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { RosterConfig } from '../roster.config'; import { FeathersRosterService } from './feathers-roster.service'; diff --git a/apps/server/src/modules/school-license/repo/mikro-orm/media-school-license.repo.integration.spec.ts b/apps/server/src/modules/school-license/repo/mikro-orm/media-school-license.repo.integration.spec.ts index 04fc53848ae..ecbd1a33775 100644 --- a/apps/server/src/modules/school-license/repo/mikro-orm/media-school-license.repo.integration.spec.ts +++ b/apps/server/src/modules/school-license/repo/mikro-orm/media-school-license.repo.integration.spec.ts @@ -1,11 +1,11 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; -import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections } from '@shared/testing'; import { mediaSourceEntityFactory } from '@modules/media-source/testing'; -import { MediaSchoolLicenseMikroOrmRepo } from './media-school-license.repo'; +import { Test, TestingModule } from '@nestjs/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { MediaSchoolLicenseEntity } from '../../entity'; import { mediaSchoolLicenseEntityFactory, mediaSchoolLicenseFactory } from '../../testing'; +import { MediaSchoolLicenseMikroOrmRepo } from './media-school-license.repo'; describe(MediaSchoolLicenseMikroOrmRepo.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/school-license/testing/media-school-license-entity.factory.ts b/apps/server/src/modules/school-license/testing/media-school-license-entity.factory.ts index 5bbee29b07a..ef5a585a097 100644 --- a/apps/server/src/modules/school-license/testing/media-school-license-entity.factory.ts +++ b/apps/server/src/modules/school-license/testing/media-school-license-entity.factory.ts @@ -1,6 +1,7 @@ -import { BaseFactory, schoolEntityFactory } from '@shared/testing'; -import { mediaSourceEntityFactory } from '@modules/media-source/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { mediaSourceEntityFactory } from '@modules/media-source/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; import { MediaSchoolLicenseEntity, MediaSchoolLicenseEntityProps } from '../entity'; import { SchoolLicenseType } from '../enum'; diff --git a/apps/server/src/modules/school-license/testing/media-school-license.factory.ts b/apps/server/src/modules/school-license/testing/media-school-license.factory.ts index da72ca2ca5d..a984f769b08 100644 --- a/apps/server/src/modules/school-license/testing/media-school-license.factory.ts +++ b/apps/server/src/modules/school-license/testing/media-school-license.factory.ts @@ -1,7 +1,7 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; import { mediaSourceFactory } from '@modules/media-source/testing'; import { schoolFactory } from '@modules/school/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaSchoolLicense, MediaSchoolLicenseProps } from '../domain'; import { SchoolLicenseType } from '../enum'; diff --git a/apps/server/src/modules/school/api/school.controller.ts b/apps/server/src/modules/school/api/school.controller.ts index a2cd034f523..5da7e5e11e1 100644 --- a/apps/server/src/modules/school/api/school.controller.ts +++ b/apps/server/src/modules/school/api/school.controller.ts @@ -2,7 +2,6 @@ import { CurrentUser, ICurrentUser, JwtAuthentication } from '@infra/auth-guard' import { Body, Controller, ForbiddenException, Get, NotFoundException, Param, Patch, Query } from '@nestjs/common'; import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'; import { ApiValidationError } from '@shared/common'; -import { PaginationParams } from '@shared/controller'; import { SchoolQueryParams, SchoolRemoveSystemUrlParams, SchoolUpdateBodyParams, SchoolUrlParams } from './dto/param'; import { SchoolForExternalInviteResponse, SchoolResponse, SchoolSystemResponse } from './dto/response'; import { SchoolExistsResponse } from './dto/response/school-exists.response'; @@ -98,10 +97,9 @@ export class SchoolController { @JwtAuthentication() public async getTeachers( @Param() urlParams: SchoolUrlParams, - @CurrentUser() user: ICurrentUser, - @Query() pagination: PaginationParams + @CurrentUser() user: ICurrentUser ): Promise { - const res = await this.schoolUc.getSchoolTeachers(urlParams.schoolId, user.userId, pagination); + const res = await this.schoolUc.getSchoolTeachers(urlParams.schoolId, user.userId); return res; } } diff --git a/apps/server/src/modules/school/api/school.uc.ts b/apps/server/src/modules/school/api/school.uc.ts index a8a01d8a643..85206590cb4 100644 --- a/apps/server/src/modules/school/api/school.uc.ts +++ b/apps/server/src/modules/school/api/school.uc.ts @@ -1,6 +1,5 @@ import { AuthorizationContextBuilder, AuthorizationService } from '@modules/authorization'; import { Injectable } from '@nestjs/common'; -import { PaginationParams } from '@shared/controller'; import { Page, UserDO } from '@shared/domain/domainobject'; import { User } from '@shared/domain/entity'; import { Permission, RoleName, SortOrder } from '@shared/domain/interface'; @@ -133,11 +132,7 @@ export class SchoolUc { return dto; } - public async getSchoolTeachers( - schoolId: EntityId, - userId: EntityId, - pagination?: PaginationParams - ): Promise { + public async getSchoolTeachers(schoolId: EntityId, userId: EntityId): Promise { const [school, user] = await Promise.all([ this.schoolService.getSchoolById(schoolId), this.authorizationService.getUserWithPermissions(userId), @@ -149,12 +144,12 @@ export class SchoolUc { let result: Page; if (isUserOfSchool) { - result = await this.userService.findBySchoolRole(schoolId, RoleName.TEACHER, { pagination }); + result = await this.userService.findBySchoolRole(schoolId, RoleName.TEACHER); } else { - result = await this.userService.findPublicTeachersBySchool(schoolId, { pagination }); + result = await this.userService.findPublicTeachersBySchool(schoolId); } - const responseDto = SchoolUserResponseMapper.mapToListResponse(result, pagination); + const responseDto = SchoolUserResponseMapper.mapToListResponse(result); return responseDto; } diff --git a/apps/server/src/modules/school/api/test/school-get.api.spec.ts b/apps/server/src/modules/school/api/test/school-get.api.spec.ts index 2246f8c18a9..8e6adab55bc 100644 --- a/apps/server/src/modules/school/api/test/school-get.api.spec.ts +++ b/apps/server/src/modules/school/api/test/school-get.api.spec.ts @@ -1,17 +1,15 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - countyEmbeddableFactory, - federalStateFactory, - schoolEntityFactory, - schoolYearFactory, - systemEntityFactory, -} from '@shared/testing'; import { ServerTestModule } from '@src/modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { countyEmbeddableFactory } from '@testing/factory/county.embeddable.factory'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; describe('School Controller (API)', () => { let app: INestApplication; diff --git a/apps/server/src/modules/school/api/test/school-patch.api.spec.ts b/apps/server/src/modules/school/api/test/school-patch.api.spec.ts index acfa1e83a2c..2b4e247fe39 100644 --- a/apps/server/src/modules/school/api/test/school-patch.api.spec.ts +++ b/apps/server/src/modules/school/api/test/school-patch.api.spec.ts @@ -3,17 +3,15 @@ import { SystemEntity } from '@modules/system/entity'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; -import { - cleanupCollections, - countyEmbeddableFactory, - federalStateFactory, - schoolEntityFactory, - schoolYearFactory, - systemEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; import { ServerTestModule } from '@src/modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { countyEmbeddableFactory } from '@testing/factory/county.embeddable.factory'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { SchoolErrorEnum } from '../../domain/error'; describe('School Controller (API)', () => { diff --git a/apps/server/src/modules/school/api/test/school-users.api.spec.ts b/apps/server/src/modules/school/api/test/school-users.api.spec.ts index 2c02af91a27..fff703664bb 100644 --- a/apps/server/src/modules/school/api/test/school-users.api.spec.ts +++ b/apps/server/src/modules/school/api/test/school-users.api.spec.ts @@ -1,14 +1,12 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { - cleanupCollections, - schoolEntityFactory, - TestApiClient, - UserAndAccountTestFactory, - userFactory, -} from '@shared/testing'; import { ServerTestModule } from '@src/modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { SchoolUserListResponse } from '../dto/response/school-user.response'; describe('School Controller (API)', () => { @@ -204,17 +202,6 @@ describe('School Controller (API)', () => { ]) ); }); - - it('should paginate', async () => { - const { loggedInClient, school } = await setup(); - - const response = await loggedInClient.get(`${school.id}/teachers`).query({ skip: 1, limit: 1 }); - const body = response.body as SchoolUserListResponse; - - expect(body.data).toHaveLength(1); - expect(body.total).toEqual(4); - expect(body.skip).toEqual(1); - }); }); }); }); diff --git a/apps/server/src/modules/school/repo/mikro-orm/mapper/school.entity.mapper.spec.ts b/apps/server/src/modules/school/repo/mikro-orm/mapper/school.entity.mapper.spec.ts index b1838ae2185..54203ad7050 100644 --- a/apps/server/src/modules/school/repo/mikro-orm/mapper/school.entity.mapper.spec.ts +++ b/apps/server/src/modules/school/repo/mikro-orm/mapper/school.entity.mapper.spec.ts @@ -1,5 +1,6 @@ import { SystemEntity } from '@modules/system/entity'; -import { schoolEntityFactory, setupEntities } from '@shared/testing'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { setupEntities } from '@testing/setup-entities'; import { School } from '../../../domain'; import { CountyEmbeddableMapper } from './county.embeddable.mapper'; import { FederalStateEntityMapper } from './federal-state.entity.mapper'; diff --git a/apps/server/src/modules/school/repo/mikro-orm/school-year.repo.integration.spec.ts b/apps/server/src/modules/school/repo/mikro-orm/school-year.repo.integration.spec.ts index eecb36bb3fe..d8b393f046b 100644 --- a/apps/server/src/modules/school/repo/mikro-orm/school-year.repo.integration.spec.ts +++ b/apps/server/src/modules/school/repo/mikro-orm/school-year.repo.integration.spec.ts @@ -1,8 +1,9 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolYearEntity } from '@shared/domain/entity/schoolyear.entity'; -import { cleanupCollections, schoolYearFactory } from '@shared/testing'; import { MongoMemoryDatabaseModule } from '@src/infra/database'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; import { SCHOOL_YEAR_REPO } from '../../domain'; import { SchoolYearEntityMapper } from './mapper'; import { SchoolYearMikroOrmRepo } from './school-year.repo'; diff --git a/apps/server/src/modules/school/repo/mikro-orm/school.repo.integration.spec.ts b/apps/server/src/modules/school/repo/mikro-orm/school.repo.integration.spec.ts index 342ef28ef77..6a4680e16b5 100644 --- a/apps/server/src/modules/school/repo/mikro-orm/school.repo.integration.spec.ts +++ b/apps/server/src/modules/school/repo/mikro-orm/school.repo.integration.spec.ts @@ -5,15 +5,13 @@ import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity/school.entity'; import { LanguageType, SortOrder } from '@shared/domain/interface'; import { SchoolFeature, SchoolPurpose } from '@shared/domain/types'; -import { - cleanupCollections, - federalStateFactory as federalStateEntityFactory, - schoolEntityFactory, - schoolYearFactory as schoolYearEntityFactory, - systemEntityFactory, -} from '@shared/testing'; -import { countyEmbeddableFactory } from '@shared/testing/factory/county.embeddable.factory'; import { MongoMemoryDatabaseModule } from '@src/infra/database'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { countyEmbeddableFactory } from '@testing/factory/county.embeddable.factory'; +import { federalStateFactory as federalStateEntityFactory } from '@testing/factory/federal-state.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolYearFactory as schoolYearEntityFactory } from '@testing/factory/schoolyear.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; import { FileStorageType, SCHOOL_REPO } from '../../domain'; import { federalStateFactory, schoolFactory } from '../../testing'; import { countyFactory } from '../../testing/county.factory'; diff --git a/apps/server/src/modules/school/testing/county.factory.ts b/apps/server/src/modules/school/testing/county.factory.ts index b7ea95b66d6..2c3f5491331 100644 --- a/apps/server/src/modules/school/testing/county.factory.ts +++ b/apps/server/src/modules/school/testing/county.factory.ts @@ -1,5 +1,5 @@ -import { BaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { BaseFactory } from '@testing/factory/base.factory'; import { County, CountyProps } from '../domain'; export const countyFactory = BaseFactory.define(County, ({ sequence }) => { diff --git a/apps/server/src/modules/school/testing/federal-state.factory.ts b/apps/server/src/modules/school/testing/federal-state.factory.ts index 884c61905c0..0ded48bf01f 100644 --- a/apps/server/src/modules/school/testing/federal-state.factory.ts +++ b/apps/server/src/modules/school/testing/federal-state.factory.ts @@ -1,5 +1,5 @@ -import { BaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { BaseFactory } from '@testing/factory/base.factory'; import { FederalState, FederalStateProps } from '../domain'; import { countyFactory } from './county.factory'; diff --git a/apps/server/src/modules/school/testing/school-year.factory.ts b/apps/server/src/modules/school/testing/school-year.factory.ts index e32f61c191a..d5d62ee2a86 100644 --- a/apps/server/src/modules/school/testing/school-year.factory.ts +++ b/apps/server/src/modules/school/testing/school-year.factory.ts @@ -1,5 +1,5 @@ -import { BaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { BaseFactory } from '@testing/factory/base.factory'; import { SchoolYear, SchoolYearProps } from '../domain'; type SchoolYearTransientParams = { diff --git a/apps/server/src/modules/school/testing/school.factory.ts b/apps/server/src/modules/school/testing/school.factory.ts index e44195c9cbb..da4e73383b2 100644 --- a/apps/server/src/modules/school/testing/school.factory.ts +++ b/apps/server/src/modules/school/testing/school.factory.ts @@ -1,6 +1,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { SchoolFeature } from '@shared/domain/types'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { School, SchoolProps } from '../domain'; import { federalStateFactory } from './federal-state.factory'; diff --git a/apps/server/src/modules/server/api/test/server.api.spec.ts b/apps/server/src/modules/server/api/test/server.api.spec.ts index 1e237aa72e1..eec44b899b0 100644 --- a/apps/server/src/modules/server/api/test/server.api.spec.ts +++ b/apps/server/src/modules/server/api/test/server.api.spec.ts @@ -1,7 +1,7 @@ import { ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient } from '@shared/testing'; +import { TestApiClient } from '@testing/test-api-client'; import { ConfigResponse } from '../dto'; describe('Server Controller (API)', () => { diff --git a/apps/server/src/modules/sharing/controller/api-test/sharing-create-token.api.spec.ts b/apps/server/src/modules/sharing/controller/api-test/sharing-create-token.api.spec.ts index d7aa58a65e4..dbb5dced8df 100644 --- a/apps/server/src/modules/sharing/controller/api-test/sharing-create-token.api.spec.ts +++ b/apps/server/src/modules/sharing/controller/api-test/sharing-create-token.api.spec.ts @@ -1,112 +1,88 @@ import { Configuration } from '@hpi-schul-cloud/commons/lib'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; -import { ExecutionContext, HttpStatus, INestApplication } from '@nestjs/common'; +import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { ApiValidationError } from '@shared/common'; -import { Permission } from '@shared/domain/interface'; -import { - cleanupCollections, - courseFactory, - mapUserToCurrentUser, - roleFactory, - schoolEntityFactory, - userFactory, -} from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { ShareTokenParentType } from '../../domainobject/share-token.do'; -import { ShareTokenBodyParams, ShareTokenResponse } from '../dto'; +import { ShareTokenResponse } from '../dto'; const baseRouteName = '/sharetoken'; -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async post(body: ShareTokenBodyParams) { - const response = await request(this.app.getHttpServer()) - .post(`${baseRouteName}`) - .set('Accept', 'application/json') - .send(body); - - return { - result: response.body as ShareTokenResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} - describe(`share token creation (api)`, () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; + let apiClient: TestApiClient; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); - api = new API(app); + + apiClient = new TestApiClient(app, baseRouteName); }); afterAll(async () => { await app.close(); }); - beforeEach(() => { - Configuration.set('FEATURE_COURSE_SHARE', true); - }); + describe('with the feature disabled', () => { + const setup = async () => { + await cleanupCollections(em); - const setup = async () => { - await cleanupCollections(em); - const school = schoolEntityFactory.build(); - const roles = roleFactory.buildList(1, { - permissions: [Permission.COURSE_CREATE], - }); - const user = userFactory.build({ school, roles }); - const course = courseFactory.build({ teachers: [user] }); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); - await em.persistAndFlush([user, course]); - em.clear(); + await em.persistAndFlush([teacherAccount, teacherUser, course]); + em.clear(); - currentUser = mapUserToCurrentUser(user); + Configuration.set('FEATURE_COURSE_SHARE', false); - return { course }; - }; + const loggedInClient = await apiClient.login(teacherAccount); + + return { course, loggedInClient }; + }; - describe('with the feature disabled', () => { it('should return status 403', async () => { - Configuration.set('FEATURE_COURSE_SHARE', false); - const { course } = await setup(); + const { course, loggedInClient } = await setup(); - const response = await api.post({ parentId: course.id, parentType: ShareTokenParentType.Course }); + const response = await loggedInClient.post(undefined, { + parentId: course.id, + parentType: ShareTokenParentType.Course, + }); expect(response.status).toEqual(HttpStatus.FORBIDDEN); }); }); describe('with invalid request data', () => { + const setup = async () => { + await cleanupCollections(em); + + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + + await em.persistAndFlush([teacherAccount, teacherUser, course]); + em.clear(); + + Configuration.set('FEATURE_COURSE_SHARE', true); + + const loggedInClient = await apiClient.login(teacherAccount); + + return { course, loggedInClient }; + }; + it('should return status 400 on empty parent id', async () => { - const response = await api.post({ + const { loggedInClient } = await setup(); + + const response = await loggedInClient.post(undefined, { parentId: '', parentType: ShareTokenParentType.Course, }); @@ -115,7 +91,9 @@ describe(`share token creation (api)`, () => { }); it('should return status 404 when parent id is not found', async () => { - const response = await api.post({ + const { loggedInClient } = await setup(); + + const response = await loggedInClient.post(undefined, { parentId: new ObjectId().toHexString(), parentType: ShareTokenParentType.Course, }); @@ -124,7 +102,9 @@ describe(`share token creation (api)`, () => { }); it('should return status 400 on invalid parent id', async () => { - const response = await api.post({ + const { loggedInClient } = await setup(); + + const response = await loggedInClient.post(undefined, { parentId: 'foobar', parentType: ShareTokenParentType.Course, }); @@ -133,11 +113,10 @@ describe(`share token creation (api)`, () => { }); it('should return status 400 on invalid parent type', async () => { - const { course } = await setup(); + const { course, loggedInClient } = await setup(); - const response = await api.post({ + const response = await loggedInClient.post(undefined, { parentId: course.id, - // @ts-expect-error test parentType: 'invalid', }); @@ -145,12 +124,11 @@ describe(`share token creation (api)`, () => { }); it('should return status 400 when expiresInDays is invalid integer', async () => { - const { course } = await setup(); + const { course, loggedInClient } = await setup(); - const response = await api.post({ + const response = await loggedInClient.post(undefined, { parentId: course.id, parentType: ShareTokenParentType.Course, - // @ts-expect-error test expiresInDays: 'foo', }); @@ -158,9 +136,9 @@ describe(`share token creation (api)`, () => { }); it('should return status 400 when expiresInDays is negative', async () => { - const { course } = await setup(); + const { course, loggedInClient } = await setup(); - const response = await api.post({ + const response = await loggedInClient.post(undefined, { parentId: course.id, parentType: ShareTokenParentType.Course, expiresInDays: -10, @@ -170,9 +148,9 @@ describe(`share token creation (api)`, () => { }); it('should return status 400 when expiresInDays is not an integer', async () => { - const { course } = await setup(); + const { course, loggedInClient } = await setup(); - const response = await api.post({ + const response = await loggedInClient.post(undefined, { parentId: course.id, parentType: ShareTokenParentType.Course, expiresInDays: 2.5, @@ -183,51 +161,44 @@ describe(`share token creation (api)`, () => { }); describe('with valid course payload', () => { - it('should return status 201', async () => { - const { course } = await setup(); + describe('with authenticated user', () => { + const setup = async () => { + await cleanupCollections(em); - const response = await api.post({ parentId: course.id, parentType: ShareTokenParentType.Course }); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); - expect(response.status).toEqual(HttpStatus.CREATED); - }); + await em.persistAndFlush([teacherAccount, teacherUser, course]); + em.clear(); - it('should return a valid result', async () => { - const { course } = await setup(); + Configuration.set('FEATURE_COURSE_SHARE', true); - const response = await api.post({ parentId: course.id, parentType: ShareTokenParentType.Course }); + const loggedInClient = await apiClient.login(teacherAccount); - expect(response.result).toEqual({ - token: expect.any(String), - payload: { - parentId: course.id, - parentType: ShareTokenParentType.Course, - }, - }); - }); + return { course, loggedInClient }; + }; - describe('when exclusive to school', () => { it('should return status 201', async () => { - const { course } = await setup(); + const { course, loggedInClient } = await setup(); - const response = await api.post({ + const response = await loggedInClient.post(undefined, { parentId: course.id, parentType: ShareTokenParentType.Course, - schoolExclusive: true, }); expect(response.status).toEqual(HttpStatus.CREATED); }); it('should return a valid result', async () => { - const { course } = await setup(); + const { course, loggedInClient } = await setup(); - const response = await api.post({ + const response = await loggedInClient.post(undefined, { parentId: course.id, parentType: ShareTokenParentType.Course, - schoolExclusive: true, }); + const result = response.body as ShareTokenResponse; - expect(response.result).toEqual({ + expect(result).toEqual({ token: expect.any(String), payload: { parentId: course.id, @@ -235,39 +206,100 @@ describe(`share token creation (api)`, () => { }, }); }); - }); - describe('with expiration duration', () => { - it('should return status 201', async () => { - const { course } = await setup(); + describe('when exclusive to school', () => { + it('should return status 201', async () => { + const { course, loggedInClient } = await setup(); - const response = await api.post({ - parentId: course.id, - parentType: ShareTokenParentType.Course, - expiresInDays: 5, + const response = await loggedInClient.post(undefined, { + parentId: course.id, + parentType: ShareTokenParentType.Course, + schoolExclusive: true, + }); + + expect(response.status).toEqual(HttpStatus.CREATED); }); - expect(response.status).toEqual(HttpStatus.CREATED); + it('should return a valid result', async () => { + const { course, loggedInClient } = await setup(); + + const response = await loggedInClient.post(undefined, { + parentId: course.id, + parentType: ShareTokenParentType.Course, + schoolExclusive: true, + }); + const result = response.body as ShareTokenResponse; + + expect(result).toEqual({ + token: expect.any(String), + payload: { + parentId: course.id, + parentType: ShareTokenParentType.Course, + }, + }); + }); }); - it('should return a valid result containg the expiration timestamp', async () => { - const { course } = await setup(); + describe('with expiration duration', () => { + it('should return status 201', async () => { + const { course, loggedInClient } = await setup(); - const response = await api.post({ - parentId: course.id, - parentType: ShareTokenParentType.Course, - expiresInDays: 5, + const response = await loggedInClient.post(undefined, { + parentId: course.id, + parentType: ShareTokenParentType.Course, + expiresInDays: 5, + }); + + expect(response.status).toEqual(HttpStatus.CREATED); }); - expect(response.result).toEqual({ - token: expect.any(String), - expiresAt: expect.any(String), - payload: { + it('should return a valid result containg the expiration timestamp', async () => { + const { course, loggedInClient } = await setup(); + + const response = await loggedInClient.post(undefined, { parentId: course.id, parentType: ShareTokenParentType.Course, - }, + expiresInDays: 5, + }); + const result = response.body as ShareTokenResponse; + + expect(result).toEqual({ + token: expect.any(String), + expiresAt: expect.any(String), + payload: { + parentId: course.id, + parentType: ShareTokenParentType.Course, + }, + }); }); }); }); + + describe('with not authenticated user', () => { + const setup = async () => { + await cleanupCollections(em); + + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + + await em.persistAndFlush([teacherAccount, teacherUser, course]); + em.clear(); + + Configuration.set('FEATURE_COURSE_SHARE', true); + + return { course }; + }; + + it('should return status 401', async () => { + const { course } = await setup(); + + const response = await apiClient.post(undefined, { + parentId: course.id, + parentType: ShareTokenParentType.Course, + }); + + expect(response.status).toEqual(HttpStatus.UNAUTHORIZED); + }); + }); }); }); diff --git a/apps/server/src/modules/sharing/controller/api-test/sharing-import-room-board-token.api.spec.ts b/apps/server/src/modules/sharing/controller/api-test/sharing-import-room-board-token.api.spec.ts index c63c27bf6d5..a3f67035aff 100644 --- a/apps/server/src/modules/sharing/controller/api-test/sharing-import-room-board-token.api.spec.ts +++ b/apps/server/src/modules/sharing/controller/api-test/sharing-import-room-board-token.api.spec.ts @@ -3,20 +3,18 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { Permission, RoleName } from '@shared/domain/interface'; -import { - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; import { BoardExternalReferenceType } from '@src/modules/board'; import { columnBoardEntityFactory } from '@src/modules/board/testing'; import { GroupEntityTypes } from '@src/modules/group/entity'; import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; import { roomEntityFactory } from '@src/modules/room/testing'; import { ServerTestModule } from '@src/modules/server'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { ShareTokenParentType } from '../../domainobject/share-token.do'; import { ShareTokenService } from '../../service'; diff --git a/apps/server/src/modules/sharing/controller/api-test/sharing-import-token.api.spec.ts b/apps/server/src/modules/sharing/controller/api-test/sharing-import-token.api.spec.ts index 02309bc3241..d9d43c4ef20 100644 --- a/apps/server/src/modules/sharing/controller/api-test/sharing-import-token.api.spec.ts +++ b/apps/server/src/modules/sharing/controller/api-test/sharing-import-token.api.spec.ts @@ -1,11 +1,5 @@ import { Configuration } from '@hpi-schul-cloud/commons/lib'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; -import { CopyApiResponse, CopyElementType, CopyStatusEnum } from '@modules/copy-helper'; -import { serverConfig, type ServerConfig, ServerTestModule } from '@modules/server'; -import { HttpStatus, INestApplication } from '@nestjs/common'; -import { Test, TestingModule } from '@nestjs/testing'; -import { Permission } from '@shared/domain/interface'; -import { Course } from '@shared/domain/entity'; import { BoardExternalReferenceType } from '@modules/board'; import { BoardNodeType } from '@modules/board/domain'; import { BoardNodeEntity } from '@modules/board/repo'; @@ -15,19 +9,23 @@ import { columnEntityFactory, externalToolElementEntityFactory, } from '@modules/board/testing'; +import { CopyApiResponse, CopyElementType, CopyStatusEnum } from '@modules/copy-helper'; +import { serverConfig, type ServerConfig, ServerTestModule } from '@modules/server'; import { ContextExternalToolEntity, ContextExternalToolType } from '@modules/tool/context-external-tool/entity'; +import { contextExternalToolEntityFactory } from '@modules/tool/context-external-tool/testing'; import { externalToolEntityFactory } from '@modules/tool/external-tool/testing'; import { schoolExternalToolEntityFactory } from '@modules/tool/school-external-tool/testing'; -import { contextExternalToolEntityFactory } from '@modules/tool/context-external-tool/testing'; -import { - cleanupCollections, - courseFactory, - schoolEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; -import { shareTokenFactory } from '../../testing/share-token.factory'; +import { HttpStatus, INestApplication } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { Course } from '@shared/domain/entity'; +import { Permission } from '@shared/domain/interface'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { ShareTokenContextType } from '../../domainobject/share-token.do'; +import { shareTokenFactory } from '../../testing/share-token.factory'; import { ShareTokenImportBodyParams } from '../dto'; describe(`Share Token Import (API)`, () => { diff --git a/apps/server/src/modules/sharing/controller/api-test/sharing-lookup-token.api.spec.ts b/apps/server/src/modules/sharing/controller/api-test/sharing-lookup-token.api.spec.ts index adf854d9b3d..a0ece0a5d50 100644 --- a/apps/server/src/modules/sharing/controller/api-test/sharing-lookup-token.api.spec.ts +++ b/apps/server/src/modules/sharing/controller/api-test/sharing-lookup-token.api.spec.ts @@ -4,7 +4,10 @@ import { ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { courseFactory, schoolEntityFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { ShareTokenContextType, ShareTokenParentType } from '../../domainobject/share-token.do'; import { ShareTokenService } from '../../service'; import { ShareTokenInfoResponse } from '../dto'; diff --git a/apps/server/src/modules/sharing/controller/share-token.controller.spec.ts b/apps/server/src/modules/sharing/controller/share-token.controller.spec.ts index cdd5f009ca2..d51463984e7 100644 --- a/apps/server/src/modules/sharing/controller/share-token.controller.spec.ts +++ b/apps/server/src/modules/sharing/controller/share-token.controller.spec.ts @@ -1,7 +1,10 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { CopyElementType, CopyStatus, CopyStatusEnum } from '@modules/copy-helper'; import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, currentUserFactory, setupEntities, shareTokenFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; +import { shareTokenFactory } from '@testing/factory/share-token.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ShareTokenParentType } from '../domainobject/share-token.do'; import { ShareTokenUC } from '../uc'; import { ShareTokenInfoDto } from '../uc/dto'; diff --git a/apps/server/src/modules/sharing/entity/share-token.entity.spec.ts b/apps/server/src/modules/sharing/entity/share-token.entity.spec.ts index 6d822ba8c8e..814ec073ab7 100644 --- a/apps/server/src/modules/sharing/entity/share-token.entity.spec.ts +++ b/apps/server/src/modules/sharing/entity/share-token.entity.spec.ts @@ -1,5 +1,5 @@ -import { setupEntities } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { setupEntities } from '@testing/setup-entities'; import { ShareTokenContextType, ShareTokenParentType } from '../domainobject/share-token.do'; import { ShareToken } from './share-token.entity'; diff --git a/apps/server/src/modules/sharing/repo/share-token.repo.integration.spec.ts b/apps/server/src/modules/sharing/repo/share-token.repo.integration.spec.ts index dc0f03f1d49..52514fcd4f8 100644 --- a/apps/server/src/modules/sharing/repo/share-token.repo.integration.spec.ts +++ b/apps/server/src/modules/sharing/repo/share-token.repo.integration.spec.ts @@ -2,8 +2,10 @@ import { createMock } from '@golevelup/ts-jest'; import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections, schoolEntityFactory, shareTokenFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { shareTokenFactory } from '@testing/factory/share-token.do.factory'; import { ShareTokenContextType } from '../domainobject/share-token.do'; import { ShareTokenRepo } from './share-token.repo'; diff --git a/apps/server/src/modules/sharing/service/share-token.service.spec.ts b/apps/server/src/modules/sharing/service/share-token.service.spec.ts index 1f721e7a00b..72aa44218e8 100644 --- a/apps/server/src/modules/sharing/service/share-token.service.spec.ts +++ b/apps/server/src/modules/sharing/service/share-token.service.spec.ts @@ -1,13 +1,17 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { NotFoundException } from '@nestjs/common'; -import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, lessonFactory, setupEntities, shareTokenFactory, taskFactory } from '@shared/testing'; +import { ObjectId } from '@mikro-orm/mongodb'; +import { ColumnBoardService } from '@modules/board/service'; import { columnBoardFactory } from '@modules/board/testing'; import { CourseService } from '@modules/learnroom/service'; -import { ColumnBoardService } from '@modules/board/service'; import { LessonService } from '@modules/lesson/service'; import { TaskService } from '@modules/task/service'; -import { ObjectId } from '@mikro-orm/mongodb'; +import { NotFoundException } from '@nestjs/common'; +import { Test, TestingModule } from '@nestjs/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { shareTokenFactory } from '@testing/factory/share-token.do.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ShareTokenContextType, ShareTokenParentType } from '../domainobject/share-token.do'; import { ShareTokenRepo } from '../repo/share-token.repo'; import { ShareTokenService } from './share-token.service'; diff --git a/apps/server/src/modules/sharing/testing/share-token.factory.ts b/apps/server/src/modules/sharing/testing/share-token.factory.ts index a9faea781f8..1f3d25a984a 100644 --- a/apps/server/src/modules/sharing/testing/share-token.factory.ts +++ b/apps/server/src/modules/sharing/testing/share-token.factory.ts @@ -1,9 +1,9 @@ -import { ShareToken, ShareTokenProperties } from '@modules/sharing/entity/share-token.entity'; -import { ShareTokenContextType, ShareTokenParentType } from '@modules/sharing/domainobject/share-token.do'; -import { BaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; -import { nanoid } from 'nanoid'; +import { ShareTokenContextType, ShareTokenParentType } from '@modules/sharing/domainobject/share-token.do'; +import { ShareToken, ShareTokenProperties } from '@modules/sharing/entity/share-token.entity'; +import { BaseFactory } from '@testing/factory/base.factory'; import { DeepPartial } from 'fishery'; +import { nanoid } from 'nanoid'; class ShareTokenFactory extends BaseFactory { withParentTypeCourse(): this { diff --git a/apps/server/src/modules/sharing/uc/share-token.uc.spec.ts b/apps/server/src/modules/sharing/uc/share-token.uc.spec.ts index 5f496c86bfa..fdb1dde6769 100644 --- a/apps/server/src/modules/sharing/uc/share-token.uc.spec.ts +++ b/apps/server/src/modules/sharing/uc/share-token.uc.spec.ts @@ -17,17 +17,15 @@ import { BadRequestException, NotImplementedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { FeatureDisabledLoggableException } from '@shared/common/loggable-exception'; import { Permission } from '@shared/domain/interface'; -import { - courseFactory, - lessonFactory, - schoolEntityFactory, - setupEntities, - shareTokenFactory, - taskFactory, - userFactory, -} from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; import { RoomMembershipService } from '@src/modules/room-membership'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { shareTokenFactory } from '@testing/factory/share-token.do.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ShareTokenContextType, ShareTokenParentType, ShareTokenPayload } from '../domainobject/share-token.do'; import { ShareTokenService } from '../service'; import { ShareTokenUC } from './share-token.uc'; diff --git a/apps/server/src/modules/shd/api/api-tests/shd.api.spec.ts b/apps/server/src/modules/shd/api/api-tests/shd.api.spec.ts index 933038cee96..bfc21817fd1 100644 --- a/apps/server/src/modules/shd/api/api-tests/shd.api.spec.ts +++ b/apps/server/src/modules/shd/api/api-tests/shd.api.spec.ts @@ -4,8 +4,9 @@ import { instanceEntityFactory } from '@modules/instance/testing'; import { ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; import { LoginDto } from '@src/modules/authentication'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { TargetUserIdParams } from '../dtos/target-user-id.params'; const forbiddenResponse = { diff --git a/apps/server/src/modules/synchronization/domain/service/synchonization.service.spec.ts b/apps/server/src/modules/synchronization/domain/service/synchonization.service.spec.ts index 589474203ba..9086c67a486 100644 --- a/apps/server/src/modules/synchronization/domain/service/synchonization.service.spec.ts +++ b/apps/server/src/modules/synchronization/domain/service/synchonization.service.spec.ts @@ -1,11 +1,11 @@ -import { Test, TestingModule } from '@nestjs/testing'; import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { setupEntities } from '@shared/testing'; +import { Test, TestingModule } from '@nestjs/testing'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; -import { SynchronizationService } from './synchronization.service'; import { Synchronization } from '..'; import { SynchronizationRepo } from '../../repo'; import { synchronizationFactory } from '../testing'; +import { SynchronizationService } from './synchronization.service'; describe(SynchronizationService.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/synchronization/domain/testing/factory/synchronization.factory.ts b/apps/server/src/modules/synchronization/domain/testing/factory/synchronization.factory.ts index 4d8c7e1ee91..62827b3eae1 100644 --- a/apps/server/src/modules/synchronization/domain/testing/factory/synchronization.factory.ts +++ b/apps/server/src/modules/synchronization/domain/testing/factory/synchronization.factory.ts @@ -1,5 +1,5 @@ -import { DoBaseFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { DoBaseFactory } from '@testing/factory/domainobject'; import { Synchronization, SynchronizationProps } from '../../do'; import { SynchronizationStatusModel } from '../../types'; diff --git a/apps/server/src/modules/synchronization/repo/entity/synchronization.entity.spec.ts b/apps/server/src/modules/synchronization/repo/entity/synchronization.entity.spec.ts index 250c7cfac1d..1cb1ad6ba0f 100644 --- a/apps/server/src/modules/synchronization/repo/entity/synchronization.entity.spec.ts +++ b/apps/server/src/modules/synchronization/repo/entity/synchronization.entity.spec.ts @@ -1,7 +1,7 @@ -import { setupEntities } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; -import { SynchronizationEntity } from './synchronization.entity'; +import { setupEntities } from '@testing/setup-entities'; import { SynchronizationStatusModel } from '../../domain/types'; +import { SynchronizationEntity } from './synchronization.entity'; describe(SynchronizationEntity.name, () => { beforeAll(async () => { diff --git a/apps/server/src/modules/synchronization/repo/entity/testing/factory/synchronization.entity.factory.ts b/apps/server/src/modules/synchronization/repo/entity/testing/factory/synchronization.entity.factory.ts index 8f006080da5..5fe1e5ec144 100644 --- a/apps/server/src/modules/synchronization/repo/entity/testing/factory/synchronization.entity.factory.ts +++ b/apps/server/src/modules/synchronization/repo/entity/testing/factory/synchronization.entity.factory.ts @@ -1,7 +1,7 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; -import { SynchronizationEntity, SynchronizationEntityProps } from '../../synchronization.entity'; +import { BaseFactory } from '@testing/factory/base.factory'; import { SynchronizationStatusModel } from '../../../../domain/types'; +import { SynchronizationEntity, SynchronizationEntityProps } from '../../synchronization.entity'; export const synchronizationEntityFactory = BaseFactory.define( SynchronizationEntity, diff --git a/apps/server/src/modules/synchronization/repo/synchronization.repo.spec.ts b/apps/server/src/modules/synchronization/repo/synchronization.repo.spec.ts index e864e021a69..39d03250c85 100644 --- a/apps/server/src/modules/synchronization/repo/synchronization.repo.spec.ts +++ b/apps/server/src/modules/synchronization/repo/synchronization.repo.spec.ts @@ -1,15 +1,15 @@ +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test } from '@nestjs/testing'; import { TestingModule } from '@nestjs/testing/testing-module'; -import { MongoMemoryDatabaseModule } from '@infra/database'; -import { cleanupCollections } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { Synchronization } from '../domain'; import { synchronizationFactory } from '../domain/testing'; +import { SynchronizationStatusModel } from '../domain/types'; import { SynchronizationEntity } from './entity'; import { synchronizationEntityFactory } from './entity/testing'; import { SynchronizationMapper } from './mapper'; import { SynchronizationRepo } from './synchronization.repo'; -import { SynchronizationStatusModel } from '../domain/types'; describe(SynchronizationRepo.name, () => { let module: TestingModule; diff --git a/apps/server/src/modules/system/controller/api-test/system.api.spec.ts b/apps/server/src/modules/system/controller/api-test/system.api.spec.ts index 5c91256d518..d0989dd35b7 100644 --- a/apps/server/src/modules/system/controller/api-test/system.api.spec.ts +++ b/apps/server/src/modules/system/controller/api-test/system.api.spec.ts @@ -3,7 +3,10 @@ import { ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; -import { schoolEntityFactory, systemEntityFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { Response } from 'supertest'; import { OauthConfigEntity, SystemEntity } from '../../entity'; import { PublicSystemListResponse, PublicSystemResponse } from '../dto'; diff --git a/apps/server/src/modules/system/entity/system.entity.spec.ts b/apps/server/src/modules/system/entity/system.entity.spec.ts index 83cd4f22d11..9812f4bc503 100644 --- a/apps/server/src/modules/system/entity/system.entity.spec.ts +++ b/apps/server/src/modules/system/entity/system.entity.spec.ts @@ -1,5 +1,6 @@ import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { setupEntities, systemEntityFactory } from '@shared/testing'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { setupEntities } from '@testing/setup-entities'; import { SystemEntity } from './system.entity'; describe('System Entity', () => { diff --git a/apps/server/src/modules/system/repo/mikro-orm/system.repo.spec.ts b/apps/server/src/modules/system/repo/mikro-orm/system.repo.spec.ts index 37eb130ca48..fc822b4fbbd 100644 --- a/apps/server/src/modules/system/repo/mikro-orm/system.repo.spec.ts +++ b/apps/server/src/modules/system/repo/mikro-orm/system.repo.spec.ts @@ -4,7 +4,8 @@ import { NotImplementedException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; import { SystemTypeEnum } from '@shared/domain/types'; -import { cleanupCollections, systemEntityFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; import { System, SYSTEM_REPO, SystemProps, SystemRepo, SystemType } from '../../domain'; import { SystemEntity } from '../../entity'; import { systemLdapConfigFactory, systemOauthConfigFactory, systemOidcConfigFactory } from '../../testing'; diff --git a/apps/server/src/modules/system/testing/system.factory.ts b/apps/server/src/modules/system/testing/system.factory.ts index 19a137ddbb9..a5a481092d2 100644 --- a/apps/server/src/modules/system/testing/system.factory.ts +++ b/apps/server/src/modules/system/testing/system.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { DomainObjectFactory } from '@shared/testing/factory/domainobject/domain-object.factory'; +import { DomainObjectFactory } from '@testing/factory/domainobject'; import { DeepPartial, Factory } from 'fishery'; import { LdapConfig, OauthConfig, OidcConfig, System, SystemProps, SystemType } from '../domain'; diff --git a/apps/server/src/modules/system/uc/system.uc.spec.ts b/apps/server/src/modules/system/uc/system.uc.spec.ts index 7032d3ba06c..79918db3109 100644 --- a/apps/server/src/modules/system/uc/system.uc.spec.ts +++ b/apps/server/src/modules/system/uc/system.uc.spec.ts @@ -5,7 +5,8 @@ import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; import { NotFoundLoggableException } from '@shared/common/loggable-exception'; import { Permission } from '@shared/domain/interface'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SystemDeletedEvent, SystemQuery, SystemType } from '../domain'; import { SystemService } from '../service'; import { systemFactory } from '../testing'; diff --git a/apps/server/src/modules/task/controller/api-test/submission.api.spec.ts b/apps/server/src/modules/task/controller/api-test/submission.api.spec.ts index 4a91e22befc..5fbbe9b0fdb 100644 --- a/apps/server/src/modules/task/controller/api-test/submission.api.spec.ts +++ b/apps/server/src/modules/task/controller/api-test/submission.api.spec.ts @@ -1,86 +1,35 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { FilesStorageClientAdapterService } from '@modules/files-storage-client'; import { ServerTestModule } from '@modules/server/server.module'; import { SubmissionStatusListResponse } from '@modules/task/controller/dto/submission.response'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { ApiValidationError } from '@shared/common'; import { Submission } from '@shared/domain/entity'; -import { Permission } from '@shared/domain/interface'; -import { - cleanupCollections, - courseGroupFactory, - mapUserToCurrentUser, - roleFactory, - submissionFactory, - taskFactory, - userFactory, -} from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; - -class API { - app: INestApplication; - - constructor(app: INestApplication) { - this.app = app; - } - - async findStatusesByTask(taskId: string) { - const response = await request(this.app.getHttpServer()) - .get(`/submissions/status/task/${taskId}`) - .set('Accept', 'application/json') - .set('Authorization', 'jwt'); - - return { - status: response.status, - error: response.body as ApiValidationError, - result: response.body as SubmissionStatusListResponse, - }; - } - - async delete(submissionId: string) { - const response = await request(this.app.getHttpServer()) - .delete(`/submissions/${submissionId}`) - .set('Accept', 'application/json') - .set('Authorization', 'jwt'); - - return { - status: response.status, - error: response.body as ApiValidationError, - result: response.text, - }; - } -} +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; describe('Submission Controller (API)', () => { describe('find statuses by task', () => { let app: INestApplication; - let currentUser: ICurrentUser; - let api: API; let em: EntityManager; + let apiClient: TestApiClient; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - - return true; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); - api = new API(app); em = module.get(EntityManager); + apiClient = new TestApiClient(app, '/submissions'); }); beforeEach(async () => { @@ -95,7 +44,7 @@ describe('Submission Controller (API)', () => { it('should return 401', async () => { const taskId = 'id'; - const { status } = await api.findStatusesByTask(taskId); + const { status } = await apiClient.get(`status/task/${taskId}`); expect(status).toEqual(401); }); @@ -103,25 +52,24 @@ describe('Submission Controller (API)', () => { describe('WHEN user is authenticated and has permission', () => { const setup = async () => { - const roles = roleFactory.buildList(1, { - permissions: [Permission.SUBMISSIONS_VIEW], - }); - const user = userFactory.buildWithId({ roles }); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); const task = taskFactory.buildWithId(); const courseGroup = courseGroupFactory.buildWithId(); - const submission = submissionFactory.buildWithId({ task, student: user, grade: 97, courseGroup }); + const submission = submissionFactory.buildWithId({ task, student: teacherUser, grade: 97, courseGroup }); - await em.persistAndFlush([submission]); + await em.persistAndFlush([submission, teacherAccount, teacherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - return { task, submission }; + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, task, submission }; }; it('should return status', async () => { - const { task, submission } = await setup(); + const { task, submission, loggedInClient } = await setup(); - const { result: statuses } = await api.findStatusesByTask(task.id); + const response = await loggedInClient.get(`status/task/${task.id}`); + const statuses = response.body as SubmissionStatusListResponse; const expectedSubmissionStatuses = { data: [ @@ -141,11 +89,28 @@ describe('Submission Controller (API)', () => { }); describe('with bad request data', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const task = taskFactory.buildWithId(); + const courseGroup = courseGroupFactory.buildWithId(); + const submission = submissionFactory.buildWithId({ task, student: teacherUser, grade: 97, courseGroup }); + + await em.persistAndFlush([submission, teacherAccount, teacherUser]); + em.clear(); + + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, task, submission }; + }; + it('should return status 400 for invalid taskId', async () => { - const response = await api.findStatusesByTask('123'); + const { loggedInClient } = await setup(); + + const response = await loggedInClient.get(`status/task/123`); + const result = response.body as ApiValidationError; expect(response.status).toEqual(400); - expect(response.error.validationErrors).toEqual([ + expect(result.validationErrors).toEqual([ { errors: ['taskId must be a mongodb id'], field: ['taskId'], @@ -157,58 +122,49 @@ describe('Submission Controller (API)', () => { describe('WHEN user is authenticated and has no permission', () => { const setup = async () => { const task = taskFactory.buildWithId(); - const user = userFactory.buildWithId(); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); const submission = submissionFactory.buildWithId({ task }); - await em.persistAndFlush([submission, user]); + await em.persistAndFlush([submission, teacherUser, teacherAccount]); em.clear(); - currentUser = mapUserToCurrentUser(user); - return { task }; + const loggedInClient = await apiClient.login(teacherAccount); + + return { task, loggedInClient }; }; - it('should return 200 and empty array', async () => { - const { task } = await setup(); + it('should return 200', async () => { + const { task, loggedInClient } = await setup(); - const { status, result } = await api.findStatusesByTask(task.id); + const response = await loggedInClient.get(`status/task/${task.id}`); const expectedResult = { data: [] }; - expect(status).toEqual(200); - expect(result).toEqual(expectedResult); + expect(response.status).toEqual(200); + expect(response.body).toEqual(expectedResult); }); }); }); describe('delete submission', () => { let app: INestApplication; - let currentUser: ICurrentUser; - let api: API; let em: EntityManager; let filesStorageClientAdapterService: DeepMocked; + let apiClient: TestApiClient; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - - return true; - }, - }) .overrideProvider(FilesStorageClientAdapterService) .useValue(createMock()) .compile(); app = module.createNestApplication(); await app.init(); - api = new API(app); em = module.get(EntityManager); filesStorageClientAdapterService = app.get(FilesStorageClientAdapterService); + apiClient = new TestApiClient(app, '/submissions'); }); beforeEach(async () => { @@ -223,7 +179,7 @@ describe('Submission Controller (API)', () => { it('should return 401', async () => { const submissionId = 'id'; - const { status } = await api.delete(submissionId); + const { status } = await apiClient.delete(submissionId); expect(status).toEqual(401); }); @@ -231,27 +187,25 @@ describe('Submission Controller (API)', () => { describe('WHEN user is authenticated and has permission', () => { const setup = async () => { - const roles = roleFactory.buildList(1, { - permissions: [Permission.SUBMISSIONS_EDIT], - }); - const user = userFactory.buildWithId({ roles }); + const { studentUser, studentAccount } = UserAndAccountTestFactory.buildStudent(); const task = taskFactory.buildWithId(); - const submission = submissionFactory.buildWithId({ task, student: user, grade: 97 }); + const submission = submissionFactory.buildWithId({ task, student: studentUser, grade: 97 }); - await em.persistAndFlush([submission]); + await em.persistAndFlush([submission, studentUser, studentAccount]); em.clear(); - currentUser = mapUserToCurrentUser(user); - return { submission }; + const loggedInClient = await apiClient.login(studentAccount); + + return { submission, loggedInClient }; }; it('should return status', async () => { - const { submission } = await setup(); + const { submission, loggedInClient } = await setup(); - const { result } = await api.delete(submission.id); + const result = await loggedInClient.delete(submission.id); expect(filesStorageClientAdapterService.deleteFilesOfParent).toBeCalled(); - expect(result).toBe('true'); + expect(result.text).toBe('true'); const expectedSubmissionResult = await em.findOne(Submission, { id: submission.id }); expect(expectedSubmissionResult).toEqual(null); @@ -259,11 +213,26 @@ describe('Submission Controller (API)', () => { }); describe('with bad request data', () => { + const setup = async () => { + const { studentUser, studentAccount } = UserAndAccountTestFactory.buildStudent(); + const task = taskFactory.buildWithId(); + const submission = submissionFactory.buildWithId({ task, student: studentUser, grade: 97 }); + + await em.persistAndFlush([submission, studentUser, studentAccount]); + em.clear(); + + const loggedInClient = await apiClient.login(studentAccount); + + return { submission, loggedInClient }; + }; + it('should return status 400 for invalid taskId', async () => { - const response = await api.delete('123'); + const { loggedInClient } = await setup(); + const response = await loggedInClient.delete('123'); + const result = response.body as ApiValidationError; expect(response.status).toEqual(400); - expect(response.error.validationErrors).toEqual([ + expect(result.validationErrors).toEqual([ { errors: ['submissionId must be a mongodb id'], field: ['submissionId'], @@ -273,22 +242,47 @@ describe('Submission Controller (API)', () => { }); describe('WHEN user is authenticated and has no permission', () => { + const setup = async () => { + const course = courseFactory.buildWithId(); + const task = taskFactory.buildWithId({ course }); + const { studentUser, studentAccount } = UserAndAccountTestFactory.buildStudent(); + const submission = submissionFactory.buildWithId({ task }); + + await em.persistAndFlush([submission, studentUser, studentAccount]); + em.clear(); + + const loggedInClient = await apiClient.login(studentAccount); + + return { submission, loggedInClient }; + }; + + it('should return 403', async () => { + const { submission, loggedInClient } = await setup(); + + const { status } = await loggedInClient.delete(submission.id); + + expect(status).toEqual(403); + }); + }); + + describe('WHEN user is authenticated, has no permission and task has no parent', () => { const setup = async () => { const task = taskFactory.buildWithId(); - const user = userFactory.buildWithId(); + const { studentUser, studentAccount } = UserAndAccountTestFactory.buildStudent(); const submission = submissionFactory.buildWithId({ task }); - await em.persistAndFlush([submission, user]); + await em.persistAndFlush([submission, studentUser, studentAccount]); em.clear(); - currentUser = mapUserToCurrentUser(user); - return { submission }; + const loggedInClient = await apiClient.login(studentAccount); + + return { submission, loggedInClient }; }; it('should return 403', async () => { - const { submission } = await setup(); + const { submission, loggedInClient } = await setup(); - const { status } = await api.delete(submission.id); + const { status } = await loggedInClient.delete(submission.id); expect(status).toEqual(403); }); diff --git a/apps/server/src/modules/task/controller/api-test/task-copy-timeout.api.spec.ts b/apps/server/src/modules/task/controller/api-test/task-copy-timeout.api.spec.ts index 93e91f3d90c..4da7c41f906 100644 --- a/apps/server/src/modules/task/controller/api-test/task-copy-timeout.api.spec.ts +++ b/apps/server/src/modules/task/controller/api-test/task-copy-timeout.api.spec.ts @@ -1,21 +1,15 @@ import { createMock } from '@golevelup/ts-jest'; import { Configuration } from '@hpi-schul-cloud/commons/lib'; import { IConfig } from '@hpi-schul-cloud/commons/lib/interfaces/IConfig'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { FilesStorageClientAdapterService } from '@modules/files-storage-client'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { - cleanupCollections, - courseFactory, - mapUserToCurrentUser, - roleFactory, - taskFactory, - userFactory, -} from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; // config must be set outside before the server module is imported, otherwise the configuration is already set Configuration.set('FEATURE_COPY_SERVICE_ENABLED', true); @@ -29,22 +23,14 @@ import { ServerTestModule } from '@modules/server/server.module'; describe('Task copy (API)', () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; let configBefore: IConfig; + let apiClient: TestApiClient; beforeAll(async () => { configBefore = Configuration.toObject({ plainSecrets: true }); const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) .overrideProvider(FilesStorageClientAdapterService) .useValue(createMock()) .compile(); @@ -52,6 +38,7 @@ describe('Task copy (API)', () => { app = moduleFixture.createNestApplication(); await app.init(); em = app.get(EntityManager); + apiClient = new TestApiClient(app, '/tasks'); }); afterAll(async () => { @@ -60,27 +47,23 @@ describe('Task copy (API)', () => { Configuration.reset(configBefore); }); - const setup = () => { - const roles = roleFactory.buildList(1, { permissions: [] }); - const user = userFactory.build({ roles }); - - return user; - }; - - it('should respond with 408 on timeout', async () => { - const teacher = setup(); - const course = courseFactory.build({ name: 'course #1', teachers: [teacher] }); + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ name: 'course #1', teachers: [teacherUser] }); const task = taskFactory.build({ name: 'task #1', course }); - await em.persistAndFlush([task, course]); + await em.persistAndFlush([task, course, teacherAccount, teacherUser]); em.clear(); - currentUser = mapUserToCurrentUser(teacher); + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, task }; + }; + + it('should respond with 408 on timeout', async () => { + const { loggedInClient, task } = await setup(); - const response = await request(app.getHttpServer()) - .post(`/tasks/${task.id}/copy`) - .set('Authorization', 'jwt') - .send(); + const response = await loggedInClient.post(`${task.id}/copy`); expect(response.status).toEqual(408); }); diff --git a/apps/server/src/modules/task/controller/api-test/task-delete.api.spec.ts b/apps/server/src/modules/task/controller/api-test/task-delete.api.spec.ts index 538ca3a5230..40e97896976 100644 --- a/apps/server/src/modules/task/controller/api-test/task-delete.api.spec.ts +++ b/apps/server/src/modules/task/controller/api-test/task-delete.api.spec.ts @@ -5,13 +5,11 @@ import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - courseFactory, - taskFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; const createStudent = () => { const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent({}, [ diff --git a/apps/server/src/modules/task/controller/api-test/task-finish.api.spec.ts b/apps/server/src/modules/task/controller/api-test/task-finish.api.spec.ts index 1ca1727f21d..84e3c83dc01 100644 --- a/apps/server/src/modules/task/controller/api-test/task-finish.api.spec.ts +++ b/apps/server/src/modules/task/controller/api-test/task-finish.api.spec.ts @@ -3,13 +3,11 @@ import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - courseFactory, - taskFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; const createStudent = () => { const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent({}, [ diff --git a/apps/server/src/modules/task/controller/api-test/task-finished.api.spec.ts b/apps/server/src/modules/task/controller/api-test/task-finished.api.spec.ts index e58673aad5e..850448a7348 100644 --- a/apps/server/src/modules/task/controller/api-test/task-finished.api.spec.ts +++ b/apps/server/src/modules/task/controller/api-test/task-finished.api.spec.ts @@ -1,69 +1,29 @@ -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; import { ServerTestModule } from '@modules/server/server.module'; -import { TaskListResponse } from '@modules/task/controller/dto'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { Permission } from '@shared/domain/interface'; -import { - cleanupCollections, - courseFactory, - lessonFactory, - mapUserToCurrentUser, - roleFactory, - taskFactory, - userFactory, -} from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; - -class API { - app: INestApplication; - - routeName: string; - - constructor(app: INestApplication, routeName: string) { - this.app = app; - this.routeName = routeName; - } - - async get(query?: string | Record) { - const response = await request(this.app.getHttpServer()) - .get(this.routeName) - .set('Accept', 'application/json') - .query(query || {}); - - return { - result: response.body as TaskListResponse, - status: response.status, - }; - } -} +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import { TaskListResponse } from '../dto/task.response'; describe('Task controller (API)', () => { let app: INestApplication; let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; + let apiClient: TestApiClient; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); em = module.get(EntityManager); - api = new API(app, '/tasks/finished'); + apiClient = new TestApiClient(app, '/tasks/finished'); }); afterAll(async () => { @@ -76,73 +36,64 @@ describe('Task controller (API)', () => { }); it('should return status 401', async () => { - const roles = roleFactory.buildList(1, { permissions: [] }); - const user = userFactory.build({ roles }); - const task = taskFactory.finished(user).build({ creator: user }); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const task = taskFactory.finished(teacherUser).build({ creator: teacherUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, teacherAccount, teacherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - - const response = await api.get(); + const response = await apiClient.get(); expect(response.status).toEqual(401); }); }); - describe(`task/finished with ${Permission.TASK_DASHBOARD_TEACHER_VIEW_V3} permission`, () => { + describe('task/finished as a teacher', () => { beforeEach(async () => { await cleanupCollections(em); }); - const setup = () => { - const roles = roleFactory.buildList(1, { - permissions: [Permission.TASK_DASHBOARD_TEACHER_VIEW_V3], - }); - const user = userFactory.build({ roles }); - - return user; - }; - it('should "not" find task if the user is not part of the parent anymore.', async () => { - const user = setup(); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); const course = courseFactory.build({ teachers: [] }); - const task = taskFactory.finished(user).build({ course }); + const task = taskFactory.finished(teacherUser).build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, teacherAccount, teacherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(teacherAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished tasks of user', async () => { - const user = setup(); - const course = courseFactory.build({ teachers: [user] }); - const task = taskFactory.finished(user).build({ course }); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ teachers: [teacherUser] }); + const task = taskFactory.finished(teacherUser).build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, teacherAccount, teacherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(teacherAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return status for privileged members if user has write permission in for tasks', async () => { - const user = setup(); - const course = courseFactory.build({ substitutionTeachers: [user] }); - const task = taskFactory.finished(user).build({ course }); + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); + const course = courseFactory.build({ substitutionTeachers: [teacherUser] }); + const task = taskFactory.finished(teacherUser).build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, teacherAccount, teacherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(teacherAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.data).toHaveLength(1); // can only be true for privileged status @@ -150,41 +101,38 @@ describe('Task controller (API)', () => { }); }); - describe(`task/finished with ${Permission.TASK_DASHBOARD_VIEW_V3} permission`, () => { + describe('task/finished as a student', () => { beforeEach(async () => { await cleanupCollections(em); }); describe('api endpoint', () => { - const setup = () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.TASK_DASHBOARD_VIEW_V3] }); - const user = userFactory.build({ roles }); + const setup = async () => { + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + + await em.persistAndFlush([studentAccount, studentUser]); + em.clear(); + + const loggedInClient = await apiClient.login(studentAccount); - return user; + return { loggedInClient }; }; it('should possible to open it', async () => { - const user = setup(); + const { loggedInClient } = await setup(); - await em.persistAndFlush([user]); - em.clear(); - - currentUser = mapUserToCurrentUser(user); - const response = await api.get(); + const response = await loggedInClient.get(); expect(response.status).toEqual(200); }); it('should return a paginated result', async () => { - const user = setup(); - - await em.persistAndFlush([user]); - em.clear(); + const { loggedInClient } = await setup(); - currentUser = mapUserToCurrentUser(user); - const response = await api.get(); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; - expect(response.result).toEqual({ + expect(result).toEqual({ total: 0, data: [], limit: 10, @@ -194,48 +142,44 @@ describe('Task controller (API)', () => { }); describe('when user is the creator', () => { - const setup = () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.TASK_DASHBOARD_VIEW_V3] }); - const user = userFactory.build({ roles }); - - return user; - }; - it('should return finished tasks', async () => { - const user = setup(); - const task = taskFactory.finished(user).build({ creator: user }); + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const task = taskFactory.finished(studentUser).build({ creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return finished draft tasks', async () => { - const user = setup(); - const task = taskFactory.finished(user).draft().build({ creator: user }); + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const task = taskFactory.finished(studentUser).draft().build({ creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should "not" return open tasks', async () => { - const user = setup(); - const task = taskFactory.build({ creator: user }); + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const task = taskFactory.build({ creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); @@ -244,133 +188,139 @@ describe('Task controller (API)', () => { describe('when user has write permission in course', () => { describe('when courses are finised', () => { const setup = () => { - const roles = roleFactory.buildList(1, { - permissions: [Permission.TASK_DASHBOARD_VIEW_V3], - }); - const user = userFactory.build({ roles }); - const course = courseFactory.isFinished().build({ teachers: [user] }); + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const course = courseFactory.isFinished().build({ teachers: [studentUser] }); - return { course, user }; + return { course, studentAccount, studentUser }; }; it('should return tasks of courses', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const task = taskFactory.build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return tasks of visible lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: false }); const task = taskFactory.build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return finished tasks of visible lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: false }); - const task = taskFactory.finished(user).build({ course, lesson }); + const task = taskFactory.finished(studentUser).build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return tasks of hidden lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: true }); const task = taskFactory.build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return finished tasks of hidden lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: true }); - const task = taskFactory.finished(user).build({ course, lesson }); + const task = taskFactory.finished(studentUser).build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return open draft tasks of user', async () => { - const { user, course } = setup(); - const task = taskFactory.draft().build({ course, creator: user }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.draft().build({ course, creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return finished draft tasks of user', async () => { - const { user, course } = setup(); - const task = taskFactory.draft().finished(user).build({ course, creator: user }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.draft().finished(studentUser).build({ course, creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should "not" return finished draft tasks of the other user', async () => { - const { user, course } = setup(); - const otherUser = userFactory.build(); - const task = taskFactory.draft().finished(user).build({ course, creator: otherUser }); + const { course, studentAccount, studentUser } = setup(); + const { studentAccount: otherAccount, studentUser: otherUser } = UserAndAccountTestFactory.buildStudent(); + const task = taskFactory.draft().finished(studentUser).build({ course, creator: otherUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser, otherAccount, otherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished tasks', async () => { - const { user, course } = setup(); - const task = taskFactory.finished(user).build({ course }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.finished(studentUser).build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); @@ -378,133 +328,139 @@ describe('Task controller (API)', () => { describe('when courses are open', () => { const setup = () => { - const roles = roleFactory.buildList(1, { - permissions: [Permission.TASK_DASHBOARD_VIEW_V3], - }); - const user = userFactory.build({ roles }); - const course = courseFactory.isOpen().build({ teachers: [user] }); + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const course = courseFactory.isOpen().build({ teachers: [studentUser] }); - return { course, user }; + return { course, studentAccount, studentUser }; }; it('should "not" return tasks of courses', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const task = taskFactory.build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should "not" return tasks of visible lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: false }); const task = taskFactory.build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished tasks of visible lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: false }); - const task = taskFactory.finished(user).build({ course, lesson }); + const task = taskFactory.finished(studentUser).build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should "not" return tasks of hidden lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: true }); const task = taskFactory.build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished tasks of hidden lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: true }); - const task = taskFactory.finished(user).build({ course, lesson }); + const task = taskFactory.finished(studentUser).build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should "not" return draft tasks of user', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const task = taskFactory.draft().build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished draft tasks of user', async () => { - const { user, course } = setup(); - const task = taskFactory.draft().finished(user).build({ course, creator: user }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.draft().finished(studentUser).build({ course, creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should "not" return finished draft tasks of the other user', async () => { - const { user, course } = setup(); - const otherUser = userFactory.build(); - const task = taskFactory.draft().finished(user).build({ course, creator: otherUser }); + const { course, studentAccount, studentUser } = setup(); + const { studentAccount: otherAccount, studentUser: otherUser } = UserAndAccountTestFactory.buildStudent(); + const task = taskFactory.draft().finished(studentUser).build({ course, creator: otherUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser, otherAccount, otherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished tasks', async () => { - const { user, course } = setup(); - const task = taskFactory.finished(user).build({ course }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.finished(studentUser).build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); @@ -514,131 +470,139 @@ describe('Task controller (API)', () => { describe('when user has read permission in course', () => { describe('when courses are finised', () => { const setup = () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.TASK_DASHBOARD_VIEW_V3] }); - const user = userFactory.build({ roles }); - const course = courseFactory.isFinished().build({ students: [user] }); + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const course = courseFactory.isFinished().build({ students: [studentUser] }); - return { course, user }; + return { course, studentAccount, studentUser }; }; it('should return tasks of courses', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const task = taskFactory.build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return tasks of visible lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: false }); const task = taskFactory.build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return finished tasks of visible lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: false }); - const task = taskFactory.finished(user).build({ course, lesson }); + const task = taskFactory.finished(studentUser).build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should "not" return tasks of hidden lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: true }); const task = taskFactory.build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should "not" return finished tasks of hidden lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: true }); - const task = taskFactory.finished(user).build({ course, lesson }); + const task = taskFactory.finished(studentUser).build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return open draft tasks of user', async () => { - const { user, course } = setup(); - const task = taskFactory.draft().build({ course, creator: user }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.draft().build({ course, creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should return finished draft tasks of user', async () => { - const { user, course } = setup(); - const task = taskFactory.draft().finished(user).build({ course, creator: user }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.draft().finished(studentUser).build({ course, creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should "not" return finished draft tasks of the other user', async () => { - const { user, course } = setup(); - const otherUser = userFactory.build(); - const task = taskFactory.draft().finished(user).build({ course, creator: otherUser }); + const { course, studentAccount, studentUser } = setup(); + const { studentAccount: otherAccount, studentUser: otherUser } = UserAndAccountTestFactory.buildStudent(); + const task = taskFactory.draft().finished(studentUser).build({ course, creator: otherUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser, otherAccount, otherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished tasks', async () => { - const { user, course } = setup(); - const task = taskFactory.finished(user).build({ course }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.finished(studentUser).build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); @@ -646,131 +610,139 @@ describe('Task controller (API)', () => { describe('when courses are open', () => { const setup = () => { - const roles = roleFactory.buildList(1, { permissions: [Permission.TASK_DASHBOARD_VIEW_V3] }); - const user = userFactory.build({ roles }); - const course = courseFactory.isOpen().build({ students: [user] }); + const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent(); + const course = courseFactory.isOpen().build({ students: [studentUser] }); - return { course, user }; + return { course, studentAccount, studentUser }; }; it('should "not" return tasks of courses', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const task = taskFactory.build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should "not" return tasks of visible lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: false }); const task = taskFactory.build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished tasks of visible lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: false }); - const task = taskFactory.finished(user).build({ course, lesson }); + const task = taskFactory.finished(studentUser).build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should "not" return tasks of hidden lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: true }); const task = taskFactory.build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should "not" return finished tasks of hidden lessons', async () => { - const { user, course } = setup(); + const { course, studentAccount, studentUser } = setup(); const lesson = lessonFactory.build({ course, hidden: true }); - const task = taskFactory.finished(user).build({ course, lesson }); + const task = taskFactory.finished(studentUser).build({ course, lesson }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should "not" return draft tasks of the user', async () => { - const { user, course } = setup(); - const task = taskFactory.draft().build({ course, creator: user }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.draft().build({ course, creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished draft tasks of the user', async () => { - const { user, course } = setup(); - const task = taskFactory.draft().finished(user).build({ course, creator: user }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.draft().finished(studentUser).build({ course, creator: studentUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); it('should "not" return finished draft tasks of the other user', async () => { - const { user, course } = setup(); - const otherUser = userFactory.build(); - const task = taskFactory.draft().finished(user).build({ course, creator: otherUser }); + const { course, studentAccount, studentUser } = setup(); + const { studentAccount: otherAccount, studentUser: otherUser } = UserAndAccountTestFactory.buildStudent(); + const task = taskFactory.draft().finished(studentUser).build({ course, creator: otherUser }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser, otherAccount, otherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(0); }); it('should return finished tasks', async () => { - const { user, course } = setup(); - const task = taskFactory.finished(user).build({ course }); + const { course, studentAccount, studentUser } = setup(); + const task = taskFactory.finished(studentUser).build({ course }); - await em.persistAndFlush([task]); + await em.persistAndFlush([task, studentAccount, studentUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - const { result } = await api.get(); + const loggedInClient = await apiClient.login(studentAccount); + const response = await loggedInClient.get(); + const result = response.body as TaskListResponse; expect(result.total).toEqual(1); }); diff --git a/apps/server/src/modules/task/controller/api-test/task-restore.api.spec.ts b/apps/server/src/modules/task/controller/api-test/task-restore.api.spec.ts index 7a61ac1ae17..971e1af8c33 100644 --- a/apps/server/src/modules/task/controller/api-test/task-restore.api.spec.ts +++ b/apps/server/src/modules/task/controller/api-test/task-restore.api.spec.ts @@ -3,13 +3,11 @@ import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - courseFactory, - taskFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; const createStudent = () => { const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent({}, [ diff --git a/apps/server/src/modules/task/controller/api-test/task-revert-published.api.spec.ts b/apps/server/src/modules/task/controller/api-test/task-revert-published.api.spec.ts index a958a1f0759..a1b5e243947 100644 --- a/apps/server/src/modules/task/controller/api-test/task-revert-published.api.spec.ts +++ b/apps/server/src/modules/task/controller/api-test/task-revert-published.api.spec.ts @@ -3,13 +3,11 @@ import { ServerTestModule } from '@modules/server'; import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - courseFactory, - taskFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; const createStudent = () => { const { studentAccount, studentUser } = UserAndAccountTestFactory.buildStudent({}, [ diff --git a/apps/server/src/modules/task/controller/api-test/task.api.spec.ts b/apps/server/src/modules/task/controller/api-test/task.api.spec.ts index 566b3840ab0..a156f8073c4 100644 --- a/apps/server/src/modules/task/controller/api-test/task.api.spec.ts +++ b/apps/server/src/modules/task/controller/api-test/task.api.spec.ts @@ -5,14 +5,12 @@ import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; import { InputFormat } from '@shared/domain/types'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - courseFactory, - submissionFactory, - taskFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; const tomorrow = new Date(Date.now() + 86400000); diff --git a/apps/server/src/modules/task/controller/task.controller.spec.ts b/apps/server/src/modules/task/controller/task.controller.spec.ts index a98f2ae42f0..14a9ad526cd 100644 --- a/apps/server/src/modules/task/controller/task.controller.spec.ts +++ b/apps/server/src/modules/task/controller/task.controller.spec.ts @@ -2,7 +2,7 @@ import { createMock } from '@golevelup/ts-jest'; import { CopyElementType, CopyStatus, CopyStatusEnum } from '@modules/copy-helper'; import { CopyApiResponse } from '@modules/copy-helper/dto/copy.response'; import { Test, TestingModule } from '@nestjs/testing'; -import { currentUserFactory } from '@shared/testing'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; import { TaskCopyUC, TaskUC } from '../uc'; import { TaskController } from './task.controller'; diff --git a/apps/server/src/modules/task/mapper/submission.mapper.spec.ts b/apps/server/src/modules/task/mapper/submission.mapper.spec.ts index fda04359c6c..4098b001d4f 100644 --- a/apps/server/src/modules/task/mapper/submission.mapper.spec.ts +++ b/apps/server/src/modules/task/mapper/submission.mapper.spec.ts @@ -1,4 +1,5 @@ -import { setupEntities, submissionFactory } from '@shared/testing'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SubmissionStatusResponse } from '../controller/dto'; import { SubmissionMapper } from './submission.mapper'; diff --git a/apps/server/src/modules/task/mapper/task.mapper.spec.ts b/apps/server/src/modules/task/mapper/task.mapper.spec.ts index fe67dcaaaca..44ee785f0a3 100644 --- a/apps/server/src/modules/task/mapper/task.mapper.spec.ts +++ b/apps/server/src/modules/task/mapper/task.mapper.spec.ts @@ -1,7 +1,8 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { Task, TaskParentDescriptions } from '@shared/domain/entity'; import { InputFormat, TaskStatus, TaskUpdate } from '@shared/domain/types'; -import { setupEntities, taskFactory } from '@shared/testing'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; import { TaskCreateParams, TaskResponse, TaskStatusResponse, TaskUpdateParams } from '../controller/dto'; import { TaskMapper } from './task.mapper'; diff --git a/apps/server/src/modules/task/service/submission.service.spec.ts b/apps/server/src/modules/task/service/submission.service.spec.ts index 1c7345a7aea..8ff865617b3 100644 --- a/apps/server/src/modules/task/service/submission.service.spec.ts +++ b/apps/server/src/modules/task/service/submission.service.spec.ts @@ -15,8 +15,11 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Submission } from '@shared/domain/entity'; import { Counted } from '@shared/domain/types'; import { SubmissionRepo } from '@shared/repo'; -import { setupEntities, submissionFactory, taskFactory, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { SubmissionService } from './submission.service'; diff --git a/apps/server/src/modules/task/service/task-copy.service.spec.ts b/apps/server/src/modules/task/service/task-copy.service.spec.ts index 4c77b83b1a7..f45e4358989 100644 --- a/apps/server/src/modules/task/service/task-copy.service.spec.ts +++ b/apps/server/src/modules/task/service/task-copy.service.spec.ts @@ -4,15 +4,13 @@ import { CopyFilesService } from '@modules/files-storage-client'; import { Test, TestingModule } from '@nestjs/testing'; import { Task } from '@shared/domain/entity'; import { TaskRepo } from '@shared/repo'; -import { - courseFactory, - legacyFileEntityMockFactory, - lessonFactory, - schoolEntityFactory, - setupEntities, - taskFactory, - userFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { legacyFileEntityMockFactory } from '@testing/factory/legacy-file-entity-mock.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { TaskCopyService } from './task-copy.service'; describe('task copy service', () => { diff --git a/apps/server/src/modules/task/service/task.service.spec.ts b/apps/server/src/modules/task/service/task.service.spec.ts index bda80e68e54..fa9b86009ff 100644 --- a/apps/server/src/modules/task/service/task.service.spec.ts +++ b/apps/server/src/modules/task/service/task.service.spec.ts @@ -12,8 +12,12 @@ import { FilesStorageClientAdapterService } from '@modules/files-storage-client' import { EventBus } from '@nestjs/cqrs'; import { Test, TestingModule } from '@nestjs/testing'; import { TaskRepo } from '@shared/repo'; -import { courseFactory, setupEntities, submissionFactory, taskFactory, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { courseFactory } from '@testing/factory/course.factory'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { SubmissionService } from './submission.service'; import { TaskService } from './task.service'; diff --git a/apps/server/src/modules/task/uc/submission.uc.spec.ts b/apps/server/src/modules/task/uc/submission.uc.spec.ts index 688ff682ab9..41761cda3ad 100644 --- a/apps/server/src/modules/task/uc/submission.uc.spec.ts +++ b/apps/server/src/modules/task/uc/submission.uc.spec.ts @@ -4,7 +4,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Submission } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; import { Counted } from '@shared/domain/types'; -import { setupEntities, submissionFactory, taskFactory, userFactory } from '@shared/testing'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SubmissionService } from '../service/submission.service'; import { SubmissionUc } from './submission.uc'; diff --git a/apps/server/src/modules/task/uc/task-copy.uc.spec.ts b/apps/server/src/modules/task/uc/task-copy.uc.spec.ts index 182294cfd91..2612e70a5fa 100644 --- a/apps/server/src/modules/task/uc/task-copy.uc.spec.ts +++ b/apps/server/src/modules/task/uc/task-copy.uc.spec.ts @@ -8,7 +8,11 @@ import { LessonService } from '@modules/lesson'; import { ForbiddenException, InternalServerErrorException, NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { CourseRepo, TaskRepo, UserRepo } from '@shared/repo'; -import { courseFactory, lessonFactory, setupEntities, taskFactory, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { TaskCopyService } from '../service'; import { TaskCopyParentParams } from '../types'; import { TaskCopyUC } from './task-copy.uc'; diff --git a/apps/server/src/modules/task/uc/task.uc.spec.ts b/apps/server/src/modules/task/uc/task.uc.spec.ts index f580f66eaaf..28f8763b633 100644 --- a/apps/server/src/modules/task/uc/task.uc.spec.ts +++ b/apps/server/src/modules/task/uc/task.uc.spec.ts @@ -8,15 +8,13 @@ import { PaginationParams } from '@shared/controller'; import { Permission, SortOrder } from '@shared/domain/interface'; import { TaskStatus } from '@shared/domain/types'; import { CourseRepo, TaskRepo } from '@shared/repo'; -import { - courseFactory, - lessonFactory, - roleFactory, - setupEntities, - submissionFactory, - taskFactory, - userFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { TaskService } from '../service'; import { TaskUC } from './task.uc'; diff --git a/apps/server/src/modules/teams/service/team-authorisable.service.spec.ts b/apps/server/src/modules/teams/service/team-authorisable.service.spec.ts index 1c6f8923a41..f76f60302dc 100644 --- a/apps/server/src/modules/teams/service/team-authorisable.service.spec.ts +++ b/apps/server/src/modules/teams/service/team-authorisable.service.spec.ts @@ -2,7 +2,8 @@ import { DeepMocked, createMock } from '@golevelup/ts-jest'; import { AuthorizableReferenceType, AuthorizationInjectionService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; import { TeamsRepo } from '@shared/repo'; -import { setupEntities, teamFactory } from '@shared/testing'; +import { teamFactory } from '@testing/factory/team.factory'; +import { setupEntities } from '@testing/setup-entities'; import { TeamAuthorisableService } from './team-authorisable.service'; describe('team authorisable service', () => { diff --git a/apps/server/src/modules/teams/service/team.service.spec.ts b/apps/server/src/modules/teams/service/team.service.spec.ts index 30502a0822c..8e42d963daa 100644 --- a/apps/server/src/modules/teams/service/team.service.spec.ts +++ b/apps/server/src/modules/teams/service/team.service.spec.ts @@ -11,8 +11,10 @@ import { deletionRequestFactory } from '@modules/deletion/domain/testing'; import { EventBus } from '@nestjs/cqrs/dist'; import { Test, TestingModule } from '@nestjs/testing'; import { TeamsRepo } from '@shared/repo'; -import { setupEntities, teamFactory, teamUserFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { teamFactory } from '@testing/factory/team.factory'; +import { teamUserFactory } from '@testing/factory/teamuser.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { TeamService } from './team.service'; diff --git a/apps/server/src/modules/tool/common/uc/tool-permission-helper.spec.ts b/apps/server/src/modules/tool/common/uc/tool-permission-helper.spec.ts index fcd2ae12244..66d214344f3 100644 --- a/apps/server/src/modules/tool/common/uc/tool-permission-helper.spec.ts +++ b/apps/server/src/modules/tool/common/uc/tool-permission-helper.spec.ts @@ -7,13 +7,15 @@ import { AuthorizationService, ForbiddenLoggableException, } from '@modules/authorization'; -import { BoardNodeAuthorizableService, BoardNodeAuthorizable, BoardNodeService } from '@modules/board'; +import { BoardNodeAuthorizable, BoardNodeAuthorizableService, BoardNodeService } from '@modules/board'; import { CourseService } from '@modules/learnroom'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { courseFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { boardNodeAuthorizableFactory, externalToolElementFactory } from '@modules/board/testing'; import { ContextExternalTool, ContextRef } from '../../context-external-tool/domain'; diff --git a/apps/server/src/modules/tool/context-external-tool/authorisation/context-external-tool.rule.spec.ts b/apps/server/src/modules/tool/context-external-tool/authorisation/context-external-tool.rule.spec.ts index 01b7b97140e..e8159af7a3b 100644 --- a/apps/server/src/modules/tool/context-external-tool/authorisation/context-external-tool.rule.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/authorisation/context-external-tool.rule.spec.ts @@ -9,7 +9,10 @@ import { schoolExternalToolEntityFactory } from '@modules/tool/school-external-t import { Test, TestingModule } from '@nestjs/testing'; import { Role, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { roleFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ContextExternalToolRule } from './context-external-tool.rule'; describe('ContextExternalToolRule', () => { diff --git a/apps/server/src/modules/tool/context-external-tool/controller/api-test/admin-api-context-external-tool.api.spec.ts b/apps/server/src/modules/tool/context-external-tool/controller/api-test/admin-api-context-external-tool.api.spec.ts index 3ce153ea042..d8ae52e0f58 100644 --- a/apps/server/src/modules/tool/context-external-tool/controller/api-test/admin-api-context-external-tool.api.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/controller/api-test/admin-api-context-external-tool.api.spec.ts @@ -3,9 +3,11 @@ import { AdminApiServerTestModule } from '@modules/server/admin-api.server.modul import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Course, SchoolEntity } from '@shared/domain/entity'; -import { courseFactory, schoolEntityFactory, TestApiClient } from '@shared/testing'; // admin-api-context-external-tool and test file is wrong placed need to be part of a admin-api-module folder import { adminApiServerConfig } from '@modules/server/admin-api-server.config'; +import { courseFactory } from '@testing/factory/course.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { ToolContextType } from '../../../common/enum'; import { ExternalToolResponse } from '../../../external-tool/controller/dto'; import { CustomParameterScope, CustomParameterType, ExternalToolEntity } from '../../../external-tool/entity'; diff --git a/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-context.api.spec.ts b/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-context.api.spec.ts index 0af81812244..4f512234a06 100644 --- a/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-context.api.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-context.api.spec.ts @@ -5,16 +5,14 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Course, SchoolEntity, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { - TestApiClient, - UserAndAccountTestFactory, - courseFactory, - roleFactory, - schoolEntityFactory, - userFactory, -} from '@shared/testing'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { accountFactory } from '@src/modules/account/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { CustomParameterScope, CustomParameterType, ToolContextType } from '../../../common/enum'; import { ExternalToolEntity } from '../../../external-tool/entity'; import { customParameterEntityFactory, externalToolEntityFactory } from '../../../external-tool/testing'; diff --git a/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-deep-link.api.spec.ts b/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-deep-link.api.spec.ts index bb71215cf33..8ddb6df03a2 100644 --- a/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-deep-link.api.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-deep-link.api.spec.ts @@ -3,7 +3,9 @@ import { EntityManager, MikroORM } from '@mikro-orm/core'; import { ServerTestModule } from '@modules/server'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { courseFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import crypto from 'crypto-js'; import { externalToolEntityFactory, lti11ToolConfigEntityFactory } from '../../../external-tool/testing'; import { schoolExternalToolEntityFactory } from '../../../school-external-tool/testing'; diff --git a/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-reference.api.spec.ts b/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-reference.api.spec.ts index 180fcab6715..8d167e8e871 100644 --- a/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-reference.api.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/controller/api-test/tool-reference.api.spec.ts @@ -4,15 +4,13 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Course, SchoolEntity } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { - cleanupCollections, - courseFactory, - DateToString, - fileRecordFactory, - schoolEntityFactory, - TestApiClient, - UserAndAccountTestFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { DateToString } from '@testing/date-to-string'; +import { courseFactory } from '@testing/factory/course.factory'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { Response } from 'supertest'; import { CustomParameterLocation, CustomParameterScope, LtiMessageType, ToolContextType } from '../../../common/enum'; import { ExternalToolEntity } from '../../../external-tool/entity'; diff --git a/apps/server/src/modules/tool/context-external-tool/entity/context-external-tool.entity.spec.ts b/apps/server/src/modules/tool/context-external-tool/entity/context-external-tool.entity.spec.ts index 7ffec395d88..e630e9ba934 100644 --- a/apps/server/src/modules/tool/context-external-tool/entity/context-external-tool.entity.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/entity/context-external-tool.entity.spec.ts @@ -1,11 +1,14 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { schoolEntityFactory, setupEntities } from '@shared/testing'; - -import { CustomParameterLocation, CustomParameterScope, CustomParameterType, ToolConfigType } from '../../common/enum'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { setupEntities } from '@testing/setup-entities'; +import { ToolConfigType } from '../../common/enum'; import { BasicToolConfigEntity, CustomParameterEntity, + CustomParameterLocation, + CustomParameterScope, + CustomParameterType, ExternalToolConfigEntity, ExternalToolEntity, } from '../../external-tool/entity'; diff --git a/apps/server/src/modules/tool/context-external-tool/repo/mikro-orm/lti-deep-link-token.repo.spec.ts b/apps/server/src/modules/tool/context-external-tool/repo/mikro-orm/lti-deep-link-token.repo.spec.ts index 7bef843ce8b..bdc315413c9 100644 --- a/apps/server/src/modules/tool/context-external-tool/repo/mikro-orm/lti-deep-link-token.repo.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/repo/mikro-orm/lti-deep-link-token.repo.spec.ts @@ -1,7 +1,7 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { cleanupCollections } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { LtiDeepLinkToken } from '../../domain'; import { LtiDeepLinkTokenEntity } from '../../entity'; import { ltiDeepLinkTokenEntityFactory, ltiDeepLinkTokenFactory } from '../../testing'; diff --git a/apps/server/src/modules/tool/context-external-tool/service/context-external-tool-authorizable.service.spec.ts b/apps/server/src/modules/tool/context-external-tool/service/context-external-tool-authorizable.service.spec.ts index 72170d073da..204676bce6d 100644 --- a/apps/server/src/modules/tool/context-external-tool/service/context-external-tool-authorizable.service.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/service/context-external-tool-authorizable.service.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { AuthorizableReferenceType, AuthorizationInjectionService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; import { ContextExternalToolRepo } from '@shared/repo'; -import { legacySchoolDoFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; import { SchoolExternalTool } from '../../school-external-tool/domain'; import { schoolExternalToolFactory } from '../../school-external-tool/testing'; import { ContextExternalTool } from '../domain'; diff --git a/apps/server/src/modules/tool/context-external-tool/service/context-external-tool.service.spec.ts b/apps/server/src/modules/tool/context-external-tool/service/context-external-tool.service.spec.ts index e799941da49..47de4faad84 100644 --- a/apps/server/src/modules/tool/context-external-tool/service/context-external-tool.service.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/service/context-external-tool.service.spec.ts @@ -1,13 +1,13 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ObjectId } from '@mikro-orm/mongodb'; import { AuthorizationContext, AuthorizationContextBuilder, AuthorizationService } from '@modules/authorization'; +import { School } from '@modules/school'; +import { schoolFactory } from '@modules/school/testing'; import { NotFoundException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; import { ContextExternalToolRepo } from '@shared/repo'; -import { legacySchoolDoFactory } from '@shared/testing'; -import { School } from '@modules/school'; -import { schoolFactory } from '@modules/school/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; import { CustomParameter } from '../../common/domain'; import { ToolContextType } from '../../common/enum'; import { CommonToolDeleteService, CommonToolService } from '../../common/service'; diff --git a/apps/server/src/modules/tool/context-external-tool/testing/context-external-tool-entity.factory.ts b/apps/server/src/modules/tool/context-external-tool/testing/context-external-tool-entity.factory.ts index ffaa41ab061..07beb387dbe 100644 --- a/apps/server/src/modules/tool/context-external-tool/testing/context-external-tool-entity.factory.ts +++ b/apps/server/src/modules/tool/context-external-tool/testing/context-external-tool-entity.factory.ts @@ -5,8 +5,8 @@ import { ContextExternalToolType, } from '@modules/tool/context-external-tool/entity'; import { schoolExternalToolEntityFactory } from '@modules/tool/school-external-tool/testing/school-external-tool-entity.factory'; -import { BaseFactory } from '@shared/testing/factory/base.factory'; -import { courseFactory } from '@shared/testing/factory/course.factory'; +import { BaseFactory } from '@testing/factory/base.factory'; +import { courseFactory } from '@testing/factory/course.factory'; export const contextExternalToolEntityFactory = BaseFactory.define< ContextExternalToolEntity, diff --git a/apps/server/src/modules/tool/context-external-tool/testing/context-external-tool.factory.ts b/apps/server/src/modules/tool/context-external-tool/testing/context-external-tool.factory.ts index 9d6140829cc..0ec7c83335f 100644 --- a/apps/server/src/modules/tool/context-external-tool/testing/context-external-tool.factory.ts +++ b/apps/server/src/modules/tool/context-external-tool/testing/context-external-tool.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { DoBaseFactory } from '@shared/testing/factory/domainobject/do-base.factory'; +import { DoBaseFactory } from '@testing/factory/domainobject'; import { DeepPartial } from 'fishery'; import { CustomParameterEntry } from '../../common/domain'; import { ToolContextType } from '../../common/enum'; diff --git a/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-embeddable.factory.ts b/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-embeddable.factory.ts index cdffaa33480..3a00125bdf5 100644 --- a/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-embeddable.factory.ts +++ b/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-embeddable.factory.ts @@ -1,4 +1,4 @@ -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { CustomParameterEntry } from '../../common/domain'; import { LtiDeepLinkEmbeddable } from '../entity'; diff --git a/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-token-entity.factory.ts b/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-token-entity.factory.ts index 2261d29ca68..a619392665d 100644 --- a/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-token-entity.factory.ts +++ b/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-token-entity.factory.ts @@ -1,5 +1,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory, userFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { UUID } from 'bson'; import { LtiDeepLinkTokenEntity, LtiDeepLinkTokenEntityProps } from '../entity'; diff --git a/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-token.factory.ts b/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-token.factory.ts index 8df64cfc115..3eb15c7c139 100644 --- a/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-token.factory.ts +++ b/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link-token.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { UUID } from 'bson'; import { LtiDeepLinkToken, LtiDeepLinkTokenProps } from '../domain'; diff --git a/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link.factory.ts b/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link.factory.ts index ddaa5216702..cf91e9b0d66 100644 --- a/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link.factory.ts +++ b/apps/server/src/modules/tool/context-external-tool/testing/lti-deep-link.factory.ts @@ -1,4 +1,4 @@ -import { BaseFactory } from '@shared/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { CustomParameterEntry } from '../../common/domain'; import { LtiDeepLink } from '../domain'; diff --git a/apps/server/src/modules/tool/context-external-tool/uc/context-external-tool.uc.spec.ts b/apps/server/src/modules/tool/context-external-tool/uc/context-external-tool.uc.spec.ts index 1d2275ef17c..76d987e2fa7 100644 --- a/apps/server/src/modules/tool/context-external-tool/uc/context-external-tool.uc.spec.ts +++ b/apps/server/src/modules/tool/context-external-tool/uc/context-external-tool.uc.spec.ts @@ -15,7 +15,9 @@ import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; -import { schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UUID } from 'bson'; import { LtiMessageType, ToolContextType } from '../../common/enum'; import { Lti11EncryptionService } from '../../common/service'; diff --git a/apps/server/src/modules/tool/external-tool/authorization/external-tool.rule.spec.ts b/apps/server/src/modules/tool/external-tool/authorization/external-tool.rule.spec.ts index d31b9dd09d5..0de3ad333d1 100644 --- a/apps/server/src/modules/tool/external-tool/authorization/external-tool.rule.spec.ts +++ b/apps/server/src/modules/tool/external-tool/authorization/external-tool.rule.spec.ts @@ -5,7 +5,8 @@ import { externalToolFactory } from '@modules/tool/external-tool/testing'; import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ExternalToolRule } from './external-tool.rule'; describe(ExternalToolRule.name, () => { diff --git a/apps/server/src/modules/tool/external-tool/controller/api-test/admin-api-external-tool.api.spec.ts b/apps/server/src/modules/tool/external-tool/controller/api-test/admin-api-external-tool.api.spec.ts index 7d7a63d659d..fc7283c4e9c 100644 --- a/apps/server/src/modules/tool/external-tool/controller/api-test/admin-api-external-tool.api.spec.ts +++ b/apps/server/src/modules/tool/external-tool/controller/api-test/admin-api-external-tool.api.spec.ts @@ -2,9 +2,9 @@ import { EntityManager, MikroORM } from '@mikro-orm/core'; import { AdminApiServerTestModule } from '@modules/server/admin-api.server.module'; import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { TestApiClient } from '@shared/testing'; // admin-api-external-tool and test file is wrong placed need to be part of a admin-api-module folder import { adminApiServerConfig } from '@modules/server/admin-api-server.config'; +import { TestApiClient } from '@testing/test-api-client'; import { CustomParameterLocationParams, CustomParameterScopeTypeParams, diff --git a/apps/server/src/modules/tool/external-tool/controller/api-test/tool-configuration.api.spec.ts b/apps/server/src/modules/tool/external-tool/controller/api-test/tool-configuration.api.spec.ts index 876215381bb..4965ecaa4d1 100644 --- a/apps/server/src/modules/tool/external-tool/controller/api-test/tool-configuration.api.spec.ts +++ b/apps/server/src/modules/tool/external-tool/controller/api-test/tool-configuration.api.spec.ts @@ -9,13 +9,11 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Course, SchoolEntity, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { - courseFactory, - schoolEntityFactory, - TestApiClient, - UserAndAccountTestFactory, - userFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { Response } from 'supertest'; import { CustomParameterLocationParams, diff --git a/apps/server/src/modules/tool/external-tool/controller/api-test/tool.api.spec.ts b/apps/server/src/modules/tool/external-tool/controller/api-test/tool.api.spec.ts index 43c3cd75f7d..f342a2b1722 100644 --- a/apps/server/src/modules/tool/external-tool/controller/api-test/tool.api.spec.ts +++ b/apps/server/src/modules/tool/external-tool/controller/api-test/tool.api.spec.ts @@ -8,8 +8,11 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { cleanupCollections, schoolEntityFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; import { columnBoardEntityFactory, externalToolElementEntityFactory } from '@src/modules/board/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { Response } from 'supertest'; diff --git a/apps/server/src/modules/tool/external-tool/entity/external-tool.entity.spec.ts b/apps/server/src/modules/tool/external-tool/entity/external-tool.entity.spec.ts index 0d25caeded4..e89212863fa 100644 --- a/apps/server/src/modules/tool/external-tool/entity/external-tool.entity.spec.ts +++ b/apps/server/src/modules/tool/external-tool/entity/external-tool.entity.spec.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { CustomParameterLocation, CustomParameterScope, diff --git a/apps/server/src/modules/tool/external-tool/mapper/external-tool-datasheet.mapper.spec.ts b/apps/server/src/modules/tool/external-tool/mapper/external-tool-datasheet.mapper.spec.ts index 3cc59845750..09a1d0d94f6 100644 --- a/apps/server/src/modules/tool/external-tool/mapper/external-tool-datasheet.mapper.spec.ts +++ b/apps/server/src/modules/tool/external-tool/mapper/external-tool-datasheet.mapper.spec.ts @@ -3,7 +3,7 @@ import { School } from '@modules/school'; import { schoolFactory } from '@modules/school/testing'; import { SchoolExternalTool } from '@modules/tool/school-external-tool/domain'; import { UserDO } from '@shared/domain/domainobject'; -import { userDoFactory } from '@shared/testing'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { CustomParameter } from '../../common/domain'; import { CustomParameterScope, CustomParameterType, ToolContextType } from '../../common/enum'; import { schoolExternalToolFactory } from '../../school-external-tool/testing'; diff --git a/apps/server/src/modules/tool/external-tool/service/datasheet-pdf.service.spec.ts b/apps/server/src/modules/tool/external-tool/service/datasheet-pdf.service.spec.ts index 93dd006f836..98bf7c6ac25 100644 --- a/apps/server/src/modules/tool/external-tool/service/datasheet-pdf.service.spec.ts +++ b/apps/server/src/modules/tool/external-tool/service/datasheet-pdf.service.spec.ts @@ -1,6 +1,6 @@ import { Test, TestingModule } from '@nestjs/testing'; import { UserDO } from '@shared/domain/domainobject'; -import { userDoFactory } from '@shared/testing'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { createPdf, TCreatedPdf } from 'pdfmake/build/pdfmake'; import { TDocumentDefinitions } from 'pdfmake/interfaces'; import { CustomParameter } from '../../common/domain'; diff --git a/apps/server/src/modules/tool/external-tool/service/external-tool-configuration.service.spec.ts b/apps/server/src/modules/tool/external-tool/service/external-tool-configuration.service.spec.ts index d6240b1c242..95c7541f7d5 100644 --- a/apps/server/src/modules/tool/external-tool/service/external-tool-configuration.service.spec.ts +++ b/apps/server/src/modules/tool/external-tool/service/external-tool-configuration.service.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Test, TestingModule } from '@nestjs/testing'; import { Page } from '@shared/domain/domainobject'; import { EntityId } from '@shared/domain/types'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { CustomParameter } from '../../common/domain'; import { CustomParameterScope, ToolContextType } from '../../common/enum'; import { CommonToolService } from '../../common/service'; diff --git a/apps/server/src/modules/tool/external-tool/service/external-tool-image.service.spec.ts b/apps/server/src/modules/tool/external-tool/service/external-tool-image.service.spec.ts index e8435d8856b..3eee26cca0f 100644 --- a/apps/server/src/modules/tool/external-tool/service/external-tool-image.service.spec.ts +++ b/apps/server/src/modules/tool/external-tool/service/external-tool-image.service.spec.ts @@ -7,7 +7,8 @@ import { instanceFactory } from '@modules/instance/testing'; import { HttpService } from '@nestjs/axios'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { axiosResponseFactory, fileRecordFactory } from '@shared/testing'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; import { of } from 'rxjs'; import { ToolConfig } from '../../tool-config'; import { FileRecordRef } from '../domain'; diff --git a/apps/server/src/modules/tool/external-tool/service/external-tool-logo.service.spec.ts b/apps/server/src/modules/tool/external-tool/service/external-tool-logo.service.spec.ts index c374e1362d0..eee5561eaed 100644 --- a/apps/server/src/modules/tool/external-tool/service/external-tool-logo.service.spec.ts +++ b/apps/server/src/modules/tool/external-tool/service/external-tool-logo.service.spec.ts @@ -3,8 +3,8 @@ import { HttpService } from '@nestjs/axios'; import { HttpException, HttpStatus } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { axiosResponseFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { of, throwError } from 'rxjs'; import { ToolConfig } from '../../tool-config'; import { ExternalTool } from '../domain'; diff --git a/apps/server/src/modules/tool/external-tool/testing/external-tool-entity.factory.ts b/apps/server/src/modules/tool/external-tool/testing/external-tool-entity.factory.ts index 3e9866dd45a..f115d8ccfd9 100644 --- a/apps/server/src/modules/tool/external-tool/testing/external-tool-entity.factory.ts +++ b/apps/server/src/modules/tool/external-tool/testing/external-tool-entity.factory.ts @@ -1,6 +1,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { fileRecordFactory } from '@shared/testing'; -import { BaseFactory } from '@shared/testing/factory/base.factory'; +import { BaseFactory } from '@testing/factory/base.factory'; +import { fileRecordFactory } from '@testing/factory/filerecord.factory'; import { DeepPartial } from 'fishery'; import { CustomParameterLocation, diff --git a/apps/server/src/modules/tool/external-tool/testing/external-tool.factory.ts b/apps/server/src/modules/tool/external-tool/testing/external-tool.factory.ts index 2327eb4eee2..5ce2fde66d0 100644 --- a/apps/server/src/modules/tool/external-tool/testing/external-tool.factory.ts +++ b/apps/server/src/modules/tool/external-tool/testing/external-tool.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { DoBaseFactory } from '@shared/testing/factory/domainobject/do-base.factory'; +import { DoBaseFactory } from '@testing/factory/domainobject'; import { DeepPartial } from 'fishery'; import { CustomParameter } from '../../common/domain'; import { diff --git a/apps/server/src/modules/tool/external-tool/uc/external-tool-configuration.uc.spec.ts b/apps/server/src/modules/tool/external-tool/uc/external-tool-configuration.uc.spec.ts index 4fb768f019a..2e83011083b 100644 --- a/apps/server/src/modules/tool/external-tool/uc/external-tool-configuration.uc.spec.ts +++ b/apps/server/src/modules/tool/external-tool/uc/external-tool-configuration.uc.spec.ts @@ -8,8 +8,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Page } from '@shared/domain/domainobject'; import { User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; import { School, SchoolService } from '@src/modules/school'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CustomParameterScope, ToolContextType } from '../../common/enum'; import { ToolPermissionHelper } from '../../common/uc/tool-permission-helper'; import { ContextExternalToolService } from '../../context-external-tool'; diff --git a/apps/server/src/modules/tool/external-tool/uc/external-tool.uc.spec.ts b/apps/server/src/modules/tool/external-tool/uc/external-tool.uc.spec.ts index 42eb7db29e5..581a831759c 100644 --- a/apps/server/src/modules/tool/external-tool/uc/external-tool.uc.spec.ts +++ b/apps/server/src/modules/tool/external-tool/uc/external-tool.uc.spec.ts @@ -12,7 +12,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Page } from '@shared/domain/domainobject/page'; import { Role, User } from '@shared/domain/entity'; import { IFindOptions, Permission, SortOrder } from '@shared/domain/interface'; -import { currentUserFactory, roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CustomParameter } from '../../common/domain'; import { LtiMessageType, LtiPrivacyPermission, ToolConfigType } from '../../common/enum'; import { ExternalToolSearchQuery } from '../../common/interface'; diff --git a/apps/server/src/modules/tool/school-external-tool/authorization/school-external-tool.rule.spec.ts b/apps/server/src/modules/tool/school-external-tool/authorization/school-external-tool.rule.spec.ts index 42c22849882..e9296220e22 100644 --- a/apps/server/src/modules/tool/school-external-tool/authorization/school-external-tool.rule.spec.ts +++ b/apps/server/src/modules/tool/school-external-tool/authorization/school-external-tool.rule.spec.ts @@ -6,7 +6,10 @@ import { schoolExternalToolEntityFactory, schoolExternalToolFactory } from '@mod import { Test, TestingModule } from '@nestjs/testing'; import { Role, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { roleFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SchoolExternalToolRule } from './school-external-tool.rule'; describe('SchoolExternalToolRule', () => { diff --git a/apps/server/src/modules/tool/school-external-tool/controller/api-test/admin-api-school-external-tool.api.spec.ts b/apps/server/src/modules/tool/school-external-tool/controller/api-test/admin-api-school-external-tool.api.spec.ts index 336d333497e..76cbc744352 100644 --- a/apps/server/src/modules/tool/school-external-tool/controller/api-test/admin-api-school-external-tool.api.spec.ts +++ b/apps/server/src/modules/tool/school-external-tool/controller/api-test/admin-api-school-external-tool.api.spec.ts @@ -3,9 +3,10 @@ import { AdminApiServerTestModule } from '@modules/server/admin-api.server.modul import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; -import { schoolEntityFactory, TestApiClient } from '@shared/testing'; // admin-api-external-tool and test file is wrong placed need to be part of a admin-api-module folder import { adminApiServerConfig } from '@modules/server/admin-api-server.config'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { ExternalToolResponse } from '../../../external-tool/controller/dto'; import { CustomParameterScope, CustomParameterType, ExternalToolEntity } from '../../../external-tool/entity'; import { customParameterEntityFactory, externalToolEntityFactory } from '../../../external-tool/testing'; diff --git a/apps/server/src/modules/tool/school-external-tool/controller/api-test/tool-school.api.spec.ts b/apps/server/src/modules/tool/school-external-tool/controller/api-test/tool-school.api.spec.ts index 14337c32f60..7318e138a3c 100644 --- a/apps/server/src/modules/tool/school-external-tool/controller/api-test/tool-school.api.spec.ts +++ b/apps/server/src/modules/tool/school-external-tool/controller/api-test/tool-school.api.spec.ts @@ -5,10 +5,13 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { schoolEntityFactory, TestApiClient, UserAndAccountTestFactory, userFactory } from '@shared/testing'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { accountFactory } from '@src/modules/account/testing'; import { columnBoardEntityFactory, externalToolElementEntityFactory } from '@src/modules/board/testing'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { ContextExternalToolEntity, ContextExternalToolType } from '../../../context-external-tool/entity'; import { contextExternalToolEntityFactory } from '../../../context-external-tool/testing'; import { CustomParameterScope, CustomParameterType, ExternalToolEntity } from '../../../external-tool/entity'; diff --git a/apps/server/src/modules/tool/school-external-tool/service/school-external-tool-authorization.service.spec.ts b/apps/server/src/modules/tool/school-external-tool/service/school-external-tool-authorization.service.spec.ts index bb14eed177d..6909d37ec72 100644 --- a/apps/server/src/modules/tool/school-external-tool/service/school-external-tool-authorization.service.spec.ts +++ b/apps/server/src/modules/tool/school-external-tool/service/school-external-tool-authorization.service.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { AuthorizableReferenceType, AuthorizationInjectionService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolExternalToolRepo } from '@shared/repo'; -import { legacySchoolDoFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; import { SchoolExternalTool } from '../domain'; import { schoolExternalToolFactory } from '../testing'; import { SchoolExternalToolAuthorizableService } from './school-external-tool-authorizable.service'; diff --git a/apps/server/src/modules/tool/school-external-tool/testing/school-external-tool-entity.factory.ts b/apps/server/src/modules/tool/school-external-tool/testing/school-external-tool-entity.factory.ts index 383aabbb407..99bf7da40ca 100644 --- a/apps/server/src/modules/tool/school-external-tool/testing/school-external-tool-entity.factory.ts +++ b/apps/server/src/modules/tool/school-external-tool/testing/school-external-tool-entity.factory.ts @@ -1,7 +1,7 @@ import { externalToolEntityFactory } from '@modules/tool/external-tool/testing'; import { SchoolExternalToolEntity, SchoolExternalToolEntityProps } from '@modules/tool/school-external-tool/entity'; -import { BaseFactory } from '@shared/testing/factory/base.factory'; -import { schoolEntityFactory } from '@shared/testing/factory/school-entity.factory'; +import { BaseFactory } from '@testing/factory/base.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; export const schoolExternalToolEntityFactory = BaseFactory.define< SchoolExternalToolEntity, diff --git a/apps/server/src/modules/tool/school-external-tool/testing/school-external-tool.factory.ts b/apps/server/src/modules/tool/school-external-tool/testing/school-external-tool.factory.ts index a3e8fd641e7..edf3bd5e978 100644 --- a/apps/server/src/modules/tool/school-external-tool/testing/school-external-tool.factory.ts +++ b/apps/server/src/modules/tool/school-external-tool/testing/school-external-tool.factory.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { DoBaseFactory } from '@shared/testing/factory/domainobject/do-base.factory'; +import { DoBaseFactory } from '@testing/factory/domainobject'; import { DeepPartial } from 'fishery'; import { CustomParameterEntry } from '../../common/domain'; import { SchoolExternalTool, SchoolExternalToolProps } from '../domain'; diff --git a/apps/server/src/modules/tool/school-external-tool/uc/school-external-tool.uc.spec.ts b/apps/server/src/modules/tool/school-external-tool/uc/school-external-tool.uc.spec.ts index 9305afbefef..552ce9405bc 100644 --- a/apps/server/src/modules/tool/school-external-tool/uc/school-external-tool.uc.spec.ts +++ b/apps/server/src/modules/tool/school-external-tool/uc/school-external-tool.uc.spec.ts @@ -5,8 +5,9 @@ import { schoolFactory } from '@modules/school/testing'; import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { setupEntities, userFactory } from '@shared/testing'; import { School, SchoolService } from '@src/modules/school'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CommonToolMetadataService } from '../../common/service/common-tool-metadata.service'; import { SchoolExternalTool } from '../domain'; import { SchoolExternalToolService, SchoolExternalToolValidationService } from '../service'; diff --git a/apps/server/src/modules/tool/tool-launch/controller/api-test/tool-launch.controller.api.spec.ts b/apps/server/src/modules/tool/tool-launch/controller/api-test/tool-launch.controller.api.spec.ts index 82f8efba10f..12858458e31 100644 --- a/apps/server/src/modules/tool/tool-launch/controller/api-test/tool-launch.controller.api.spec.ts +++ b/apps/server/src/modules/tool/tool-launch/controller/api-test/tool-launch.controller.api.spec.ts @@ -5,9 +5,12 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Course, SchoolEntity } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { courseFactory, schoolEntityFactory, TestApiClient, UserAndAccountTestFactory } from '@shared/testing'; import { BoardExternalReferenceType } from '@src/modules/board'; import { mediaBoardEntityFactory } from '@src/modules/board/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { Response } from 'supertest'; import { CustomParameterLocation, diff --git a/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-context-name.strategy.spec.ts b/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-context-name.strategy.spec.ts index c4893063bb8..fc6a07645c3 100644 --- a/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-context-name.strategy.spec.ts +++ b/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-context-name.strategy.spec.ts @@ -1,11 +1,12 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ObjectId } from '@mikro-orm/mongodb'; -import { BoardCommonToolService, BoardExternalReferenceType, ColumnBoard, BoardNodeService } from '@modules/board'; +import { BoardCommonToolService, BoardExternalReferenceType, BoardNodeService, ColumnBoard } from '@modules/board'; +import { columnBoardFactory, externalToolElementFactory } from '@modules/board/testing'; import { CourseService } from '@modules/learnroom'; import { Test, TestingModule } from '@nestjs/testing'; import { Course } from '@shared/domain/entity'; -import { courseFactory, setupEntities } from '@shared/testing'; -import { columnBoardFactory, externalToolElementFactory } from '@modules/board/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ToolContextType } from '../../../common/enum'; import { ContextExternalTool } from '../../../context-external-tool/domain'; import { contextExternalToolFactory } from '../../../context-external-tool/testing'; diff --git a/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-group-external-uuid.strategy.spec.ts b/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-group-external-uuid.strategy.spec.ts index db7f9351f25..78f5b0d02ce 100644 --- a/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-group-external-uuid.strategy.spec.ts +++ b/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-group-external-uuid.strategy.spec.ts @@ -7,7 +7,10 @@ import { GroupEntity } from '@modules/group/entity'; import { CourseService } from '@modules/learnroom'; import { Test, TestingModule } from '@nestjs/testing'; import { Course } from '@shared/domain/entity'; -import { courseFactory, groupEntityFactory, groupFactory, setupEntities } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { groupFactory } from '@testing/factory/domainobject'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ToolContextType } from '../../../common/enum'; import { ContextExternalTool } from '../../../context-external-tool/domain'; import { contextExternalToolFactory } from '../../../context-external-tool/testing'; diff --git a/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-school-number.strategy.spec.ts b/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-school-number.strategy.spec.ts index 122e559cad3..cb8f9a825f0 100644 --- a/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-school-number.strategy.spec.ts +++ b/apps/server/src/modules/tool/tool-launch/service/auto-parameter-strategy/auto-school-number.strategy.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { LegacySchoolService } from '@modules/legacy-school'; import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo } from '@shared/domain/domainobject'; -import { legacySchoolDoFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; import { ContextExternalTool } from '../../../context-external-tool/domain'; import { contextExternalToolFactory } from '../../../context-external-tool/testing'; import { SchoolExternalTool } from '../../../school-external-tool/domain'; diff --git a/apps/server/src/modules/tool/tool-launch/service/launch-strategy/lti11-tool-launch.strategy.spec.ts b/apps/server/src/modules/tool/tool-launch/service/launch-strategy/lti11-tool-launch.strategy.spec.ts index 8a8c25831df..6f66b5c5f24 100644 --- a/apps/server/src/modules/tool/tool-launch/service/launch-strategy/lti11-tool-launch.strategy.spec.ts +++ b/apps/server/src/modules/tool/tool-launch/service/launch-strategy/lti11-tool-launch.strategy.spec.ts @@ -8,8 +8,8 @@ import { InternalServerErrorException, UnprocessableEntityException } from '@nes import { Test, TestingModule } from '@nestjs/testing'; import { Pseudonym, UserDO } from '@shared/domain/domainobject'; import { RoleName } from '@shared/domain/interface'; -import { userDoFactory } from '@shared/testing'; -import { pseudonymFactory } from '@shared/testing/factory/domainobject/pseudonym.factory'; +import { pseudonymFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { Authorization } from 'oauth-1.0a'; import { CustomParameterEntry } from '../../../common/domain'; import { LtiMessageType, LtiPrivacyPermission, LtiRole, ToolContextType } from '../../../common/enum'; diff --git a/apps/server/src/modules/tool/tool-launch/uc/tool-launch.uc.spec.ts b/apps/server/src/modules/tool/tool-launch/uc/tool-launch.uc.spec.ts index e83fb3afc64..b40ef892f82 100644 --- a/apps/server/src/modules/tool/tool-launch/uc/tool-launch.uc.spec.ts +++ b/apps/server/src/modules/tool/tool-launch/uc/tool-launch.uc.spec.ts @@ -6,7 +6,8 @@ import { LaunchContextUnavailableLoggableException } from '@modules/tool/tool-la import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ToolContextType } from '../../common/enum'; import { ToolPermissionHelper } from '../../common/uc/tool-permission-helper'; import { ContextExternalTool, ContextExternalToolLaunchable } from '../../context-external-tool/domain'; diff --git a/apps/server/src/modules/user-import/controller/api-test/import-user-populate.api.spec.ts b/apps/server/src/modules/user-import/controller/api-test/import-user-populate.api.spec.ts index 47eee9ccb07..fa9c34b2107 100644 --- a/apps/server/src/modules/user-import/controller/api-test/import-user-populate.api.spec.ts +++ b/apps/server/src/modules/user-import/controller/api-test/import-user-populate.api.spec.ts @@ -8,15 +8,13 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission, RoleName } from '@shared/domain/interface'; import { SchoolFeature } from '@shared/domain/types'; -import { - roleFactory, - schoolEntityFactory, - systemEntityFactory, - TestApiClient, - userFactory, - userLoginMigrationFactory, -} from '@shared/testing'; import { accountFactory } from '@src/modules/account/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userLoginMigrationFactory } from '@testing/factory/user-login-migration.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; diff --git a/apps/server/src/modules/user-import/controller/api-test/import-user.api.spec.ts b/apps/server/src/modules/user-import/controller/api-test/import-user.api.spec.ts index 5286458b0eb..1f5e4e47df9 100644 --- a/apps/server/src/modules/user-import/controller/api-test/import-user.api.spec.ts +++ b/apps/server/src/modules/user-import/controller/api-test/import-user.api.spec.ts @@ -24,18 +24,16 @@ import { PaginationParams } from '@shared/controller'; import { SchoolEntity, User } from '@shared/domain/entity'; import { Permission, RoleName, SortOrder } from '@shared/domain/interface'; import { SchoolFeature } from '@shared/domain/types'; -import { - cleanupCollections, - importUserFactory, - roleFactory, - schoolEntityFactory, - systemEntityFactory, - TestApiClient, - UserAndAccountTestFactory, - userFactory, -} from '@shared/testing'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { accountFactory } from '@src/modules/account/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { ImportUser, MatchCreator } from '../../entity'; describe('ImportUser Controller (API)', () => { diff --git a/apps/server/src/modules/user-import/controller/dto/populate-import-user.params.ts b/apps/server/src/modules/user-import/controller/dto/populate-import-user.params.ts new file mode 100644 index 00000000000..4ddb7271358 --- /dev/null +++ b/apps/server/src/modules/user-import/controller/dto/populate-import-user.params.ts @@ -0,0 +1,12 @@ +import { ApiPropertyOptional } from '@nestjs/swagger'; +import { IsBoolean, IsOptional } from 'class-validator'; + +export class PopulateImportUserParams { + @IsOptional() + @IsBoolean() + @ApiPropertyOptional({ + description: + 'Should the users preferred name from the external system be used for auto-matching to existing users?', + }) + public matchByPreferredName?: boolean; +} diff --git a/apps/server/src/modules/user-import/controller/import-user.controller.ts b/apps/server/src/modules/user-import/controller/import-user.controller.ts index d1fb56b3c6b..3539e9a49de 100644 --- a/apps/server/src/modules/user-import/controller/import-user.controller.ts +++ b/apps/server/src/modules/user-import/controller/import-user.controller.ts @@ -28,6 +28,7 @@ import { UpdateMatchParams, UserMatchListResponse, } from './dto'; +import { PopulateImportUserParams } from './dto/populate-import-user.params'; @ApiTags('UserImport') @JwtAuthentication() @@ -135,8 +136,11 @@ export class ImportUserController { @ApiServiceUnavailableResponse() @ApiBadRequestResponse() @ApiForbiddenResponse() - async populateImportUsers(@CurrentUser() currentUser: ICurrentUser): Promise { - await this.userImportFetchUc.populateImportUsers(currentUser.userId); + async populateImportUsers( + @CurrentUser() currentUser: ICurrentUser, + @Query() query: PopulateImportUserParams + ): Promise { + await this.userImportFetchUc.populateImportUsers(currentUser.userId, query.matchByPreferredName); } @Post('cancel') diff --git a/apps/server/src/modules/user-import/entity/import-user.entity.spec.ts b/apps/server/src/modules/user-import/entity/import-user.entity.spec.ts index 66c55798cd9..720892bf42d 100644 --- a/apps/server/src/modules/user-import/entity/import-user.entity.spec.ts +++ b/apps/server/src/modules/user-import/entity/import-user.entity.spec.ts @@ -1,4 +1,7 @@ -import { importUserFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { MatchCreator } from './import-user.entity'; describe('ImportUser entity', () => { diff --git a/apps/server/src/modules/user-import/entity/import-user.entity.ts b/apps/server/src/modules/user-import/entity/import-user.entity.ts index 5944ae5f4c5..ce96dbe6a70 100644 --- a/apps/server/src/modules/user-import/entity/import-user.entity.ts +++ b/apps/server/src/modules/user-import/entity/import-user.entity.ts @@ -16,6 +16,7 @@ export interface ImportUserProperties { externalId: string; // descriptive properties firstName: string; + preferredName?: string; lastName: string; email: string; // TODO VO roleNames?: ImportUserRoleName[]; @@ -43,6 +44,7 @@ export class ImportUser extends BaseEntityWithTimestamps implements EntityWithSc this.ldapDn = props.ldapDn; this.externalId = props.externalId; this.firstName = props.firstName; + this.preferredName = props.preferredName; this.lastName = props.lastName; this.email = props.email; if (Array.isArray(props.roleNames) && props.roleNames.length > 0) this.roleNames.push(...props.roleNames); @@ -81,6 +83,9 @@ export class ImportUser extends BaseEntityWithTimestamps implements EntityWithSc @Property() firstName: string; + @Property({ nullable: true }) + preferredName?: string; + @Property() lastName: string; diff --git a/apps/server/src/modules/user-import/loggable/user-migration-canceled.loggable.spec.ts b/apps/server/src/modules/user-import/loggable/user-migration-canceled.loggable.spec.ts index 7a53884cd95..77aa080d05a 100644 --- a/apps/server/src/modules/user-import/loggable/user-migration-canceled.loggable.spec.ts +++ b/apps/server/src/modules/user-import/loggable/user-migration-canceled.loggable.spec.ts @@ -1,4 +1,4 @@ -import { legacySchoolDoFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; import { UserMigrationCanceledLoggable } from './user-migration-canceled.loggable'; describe('UserMigrationCanceledLoggable', () => { diff --git a/apps/server/src/modules/user-import/loggable/user-migration-failed.loggable.spec.ts b/apps/server/src/modules/user-import/loggable/user-migration-failed.loggable.spec.ts index 96363bb1ec9..a4c169f0309 100644 --- a/apps/server/src/modules/user-import/loggable/user-migration-failed.loggable.spec.ts +++ b/apps/server/src/modules/user-import/loggable/user-migration-failed.loggable.spec.ts @@ -1,5 +1,6 @@ import { NotFoundException } from '@nestjs/common'; -import { importUserFactory, setupEntities } from '@shared/testing'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserMigrationFailedLoggable } from './user-migration-failed.loggable'; describe(UserMigrationFailedLoggable.name, () => { diff --git a/apps/server/src/modules/user-import/mapper/import-user.mapper.spec.ts b/apps/server/src/modules/user-import/mapper/import-user.mapper.spec.ts index a298006d329..eedbf21eb84 100644 --- a/apps/server/src/modules/user-import/mapper/import-user.mapper.spec.ts +++ b/apps/server/src/modules/user-import/mapper/import-user.mapper.spec.ts @@ -1,6 +1,9 @@ import { BadRequestException } from '@nestjs/common'; import { RoleName, SortOrder } from '@shared/domain/interface'; -import { importUserFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { FilterImportUserParams, FilterMatchType, diff --git a/apps/server/src/modules/user-import/mapper/schulconnex-import-user.mapper.ts b/apps/server/src/modules/user-import/mapper/schulconnex-import-user.mapper.ts index 83d7f5a7455..5dae20284d6 100644 --- a/apps/server/src/modules/user-import/mapper/schulconnex-import-user.mapper.ts +++ b/apps/server/src/modules/user-import/mapper/schulconnex-import-user.mapper.ts @@ -27,6 +27,7 @@ export class SchulconnexImportUserMapper { ldapDn: `uid=${externalUser.person.name.vorname}.${externalUser.person.name.familienname}.${externalUser.pid},`, externalId: externalUser.pid, firstName: externalUser.person.name.vorname, + preferredName: externalUser.person.name.rufname, lastName: externalUser.person.name.familienname, roleNames: ImportUser.isImportUserRole(role) ? [role] : [], email: `${externalUser.person.name.vorname}.${externalUser.person.name.familienname}.${externalUser.pid}@schul-cloud.org`, diff --git a/apps/server/src/modules/user-import/mapper/user-match.mapper.spec.ts b/apps/server/src/modules/user-import/mapper/user-match.mapper.spec.ts index df826a50f2e..a5e304d01f2 100644 --- a/apps/server/src/modules/user-import/mapper/user-match.mapper.spec.ts +++ b/apps/server/src/modules/user-import/mapper/user-match.mapper.spec.ts @@ -1,10 +1,12 @@ import { RoleName } from '@shared/domain/interface'; -import { roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { MatchType, UserRole } from '../controller/dto'; import { FilterUserParams } from '../controller/dto/filter-user.params'; +import { MatchCreator } from '../entity'; import { ImportUserMatchMapper } from './match.mapper'; import { UserMatchMapper } from './user-match.mapper'; -import { MatchCreator } from '../entity'; describe('[UserMatchMapper]', () => { beforeAll(async () => { diff --git a/apps/server/src/modules/user-import/repo/import-user.repo.spec.ts b/apps/server/src/modules/user-import/repo/import-user.repo.spec.ts index 163e62fe42c..ff87e50e5ad 100644 --- a/apps/server/src/modules/user-import/repo/import-user.repo.spec.ts +++ b/apps/server/src/modules/user-import/repo/import-user.repo.spec.ts @@ -4,15 +4,13 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity, User } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; -import { - cleanupCollections, - createCollections, - importUserFactory, - schoolEntityFactory, - userFactory, -} from '@shared/testing'; -import { ImportUserRoleName, ImportUser, MatchCreator } from '../entity'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { createCollections } from '@testing/create-collections'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { ImportUserMatchCreatorScope } from '../domain/interface'; +import { ImportUser, ImportUserRoleName, MatchCreator } from '../entity'; import { ImportUserRepo } from './import-user.repo'; describe('ImportUserRepo', () => { diff --git a/apps/server/src/modules/user-import/service/schulconnex-fetch-import-users.service.spec.ts b/apps/server/src/modules/user-import/service/schulconnex-fetch-import-users.service.spec.ts index c764d2b1793..a191ea1adc0 100644 --- a/apps/server/src/modules/user-import/service/schulconnex-fetch-import-users.service.spec.ts +++ b/apps/server/src/modules/user-import/service/schulconnex-fetch-import-users.service.spec.ts @@ -10,13 +10,11 @@ import { Test, TestingModule } from '@nestjs/testing'; import { UserDO } from '@shared/domain/domainobject'; import { SchoolEntity } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; -import { - importUserFactory, - schoolEntityFactory, - setupEntities, - systemEntityFactory, - userDoFactory, -} from '@shared/testing'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ImportUser } from '../entity'; import { UserImportSchoolExternalIdMissingLoggableException } from '../loggable'; import { SchulconnexFetchImportUsersService } from './schulconnex-fetch-import-users.service'; @@ -70,6 +68,7 @@ describe(SchulconnexFetchImportUsersService.name, () => { ldapDn: `uid=${externalUserData.person.name.vorname}.${externalUserData.person.name.familienname}.${externalUserData.pid},`, externalId: externalUserData.pid, firstName: externalUserData.person.name.vorname, + preferredName: externalUserData.person.name.rufname, lastName: externalUserData.person.name.familienname, email: `${externalUserData.person.name.vorname}.${externalUserData.person.name.familienname}.${externalUserData.pid}@schul-cloud.org`, roleNames: [RoleName.ADMINISTRATOR], diff --git a/apps/server/src/modules/user-import/service/user-import.service.spec.ts b/apps/server/src/modules/user-import/service/user-import.service.spec.ts index e4f0b759e79..d4d0f93a799 100644 --- a/apps/server/src/modules/user-import/service/user-import.service.spec.ts +++ b/apps/server/src/modules/user-import/service/user-import.service.spec.ts @@ -11,15 +11,12 @@ import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, UserLoginMigrationDO } from '@shared/domain/domainobject'; import { SchoolEntity, User } from '@shared/domain/entity'; import { SchoolFeature } from '@shared/domain/types'; -import { - importUserFactory, - legacySchoolDoFactory, - schoolEntityFactory, - setupEntities, - userFactory, - userLoginMigrationDOFactory, -} from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ImportUser, MatchCreator } from '../entity'; import { UserMigrationCanceledLoggable, UserMigrationIsNotEnabled } from '../loggable'; import { ImportUserRepo } from '../repo'; @@ -247,7 +244,48 @@ describe(UserImportService.name, () => { it('should return all users as auto matched', async () => { const { user1, user2, importUser1, importUser2, userLoginMigration } = setup(); - const result: ImportUser[] = await service.matchUsers([importUser1, importUser2], userLoginMigration); + const result: ImportUser[] = await service.matchUsers([importUser1, importUser2], userLoginMigration, false); + + expect(result).toEqual([ + { ...importUser1, user: user1, matchedBy: MatchCreator.AUTO }, + { ...importUser2, user: user2, matchedBy: MatchCreator.AUTO }, + ]); + }); + }); + + describe('when preferred names are used and all users have unique names', () => { + const setup = () => { + const school: SchoolEntity = schoolEntityFactory.buildWithId(); + const userLoginMigration: UserLoginMigrationDO = userLoginMigrationDOFactory.build({ schoolId: school.id }); + const user1: User = userFactory.buildWithId({ firstName: 'First1', lastName: 'Last1' }); + const user2: User = userFactory.buildWithId({ firstName: 'First2', lastName: 'Last2' }); + const importUser1: ImportUser = importUserFactory.buildWithId({ + school, + preferredName: user1.preferredName, + lastName: user1.lastName, + }); + const importUser2: ImportUser = importUserFactory.buildWithId({ + school, + firstName: user2.firstName, + lastName: user2.lastName, + }); + + userService.findUserBySchoolAndName.mockResolvedValueOnce([user1]); + userService.findUserBySchoolAndName.mockResolvedValueOnce([user2]); + + return { + user1, + user2, + importUser1, + importUser2, + userLoginMigration, + }; + }; + + it('should return users with preferred name matched by preferred name and users without matched by first name', async () => { + const { user1, user2, importUser1, importUser2, userLoginMigration } = setup(); + + const result: ImportUser[] = await service.matchUsers([importUser1, importUser2], userLoginMigration, true); expect(result).toEqual([ { ...importUser1, user: user1, matchedBy: MatchCreator.AUTO }, @@ -286,7 +324,7 @@ describe(UserImportService.name, () => { it('should return the users without a match', async () => { const { importUser1, importUser2, userLoginMigration } = setup(); - const result: ImportUser[] = await service.matchUsers([importUser1, importUser2], userLoginMigration); + const result: ImportUser[] = await service.matchUsers([importUser1, importUser2], userLoginMigration, false); expect(result).toEqual([importUser1, importUser2]); }); @@ -318,7 +356,7 @@ describe(UserImportService.name, () => { it('should return the users without a match', async () => { const { importUser1, userLoginMigration } = setup(); - const result: ImportUser[] = await service.matchUsers([importUser1], userLoginMigration); + const result: ImportUser[] = await service.matchUsers([importUser1], userLoginMigration, false); expect(result).toEqual([importUser1]); }); @@ -354,7 +392,7 @@ describe(UserImportService.name, () => { it('should return the users without a match', async () => { const { importUser1, importUser2, userLoginMigration } = setup(); - const result: ImportUser[] = await service.matchUsers([importUser1, importUser2], userLoginMigration); + const result: ImportUser[] = await service.matchUsers([importUser1, importUser2], userLoginMigration, false); result.forEach((importUser) => expect(importUser.matchedBy).toBeUndefined()); }); @@ -387,7 +425,7 @@ describe(UserImportService.name, () => { it('should return the user without a match', async () => { const { importUser1, userLoginMigration } = setup(); - const result: ImportUser[] = await service.matchUsers([importUser1], userLoginMigration); + const result: ImportUser[] = await service.matchUsers([importUser1], userLoginMigration, false); result.forEach((importUser) => expect(importUser.matchedBy).toBeUndefined()); }); diff --git a/apps/server/src/modules/user-import/service/user-import.service.ts b/apps/server/src/modules/user-import/service/user-import.service.ts index ab9014acef0..8a1f82be0a4 100644 --- a/apps/server/src/modules/user-import/service/user-import.service.ts +++ b/apps/server/src/modules/user-import/service/user-import.service.ts @@ -7,10 +7,10 @@ import { LegacySchoolDo, UserLoginMigrationDO } from '@shared/domain/domainobjec import { SchoolEntity, User } from '@shared/domain/entity'; import { SchoolFeature } from '@shared/domain/types'; import { Logger } from '@src/core/logger'; +import { ImportUser, MatchCreator } from '../entity'; import { UserMigrationCanceledLoggable, UserMigrationIsNotEnabled } from '../loggable'; -import { UserImportConfig } from '../user-import-config'; import { ImportUserRepo } from '../repo/import-user.repo'; -import { ImportUser, MatchCreator } from '../entity'; +import { UserImportConfig } from '../user-import-config'; @Injectable() export class UserImportService { @@ -45,20 +45,26 @@ export class UserImportService { } } - public async matchUsers(importUsers: ImportUser[], userLoginMigration: UserLoginMigrationDO): Promise { + public async matchUsers( + importUsers: ImportUser[], + userLoginMigration: UserLoginMigrationDO, + matchByPreferredName: boolean + ): Promise { const importUserMap: Map = new Map(); - importUsers.forEach((importUser) => { - const key = `${importUser.school.id}_${importUser.firstName}_${importUser.lastName}`; + importUsers.forEach((importUser: ImportUser): void => { + const firstName: string = this.getFirstNameForMatching(importUser, matchByPreferredName); + const key = `${importUser.school.id}_${firstName}_${importUser.lastName}`; const count = importUserMap.get(key) || 0; importUserMap.set(key, count + 1); }); const matchedImportUsers: ImportUser[] = await Promise.all( importUsers.map(async (importUser: ImportUser): Promise => { + const firstName: string = this.getFirstNameForMatching(importUser, matchByPreferredName); const users: User[] = await this.userService.findUserBySchoolAndName( importUser.school.id, - importUser.firstName, + firstName, importUser.lastName ); @@ -66,7 +72,7 @@ export class UserImportService { (user: User) => !user.lastLoginSystemChange || user.lastLoginSystemChange < userLoginMigration.startedAt ); - const key = `${importUser.school.id}_${importUser.firstName}_${importUser.lastName}`; + const key = `${importUser.school.id}_${firstName}_${importUser.lastName}`; if (users.length === 1 && unmigratedUsers.length === 1 && importUserMap.get(key) === 1) { importUser.user = unmigratedUsers[0]; @@ -80,6 +86,10 @@ export class UserImportService { return matchedImportUsers; } + private getFirstNameForMatching(importUser: ImportUser, matchByPreferredName: boolean): string { + return matchByPreferredName && importUser.preferredName ? importUser.preferredName : importUser.firstName; + } + public async deleteImportUsersBySchool(school: SchoolEntity): Promise { await this.userImportRepo.deleteImportUsersBySchool(school); } diff --git a/apps/server/src/modules/user-import/uc/user-import-fetch.uc.spec.ts b/apps/server/src/modules/user-import/uc/user-import-fetch.uc.spec.ts index 5b6df1f8e97..122897f7551 100644 --- a/apps/server/src/modules/user-import/uc/user-import-fetch.uc.spec.ts +++ b/apps/server/src/modules/user-import/uc/user-import-fetch.uc.spec.ts @@ -9,13 +9,11 @@ import { Test, TestingModule } from '@nestjs/testing'; import { UserLoginMigrationDO } from '@shared/domain/domainobject'; import { User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { - importUserFactory, - setupEntities, - systemEntityFactory, - userFactory, - userLoginMigrationDOFactory, -} from '@shared/testing'; +import { userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserLoginMigrationService } from '../../user-login-migration'; import { ImportUser } from '../entity'; import { UserLoginMigrationNotActiveLoggableException, UserMigrationIsNotEnabledLoggableException } from '../loggable'; @@ -147,7 +145,7 @@ describe(UserImportFetchUc.name, () => { await uc.populateImportUsers(user.id); - expect(userImportService.matchUsers).toHaveBeenCalledWith([importUser], userLoginMigration); + expect(userImportService.matchUsers).toHaveBeenCalledWith([importUser], userLoginMigration, false); }); it('should delete all existing imported users of the school', async () => { @@ -166,6 +164,43 @@ describe(UserImportFetchUc.name, () => { expect(userImportService.saveImportUsers).toHaveBeenCalledWith([importUser]); }); }); + + describe('when matching users by preferred name', () => { + const setup = () => { + const systemEntity: SystemEntity = systemEntityFactory.buildWithId(); + const system: System = systemFactory.build({ id: systemEntity.id }); + const user: User = userFactory.buildWithId(); + const importUser: ImportUser = importUserFactory.build({ + system: systemEntity, + }); + const userLoginMigration: UserLoginMigrationDO = userLoginMigrationDOFactory.build({ + targetSystemId: system.id, + }); + + authorizationService.getUserWithPermissions.mockResolvedValueOnce(user); + userLoginMigrationService.findMigrationBySchool.mockResolvedValueOnce(userLoginMigration); + systemService.findByIdOrFail.mockResolvedValueOnce(system); + schulconnexFetchImportUsersService.getData.mockResolvedValueOnce([importUser]); + schulconnexFetchImportUsersService.filterAlreadyMigratedUser.mockResolvedValueOnce([importUser]); + userImportService.matchUsers.mockResolvedValueOnce([importUser]); + + return { + user, + systemEntity, + system, + importUser, + userLoginMigration, + }; + }; + + it('should match the users by preferred name', async () => { + const { user, importUser, userLoginMigration } = setup(); + + await uc.populateImportUsers(user.id, true); + + expect(userImportService.matchUsers).toHaveBeenCalledWith([importUser], userLoginMigration, true); + }); + }); }); describe('when the school has not started the migration', () => { diff --git a/apps/server/src/modules/user-import/uc/user-import-fetch.uc.ts b/apps/server/src/modules/user-import/uc/user-import-fetch.uc.ts index 40ee1e9f8d6..1c2bc866379 100644 --- a/apps/server/src/modules/user-import/uc/user-import-fetch.uc.ts +++ b/apps/server/src/modules/user-import/uc/user-import-fetch.uc.ts @@ -23,7 +23,7 @@ export class UserImportFetchUc { private readonly systemService: SystemService ) {} - public async populateImportUsers(currentUserId: EntityId): Promise { + public async populateImportUsers(currentUserId: EntityId, matchByPreferredName = false): Promise { if (!this.configService.get('FEATURE_USER_MIGRATION_ENABLED')) { throw new UserMigrationIsNotEnabledLoggableException(currentUserId); } @@ -49,7 +49,8 @@ export class UserImportFetchUc { const matchedImportUsers: ImportUser[] = await this.userImportService.matchUsers( filteredFetchedData, - userLoginMigration + userLoginMigration, + matchByPreferredName ); await this.userImportService.deleteImportUsersBySchool(user.school); diff --git a/apps/server/src/modules/user-import/uc/user-import.uc.spec.ts b/apps/server/src/modules/user-import/uc/user-import.uc.spec.ts index b924f67f54f..95eeeb070e3 100644 --- a/apps/server/src/modules/user-import/uc/user-import.uc.spec.ts +++ b/apps/server/src/modules/user-import/uc/user-import.uc.spec.ts @@ -19,18 +19,15 @@ import { SchoolEntity, User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; import { Counted, SchoolFeature } from '@shared/domain/types'; import { UserRepo } from '@shared/repo'; -import { - federalStateFactory, - importUserFactory, - legacySchoolDoFactory, - schoolEntityFactory, - setupEntities, - systemEntityFactory, - userDoFactory, - userFactory, - userLoginMigrationDOFactory, -} from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ImportUserFilter, ImportUserMatchCreatorScope } from '../domain/interface'; import { ImportUser, MatchCreator } from '../entity'; import { diff --git a/apps/server/src/modules/user-license/repo/media-user-license.repo.spec.ts b/apps/server/src/modules/user-license/repo/media-user-license.repo.spec.ts index da981e32060..454e082f852 100644 --- a/apps/server/src/modules/user-license/repo/media-user-license.repo.spec.ts +++ b/apps/server/src/modules/user-license/repo/media-user-license.repo.spec.ts @@ -1,17 +1,18 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; -import { Test, TestingModule } from '@nestjs/testing'; -import { User as UserEntity } from '@shared/domain/entity'; -import { cleanupCollections, userFactory } from '@shared/testing'; import { MediaSource } from '@modules/media-source'; import { MediaSourceEntity } from '@modules/media-source/entity'; import { MediaSourceConfigMapper } from '@modules/media-source/repo'; import { - mediaSourceFactory, - mediaSourceEntityFactory, mediaSourceBasicConfigEmbeddableFactory, + mediaSourceEntityFactory, + mediaSourceFactory, mediaSourceOAuthConfigEmbeddableFactory, } from '@modules/media-source/testing'; +import { Test, TestingModule } from '@nestjs/testing'; +import { User as UserEntity } from '@shared/domain/entity'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { userFactory } from '@testing/factory/user.factory'; import { MediaUserLicense } from '../domain'; import { MediaUserLicenseEntity } from '../entity'; import { mediaUserLicenseEntityFactory, mediaUserLicenseFactory } from '../testing'; diff --git a/apps/server/src/modules/user-license/testing/media-user-license-entity.factory.ts b/apps/server/src/modules/user-license/testing/media-user-license-entity.factory.ts index abf8c114b30..5f7d43de33c 100644 --- a/apps/server/src/modules/user-license/testing/media-user-license-entity.factory.ts +++ b/apps/server/src/modules/user-license/testing/media-user-license-entity.factory.ts @@ -1,5 +1,6 @@ -import { BaseFactory, userFactory } from '@shared/testing'; import { mediaSourceEntityFactory } from '@modules/media-source/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { MediaUserLicenseEntity, MediaUserLicenseEntityProps, UserLicenseType } from '../entity'; export const mediaUserLicenseEntityFactory = BaseFactory.define( diff --git a/apps/server/src/modules/user-license/testing/media-user-license.factory.ts b/apps/server/src/modules/user-license/testing/media-user-license.factory.ts index 03f5b4be1e0..8e1cedaf792 100644 --- a/apps/server/src/modules/user-license/testing/media-user-license.factory.ts +++ b/apps/server/src/modules/user-license/testing/media-user-license.factory.ts @@ -1,6 +1,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { BaseFactory } from '@shared/testing'; import { mediaSourceFactory } from '@modules/media-source/testing'; +import { BaseFactory } from '@testing/factory/base.factory'; import { MediaUserLicense, MediaUserLicenseProps } from '../domain'; import { UserLicenseType } from '../entity'; diff --git a/apps/server/src/modules/user-login-migration/controller/api-test/user-login-migration-rollback.api.spec.ts b/apps/server/src/modules/user-login-migration/controller/api-test/user-login-migration-rollback.api.spec.ts index 940d596d9fa..3a2b4c654ad 100644 --- a/apps/server/src/modules/user-login-migration/controller/api-test/user-login-migration-rollback.api.spec.ts +++ b/apps/server/src/modules/user-login-migration/controller/api-test/user-login-migration-rollback.api.spec.ts @@ -5,15 +5,13 @@ import { HttpStatus, INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity, User } from '@shared/domain/entity'; import { UserLoginMigrationEntity } from '@shared/domain/entity/user-login-migration.entity'; -import { - cleanupCollections, - schoolEntityFactory, - systemEntityFactory, - TestApiClient, - UserAndAccountTestFactory, - userLoginMigrationFactory, -} from '@shared/testing'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userLoginMigrationFactory } from '@testing/factory/user-login-migration.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { Response } from 'supertest'; describe('UserLoginMigrationRollbackController (API)', () => { diff --git a/apps/server/src/modules/user-login-migration/controller/api-test/user-login-migration.api.spec.ts b/apps/server/src/modules/user-login-migration/controller/api-test/user-login-migration.api.spec.ts index acfb9c4c0b9..b5c58ecfe4a 100644 --- a/apps/server/src/modules/user-login-migration/controller/api-test/user-login-migration.api.spec.ts +++ b/apps/server/src/modules/user-login-migration/controller/api-test/user-login-migration.api.spec.ts @@ -11,18 +11,16 @@ import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity, User } from '@shared/domain/entity'; import { UserLoginMigrationEntity } from '@shared/domain/entity/user-login-migration.entity'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { - cleanupCollections, - importUserFactory, - JwtTestFactory, - schoolEntityFactory, - systemEntityFactory, - TestApiClient, - UserAndAccountTestFactory, - userFactory, - userLoginMigrationFactory, -} from '@shared/testing'; import { ErrorResponse } from '@src/core/error/dto'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { importUserFactory } from '@testing/factory/import-user.factory'; +import { JwtTestFactory } from '@testing/factory/jwt.test.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userLoginMigrationFactory } from '@testing/factory/user-login-migration.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { UUID } from 'bson'; @@ -47,7 +45,6 @@ jest.mock('jwks-rsa', () => () => { describe('UserLoginMigrationController (API)', () => { let app: INestApplication; let em: EntityManager; - let axiosMock: MockAdapter; let testApiClient: TestApiClient; let configService: ConfigService; @@ -58,7 +55,6 @@ describe('UserLoginMigrationController (API)', () => { imports: [ServerTestModule], }).compile(); - axiosMock = new MockAdapter(axios); app = moduleRef.createNestApplication(); await app.init(); em = app.get(EntityManager); @@ -437,6 +433,8 @@ describe('UserLoginMigrationController (API)', () => { targetUserId: string, officialSchoolNumber: string ) => { + const axiosMock = new MockAdapter(axios); + axiosMock .onPost(targetSystem.oauthConfig?.tokenEndpoint) .replyOnce(200, { diff --git a/apps/server/src/modules/user-login-migration/loggable/debug/school-migration-successful.loggable.spec.ts b/apps/server/src/modules/user-login-migration/loggable/debug/school-migration-successful.loggable.spec.ts index d5e8d7407f6..42be1624fae 100644 --- a/apps/server/src/modules/user-login-migration/loggable/debug/school-migration-successful.loggable.spec.ts +++ b/apps/server/src/modules/user-login-migration/loggable/debug/school-migration-successful.loggable.spec.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@shared/testing'; +import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@testing/factory/domainobject'; import { SchoolMigrationSuccessfulLoggable } from './school-migration-successful.loggable'; describe(SchoolMigrationSuccessfulLoggable.name, () => { diff --git a/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-correction-successful-loggable.spec.ts b/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-correction-successful-loggable.spec.ts index 1fa3c4c37bf..fd8fe76223e 100644 --- a/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-correction-successful-loggable.spec.ts +++ b/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-correction-successful-loggable.spec.ts @@ -1,8 +1,8 @@ -import { UserMigrationCorrectionSuccessfulLoggable } from '@modules/user-login-migration/loggable/debug/user-migration-correction-successful-loggable'; -import { userLoginMigrationDOFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { UserMigrationCorrectionSuccessfulLoggable } from '@modules/user-login-migration/loggable/debug/user-migration-correction-successful-loggable'; import { UserLoginMigrationDO } from '@shared/domain/domainobject'; import { LogMessage } from '@src/core/logger'; +import { userLoginMigrationDOFactory } from '@testing/factory/domainobject'; describe(UserMigrationCorrectionSuccessfulLoggable.name, () => { describe('getLogMessage', () => { diff --git a/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-started.loggable.spec.ts b/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-started.loggable.spec.ts index 22c2ded1b67..93805170941 100644 --- a/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-started.loggable.spec.ts +++ b/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-started.loggable.spec.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { userLoginMigrationDOFactory } from '@shared/testing'; +import { userLoginMigrationDOFactory } from '@testing/factory/domainobject'; import { UserMigrationStartedLoggable } from './user-migration-started.loggable'; describe(UserMigrationStartedLoggable.name, () => { diff --git a/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-successful.loggable.spec.ts b/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-successful.loggable.spec.ts index aae8baf96d9..c695e99585f 100644 --- a/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-successful.loggable.spec.ts +++ b/apps/server/src/modules/user-login-migration/loggable/debug/user-migration-successful.loggable.spec.ts @@ -1,5 +1,5 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { userLoginMigrationDOFactory } from '@shared/testing'; +import { userLoginMigrationDOFactory } from '@testing/factory/domainobject'; import { UserMigrationSuccessfulLoggable } from './user-migration-successful.loggable'; describe(UserMigrationSuccessfulLoggable.name, () => { diff --git a/apps/server/src/modules/user-login-migration/loggable/school-migration-database-operation-failed.loggable-exception.spec.ts b/apps/server/src/modules/user-login-migration/loggable/school-migration-database-operation-failed.loggable-exception.spec.ts index 701b5a6a4fe..b33062b9989 100644 --- a/apps/server/src/modules/user-login-migration/loggable/school-migration-database-operation-failed.loggable-exception.spec.ts +++ b/apps/server/src/modules/user-login-migration/loggable/school-migration-database-operation-failed.loggable-exception.spec.ts @@ -1,4 +1,4 @@ -import { legacySchoolDoFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; import { SchoolMigrationDatabaseOperationFailedLoggableException } from './school-migration-database-operation-failed.loggable-exception'; describe(SchoolMigrationDatabaseOperationFailedLoggableException.name, () => { diff --git a/apps/server/src/modules/user-login-migration/service/migration-check.service.spec.ts b/apps/server/src/modules/user-login-migration/service/migration-check.service.spec.ts index 2bcef2646c6..f03dd85c7ef 100644 --- a/apps/server/src/modules/user-login-migration/service/migration-check.service.spec.ts +++ b/apps/server/src/modules/user-login-migration/service/migration-check.service.spec.ts @@ -4,7 +4,8 @@ import { UserService } from '@modules/user'; import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, UserDO, UserLoginMigrationDO } from '@shared/domain/domainobject'; import { UserLoginMigrationRepo } from '@shared/repo'; -import { legacySchoolDoFactory, userDoFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { MigrationCheckService } from './migration-check.service'; describe('MigrationCheckService', () => { diff --git a/apps/server/src/modules/user-login-migration/service/school-migration.service.spec.ts b/apps/server/src/modules/user-login-migration/service/school-migration.service.spec.ts index 56455c0b90e..12cb3178165 100644 --- a/apps/server/src/modules/user-login-migration/service/school-migration.service.spec.ts +++ b/apps/server/src/modules/user-login-migration/service/school-migration.service.spec.ts @@ -5,8 +5,10 @@ import { UserService } from '@modules/user'; import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, Page, UserDO, UserLoginMigrationDO } from '@shared/domain/domainobject'; import { UserLoginMigrationRepo } from '@shared/repo/userloginmigration/user-login-migration.repo'; -import { legacySchoolDoFactory, setupEntities, userDoFactory, userLoginMigrationDOFactory } from '@shared/testing'; import { LegacyLogger, Logger } from '@src/core/logger'; +import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SchoolMigrationDatabaseOperationFailedLoggableException, SchoolNumberMismatchLoggableException, diff --git a/apps/server/src/modules/user-login-migration/service/user-login-migration-revert.service.spec.ts b/apps/server/src/modules/user-login-migration/service/user-login-migration-revert.service.spec.ts index fd94f69d66e..684cb3ea191 100644 --- a/apps/server/src/modules/user-login-migration/service/user-login-migration-revert.service.spec.ts +++ b/apps/server/src/modules/user-login-migration/service/user-login-migration-revert.service.spec.ts @@ -2,7 +2,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { LegacySchoolService } from '@modules/legacy-school'; import { Test, TestingModule } from '@nestjs/testing'; import { SchoolFeature } from '@shared/domain/types'; -import { userLoginMigrationDOFactory } from '@shared/testing'; +import { userLoginMigrationDOFactory } from '@testing/factory/domainobject'; import { UserLoginMigrationRevertService } from './user-login-migration-revert.service'; import { UserLoginMigrationService } from './user-login-migration.service'; diff --git a/apps/server/src/modules/user-login-migration/service/user-login-migration-rollback.service.spec.ts b/apps/server/src/modules/user-login-migration/service/user-login-migration-rollback.service.spec.ts index e40674c2e10..37c4e2147be 100644 --- a/apps/server/src/modules/user-login-migration/service/user-login-migration-rollback.service.spec.ts +++ b/apps/server/src/modules/user-login-migration/service/user-login-migration-rollback.service.spec.ts @@ -4,9 +4,10 @@ import { Account, AccountService } from '@modules/account'; import { UserService } from '@modules/user'; import { Test, TestingModule } from '@nestjs/testing'; import { UserDO } from '@shared/domain/domainobject'; -import { userDoFactory, userLoginMigrationDOFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; import { accountDoFactory } from '@src/modules/account/testing'; +import { userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { UserLoginMigrationNotFoundLoggableException, UserMigrationRollbackSuccessfulLoggable, diff --git a/apps/server/src/modules/user-login-migration/service/user-login-migration.service.spec.ts b/apps/server/src/modules/user-login-migration/service/user-login-migration.service.spec.ts index d1974552fbe..3faf5748b85 100644 --- a/apps/server/src/modules/user-login-migration/service/user-login-migration.service.spec.ts +++ b/apps/server/src/modules/user-login-migration/service/user-login-migration.service.spec.ts @@ -9,7 +9,8 @@ import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, UserDO, UserLoginMigrationDO } from '@shared/domain/domainobject'; import { EntityId, SchoolFeature } from '@shared/domain/types'; import { UserLoginMigrationRepo } from '@shared/repo'; -import { legacySchoolDoFactory, userDoFactory, userLoginMigrationDOFactory } from '@shared/testing'; +import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { IdenticalUserLoginMigrationSystemLoggableException, MoinSchuleSystemNotFoundLoggableException, diff --git a/apps/server/src/modules/user-login-migration/service/user-migration.service.spec.ts b/apps/server/src/modules/user-login-migration/service/user-migration.service.spec.ts index 747db5cc476..22b634ca537 100644 --- a/apps/server/src/modules/user-login-migration/service/user-migration.service.spec.ts +++ b/apps/server/src/modules/user-login-migration/service/user-migration.service.spec.ts @@ -1,14 +1,17 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { ObjectId } from '@mikro-orm/mongodb'; -import { AccountService, Account } from '@modules/account'; +import { Account, AccountService } from '@modules/account'; import { UserService } from '@modules/user'; import { Test, TestingModule } from '@nestjs/testing'; import { UserDO, UserLoginMigrationDO } from '@shared/domain/domainobject'; -import { roleFactory, setupEntities, userDoFactory, userLoginMigrationDOFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { - UserMigrationDatabaseOperationFailedLoggableException, UserLoginMigrationUserAlreadyMigratedLoggableException, + UserMigrationDatabaseOperationFailedLoggableException, } from '../loggable'; import { UserMigrationService } from './user-migration.service'; diff --git a/apps/server/src/modules/user-login-migration/uc/close-migration-wizard.uc.spec.ts b/apps/server/src/modules/user-login-migration/uc/close-migration-wizard.uc.spec.ts index b8e7b9f589c..cc678c479aa 100644 --- a/apps/server/src/modules/user-login-migration/uc/close-migration-wizard.uc.spec.ts +++ b/apps/server/src/modules/user-login-migration/uc/close-migration-wizard.uc.spec.ts @@ -3,7 +3,10 @@ import { AuthorizationService } from '@modules/authorization'; import { LegacySchoolService } from '@modules/legacy-school'; import { UserImportService } from '@modules/user-import'; import { Test, TestingModule } from '@nestjs/testing'; -import { legacySchoolDoFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ObjectId } from 'bson'; import { CloseMigrationWizardUc } from './close-migration-wizard.uc'; diff --git a/apps/server/src/modules/user-login-migration/uc/close-user-login-migration.uc.spec.ts b/apps/server/src/modules/user-login-migration/uc/close-user-login-migration.uc.spec.ts index ec5dfdd9cf2..5a663fa6e7b 100644 --- a/apps/server/src/modules/user-login-migration/uc/close-user-login-migration.uc.spec.ts +++ b/apps/server/src/modules/user-login-migration/uc/close-user-login-migration.uc.spec.ts @@ -5,7 +5,9 @@ import { LegacySchoolService } from '@modules/legacy-school'; import { Test, TestingModule } from '@nestjs/testing'; import { UserLoginMigrationDO } from '@shared/domain/domainobject'; import { Permission } from '@shared/domain/interface'; -import { legacySchoolDoFactory, setupEntities, userFactory, userLoginMigrationDOFactory } from '@shared/testing'; +import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserLoginMigrationNotFoundLoggableException } from '../loggable'; import { SchoolMigrationService, UserLoginMigrationRevertService, UserLoginMigrationService } from '../service'; import { CloseUserLoginMigrationUc } from './close-user-login-migration.uc'; diff --git a/apps/server/src/modules/user-login-migration/uc/restart-user-login-migration.uc.spec.ts b/apps/server/src/modules/user-login-migration/uc/restart-user-login-migration.uc.spec.ts index 14b05604707..7bbe853c7d5 100644 --- a/apps/server/src/modules/user-login-migration/uc/restart-user-login-migration.uc.spec.ts +++ b/apps/server/src/modules/user-login-migration/uc/restart-user-login-migration.uc.spec.ts @@ -5,8 +5,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { UserLoginMigrationDO } from '@shared/domain/domainobject'; import { User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { setupEntities, userFactory, userLoginMigrationDOFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserLoginMigrationNotFoundLoggableException } from '../loggable'; import { SchoolMigrationService, UserLoginMigrationService } from '../service'; import { RestartUserLoginMigrationUc } from './restart-user-login-migration.uc'; diff --git a/apps/server/src/modules/user-login-migration/uc/start-user-login-migration.uc.spec.ts b/apps/server/src/modules/user-login-migration/uc/start-user-login-migration.uc.spec.ts index 6ddaa59e9d4..f6fea7739ca 100644 --- a/apps/server/src/modules/user-login-migration/uc/start-user-login-migration.uc.spec.ts +++ b/apps/server/src/modules/user-login-migration/uc/start-user-login-migration.uc.spec.ts @@ -6,8 +6,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, UserLoginMigrationDO } from '@shared/domain/domainobject'; import { User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { legacySchoolDoFactory, setupEntities, userFactory, userLoginMigrationDOFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SchoolNumberMissingLoggableException, UserLoginMigrationAlreadyClosedLoggableException } from '../loggable'; import { UserLoginMigrationService } from '../service'; import { StartUserLoginMigrationUc } from './start-user-login-migration.uc'; diff --git a/apps/server/src/modules/user-login-migration/uc/toggle-user-login-migration.uc.spec.ts b/apps/server/src/modules/user-login-migration/uc/toggle-user-login-migration.uc.spec.ts index a970f654d9b..3d7dbcf583c 100644 --- a/apps/server/src/modules/user-login-migration/uc/toggle-user-login-migration.uc.spec.ts +++ b/apps/server/src/modules/user-login-migration/uc/toggle-user-login-migration.uc.spec.ts @@ -1,4 +1,5 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; +import { ObjectId } from '@mikro-orm/mongodb'; import { AuthorizationContextBuilder, AuthorizationService } from '@modules/authorization'; import { LegacySchoolService } from '@modules/legacy-school'; import { ForbiddenException } from '@nestjs/common'; @@ -6,9 +7,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { LegacySchoolDo, UserLoginMigrationDO } from '@shared/domain/domainobject'; import { User } from '@shared/domain/entity'; import { Permission } from '@shared/domain/interface'; -import { legacySchoolDoFactory, setupEntities, userFactory, userLoginMigrationDOFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; -import { ObjectId } from '@mikro-orm/mongodb'; +import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserLoginMigrationNotFoundLoggableException } from '../loggable'; import { UserLoginMigrationService } from '../service'; import { ToggleUserLoginMigrationUc } from './toggle-user-login-migration.uc'; diff --git a/apps/server/src/modules/user-login-migration/uc/user-login-migration-rollback.uc.spec.ts b/apps/server/src/modules/user-login-migration/uc/user-login-migration-rollback.uc.spec.ts index b3497cafdbd..52304c31225 100644 --- a/apps/server/src/modules/user-login-migration/uc/user-login-migration-rollback.uc.spec.ts +++ b/apps/server/src/modules/user-login-migration/uc/user-login-migration-rollback.uc.spec.ts @@ -3,7 +3,8 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { AuthorizationService } from '@modules/authorization'; import { Test, TestingModule } from '@nestjs/testing'; import { Permission } from '@shared/domain/interface'; -import { setupEntities, userFactory } from '@shared/testing'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserLoginMigrationRollbackService } from '../service'; import { UserLoginMigrationRollbackUc } from './user-login-migration-rollback.uc'; diff --git a/apps/server/src/modules/user-login-migration/uc/user-login-migration.uc.spec.ts b/apps/server/src/modules/user-login-migration/uc/user-login-migration.uc.spec.ts index 3d52fb94525..178c25d2460 100644 --- a/apps/server/src/modules/user-login-migration/uc/user-login-migration.uc.spec.ts +++ b/apps/server/src/modules/user-login-migration/uc/user-login-migration.uc.spec.ts @@ -14,16 +14,13 @@ import { LegacySchoolDo, Page, RoleReference, UserDO, UserLoginMigrationDO } fro import { User } from '@shared/domain/entity'; import { Permission, RoleName } from '@shared/domain/interface'; import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; -import { - legacySchoolDoFactory, - schoolEntityFactory, - setupEntities, - systemEntityFactory, - userDoFactory, - userFactory, - userLoginMigrationDOFactory, -} from '@shared/testing'; import { Logger } from '@src/core/logger'; +import { legacySchoolDoFactory, userLoginMigrationDOFactory } from '@testing/factory/domainobject'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { externalUserDtoFactory } from '../../provisioning/testing'; import { ExternalSchoolNumberMissingLoggableException, diff --git a/apps/server/src/modules/user/controller/api-test/admin-api-user.api.spec.ts b/apps/server/src/modules/user/controller/api-test/admin-api-user.api.spec.ts index 3b89aa1eb06..c8447803555 100644 --- a/apps/server/src/modules/user/controller/api-test/admin-api-user.api.spec.ts +++ b/apps/server/src/modules/user/controller/api-test/admin-api-user.api.spec.ts @@ -1,12 +1,12 @@ -import { XApiKeyGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; -import { TestApiClient, schoolEntityFactory } from '@shared/testing'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { AdminApiServerTestModule } from '@src/modules/server/admin-api.server.module'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { nanoid } from 'nanoid'; import { AdminApiUserCreateResponse } from '../dto/admin-api-user-create.response.dto'; @@ -16,20 +16,12 @@ describe('Admin API - Users (API)', () => { let app: INestApplication; let testApiClient: TestApiClient; let em: EntityManager; - const API_KEY = '7ccd4e11-c6f6-48b0-81eb-cccf7922e7a4'; + const API_KEY = 'someotherkey'; beforeAll(async () => { const module: TestingModule = await Test.createTestingModule({ imports: [AdminApiServerTestModule], - }) - .overrideGuard(XApiKeyGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - return req.headers['x-api-key'] === API_KEY; - }, - }) - .compile(); + }).compile(); app = module.createNestApplication(); await app.init(); @@ -45,13 +37,17 @@ describe('Admin API - Users (API)', () => { describe('without token', () => { it('should refuse with wrong token', async () => { const client = new TestApiClient(app, baseRouteName, 'thisisaninvalidapikey', true); + const response = await client.post(''); - expect(response.status).toEqual(403); + + expect(response.status).toEqual(401); }); it('should refuse without token', async () => { const client = new TestApiClient(app, baseRouteName, '', true); + const response = await client.post(''); - expect(response.status).toEqual(403); + + expect(response.status).toEqual(401); }); }); diff --git a/apps/server/src/modules/user/controller/api-test/user-language.api.spec.ts b/apps/server/src/modules/user/controller/api-test/user-language.api.spec.ts index e8d6debf0e1..e227b923d11 100644 --- a/apps/server/src/modules/user/controller/api-test/user-language.api.spec.ts +++ b/apps/server/src/modules/user/controller/api-test/user-language.api.spec.ts @@ -1,133 +1,63 @@ import { EntityManager } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { ServerTestModule } from '@modules/server/server.module'; import { ApiValidationError } from '@shared/common'; import { User } from '@shared/domain/entity'; import { LanguageType } from '@shared/domain/interface'; -import { cleanupCollections, mapUserToCurrentUser, roleFactory, userFactory } from '@shared/testing'; -import { Request } from 'express'; -import request from 'supertest'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; const baseRouteName = '/user/language'; -class API { - app: INestApplication; - - routeName: string; - - constructor(app: INestApplication, routeName: string) { - this.app = app; - this.routeName = routeName; - } - - async patch(language: string) { - const response = await request(this.app.getHttpServer()) - .patch(`${this.routeName}`) - .set('Accept', 'application/json') - .send({ language }); - - return { - result: response.body as boolean, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} - describe(baseRouteName, () => { - describe('with user is not logged in', () => { - let app: INestApplication; - let em: EntityManager; - let api: API; - - beforeAll(async () => { - const module: TestingModule = await Test.createTestingModule({ - imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate() { - return false; - }, - }) - .compile(); - - app = module.createNestApplication(); - await app.init(); - em = module.get(EntityManager); - api = new API(app, baseRouteName); - }); - - afterAll(async () => { - await app.close(); - }); - - beforeEach(async () => { - await cleanupCollections(em); - - const roles = roleFactory.buildList(1, { permissions: [] }); - const user = userFactory.build({ roles }); + let app: INestApplication; + let em: EntityManager; + let apiClient: TestApiClient; + + beforeAll(async () => { + const module: TestingModule = await Test.createTestingModule({ + imports: [ServerTestModule], + }).compile(); + + app = module.createNestApplication(); + await app.init(); + em = module.get(EntityManager); + apiClient = new TestApiClient(app, baseRouteName); + }); - await em.persistAndFlush([user]); - em.clear(); - }); + afterAll(async () => { + await app.close(); + }); - it('should return status 403', async () => { - const response = await api.patch(LanguageType.DE); + describe('when user is not logged in', () => { + it('should return status 401', async () => { + const response = await apiClient.patch(undefined, LanguageType.DE); - expect(response.status).toEqual(403); + expect(response.status).toEqual(401); }); }); describe('with bad request data', () => { - let app: INestApplication; - let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; - - beforeAll(async () => { - const module: TestingModule = await Test.createTestingModule({ - imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); - - app = module.createNestApplication(); - await app.init(); - em = module.get(EntityManager); - api = new API(app, baseRouteName); - }); - - afterAll(async () => { - await app.close(); - }); + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); - beforeEach(async () => { - await cleanupCollections(em); - - const roles = roleFactory.buildList(1, { permissions: [] }); - const user = userFactory.build({ roles }); - - await em.persistAndFlush([user]); + await em.persistAndFlush([teacherAccount, teacherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - }); + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient }; + }; it('should throw an validation error is not supported language is passed.', async () => { - const response = await api.patch('super'); + const { loggedInClient } = await setup(); - expect(response.error.validationErrors).toEqual([ + const result = await loggedInClient.patch(undefined, 'super'); + const response = result.body as ApiValidationError; + + expect(response.validationErrors).toEqual([ { errors: ['language must be one of the following values: de, en, es, uk'], field: ['language'], @@ -136,73 +66,52 @@ describe(baseRouteName, () => { }); }); - describe('without valid request data', () => { - let app: INestApplication; - let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; - - beforeAll(async () => { - const module: TestingModule = await Test.createTestingModule({ - imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); - - app = module.createNestApplication(); - await app.init(); - em = module.get(EntityManager); - api = new API(app, baseRouteName); - }); - - afterAll(async () => { - await app.close(); - }); - - beforeEach(async () => { - await cleanupCollections(em); - - const roles = roleFactory.buildList(1, { permissions: [] }); - const user = userFactory.build({ roles, language: LanguageType.DE }); + describe('with valid request data', () => { + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher({ language: LanguageType.DE }); - await em.persistAndFlush([user]); + await em.persistAndFlush([teacherAccount, teacherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - }); + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, teacherUser }; + }; it('should return status 200 for successful request.', async () => { - const response = await api.patch(LanguageType.EN); + const { loggedInClient } = await setup(); + + const response = await loggedInClient.patch(undefined, { language: LanguageType.EN }); expect(response.status).toEqual(200); }); it('should return successful true.', async () => { - const response = await api.patch(LanguageType.EN); + const { loggedInClient } = await setup(); + + const result = await loggedInClient.patch(undefined, { language: LanguageType.EN }); + const response = result.body as { successful: boolean }; - expect(response.result).toEqual({ successful: true }); + expect(response).toEqual({ successful: true }); }); it('should change the language', async () => { - await api.patch(LanguageType.EN); + const { loggedInClient, teacherUser } = await setup(); - const user = await em.findOne(User, { id: currentUser.userId }); + await loggedInClient.patch(undefined, { language: LanguageType.EN }); + + const user = await em.findOne(User, { id: teacherUser.id }); expect(user?.language).toEqual('en'); }); it('should support de, en, es, ua', async () => { - const de = await api.patch(LanguageType.DE); - const en = await api.patch(LanguageType.EN); - const es = await api.patch(LanguageType.ES); - const ua = await api.patch(LanguageType.UK); + const { loggedInClient } = await setup(); + + const de = await loggedInClient.patch(undefined, { language: LanguageType.DE }); + const en = await loggedInClient.patch(undefined, { language: LanguageType.EN }); + const es = await loggedInClient.patch(undefined, { language: LanguageType.ES }); + const ua = await loggedInClient.patch(undefined, { language: LanguageType.UK }); expect(de.status).toEqual(200); expect(en.status).toEqual(200); diff --git a/apps/server/src/modules/user/controller/api-test/user-me.api.spec.ts b/apps/server/src/modules/user/controller/api-test/user-me.api.spec.ts index df8e9d588f7..9459a503184 100644 --- a/apps/server/src/modules/user/controller/api-test/user-me.api.spec.ts +++ b/apps/server/src/modules/user/controller/api-test/user-me.api.spec.ts @@ -1,142 +1,73 @@ -import { MikroORM } from '@mikro-orm/core'; import { EntityManager } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; -import { Request } from 'express'; -import request from 'supertest'; -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { ServerTestModule } from '@modules/server/server.module'; -import { ResolvedUserResponse } from '@modules/user/controller/dto'; -import { ApiValidationError } from '@shared/common'; -import { LanguageType } from '@shared/domain/interface'; -import { cleanupCollections, mapUserToCurrentUser, roleFactory, userFactory } from '@shared/testing'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { TestApiClient } from '@testing/test-api-client'; -const baseRouteName = '/user/me'; - -class API { - app: INestApplication; - - routeName: string; - - constructor(app: INestApplication, routeName: string) { - this.app = app; - this.routeName = routeName; - } - - async me() { - const response = await request(this.app.getHttpServer()).get(this.routeName).set('Accept', 'application/json'); - - return { - result: response.body as ResolvedUserResponse, - error: response.body as ApiValidationError, - status: response.status, - }; - } -} +const baseRouteName = '/user'; describe(baseRouteName, () => { - describe('with user is not logged in', () => { - let app: INestApplication; - let em: EntityManager; - let api: API; - - beforeAll(async () => { - const module: TestingModule = await Test.createTestingModule({ - imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate() { - return false; - }, - }) - .compile(); - - app = module.createNestApplication(); - await app.init(); - em = module.get(EntityManager); - api = new API(app, baseRouteName); - }); - - afterAll(async () => { - await app.close(); - }); - - beforeEach(async () => { - await cleanupCollections(em); - - const roles = roleFactory.buildList(1, { permissions: [] }); - const user = userFactory.build({ roles }); + let app: INestApplication; + let em: EntityManager; + let apiClient: TestApiClient; + + beforeAll(async () => { + const module: TestingModule = await Test.createTestingModule({ + imports: [ServerTestModule], + }).compile(); + + app = module.createNestApplication(); + await app.init(); + em = module.get(EntityManager); + apiClient = new TestApiClient(app, baseRouteName); + }); - await em.persistAndFlush([user]); - em.clear(); - }); + afterAll(async () => { + await app.close(); + }); - it('should return status 403', async () => { - const response = await api.me(); + describe('with user is not logged in', () => { + it('should return status 401', async () => { + const response = await apiClient.get('/me'); - expect(response.status).toEqual(403); + expect(response.status).toEqual(401); }); }); - describe('without bad request data', () => {}); - describe('without valid request data', () => { - let app: INestApplication; - let orm: MikroORM; - let em: EntityManager; - let currentUser: ICurrentUser; - let api: API; - - beforeAll(async () => { - const module: TestingModule = await Test.createTestingModule({ - imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); - - app = module.createNestApplication(); - await app.init(); - orm = app.get(MikroORM); - em = module.get(EntityManager); - api = new API(app, baseRouteName); - }); - - afterAll(async () => { - await orm.close(); - await app.close(); - }); + const setup = async () => { + const { teacherAccount, teacherUser } = UserAndAccountTestFactory.buildTeacher(); - beforeEach(async () => { - await cleanupCollections(em); - - const roles = roleFactory.buildList(1, { permissions: [] }); - const user = userFactory.build({ roles, language: LanguageType.DE }); - - await em.persistAndFlush([user]); + await em.persistAndFlush([teacherAccount, teacherUser]); em.clear(); - currentUser = mapUserToCurrentUser(user); - }); + const loggedInClient = await apiClient.login(teacherAccount); + + return { loggedInClient, teacherUser }; + }; it('should return status 200 for successful request.', async () => { - const response = await api.me(); + const { loggedInClient } = await setup(); + + const response = await loggedInClient.get('/me'); - expect(response.status).toEqual(200); + expect(response.statusCode).toEqual(200); }); it('should return ResolvedUserResponse.', async () => { - const response = await api.me(); + const { loggedInClient, teacherUser } = await setup(); + + const response = await loggedInClient.get('/me'); - expect(response.result.id).toEqual(currentUser.userId); + expect(response.body).toMatchObject({ + id: teacherUser.id, + firstName: teacherUser.firstName, + lastName: teacherUser.lastName, + permissions: teacherUser.resolvePermissions(), + schoolId: teacherUser.school.id, + }); }); }); }); diff --git a/apps/server/src/modules/user/legacy/controller/api-test/admin-api-students.api.spec.ts b/apps/server/src/modules/user/legacy/controller/api-test/admin-api-students.api.spec.ts index adc58ec3839..236965a6514 100644 --- a/apps/server/src/modules/user/legacy/controller/api-test/admin-api-students.api.spec.ts +++ b/apps/server/src/modules/user/legacy/controller/api-test/admin-api-students.api.spec.ts @@ -1,23 +1,16 @@ -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; -import { EntityManager } from '@mikro-orm/core'; -import { ObjectId } from '@mikro-orm/mongodb'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { EntityManager } from '@mikro-orm/mongodb'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; -import { Permission, RoleName } from '@shared/domain/interface'; -import { - mapUserToCurrentUser, - roleFactory, - schoolEntityFactory, - schoolYearFactory, - userFactory, -} from '@shared/testing'; -import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; +import { RoleName } from '@shared/domain/interface'; import { accountFactory } from '@src/modules/account/testing'; import { ServerTestModule } from '@src/modules/server/server.module'; -import { Request } from 'express'; -import request from 'supertest'; -import { classEntityFactory } from '../../../../class/entity/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { UserListResponse, UserResponse, UsersSearchQueryParams } from '../dto'; describe('Users Admin Students Controller (API)', () => { @@ -25,116 +18,62 @@ describe('Users Admin Students Controller (API)', () => { let app: INestApplication; let em: EntityManager; + let apiClient: TestApiClient; - let adminAccount: AccountEntity; - let studentAccount1: AccountEntity; - let studentAccount2: AccountEntity; - - let adminUser: User; let studentUser1: User; let studentUser2: User; + let loggedInAdminClient: TestApiClient; + let loggedInStudentClient: TestApiClient; - let currentUser: ICurrentUser; - - const defaultPasswordHash = '$2a$10$/DsztV5o6P5piW2eWJsxw.4nHovmJGBA.QNwiTmuZ/uvUc40b.Uhu'; - - const setupDb = async () => { + const setup = async () => { const currentYear = schoolYearFactory.withStartYear(2002).buildWithId(); const school = schoolEntityFactory.buildWithId({ currentYear }); + const studentRole = roleFactory.buildWithId({ name: RoleName.STUDENT, permissions: [] }); - const adminRoles = roleFactory.build({ - name: RoleName.ADMINISTRATOR, - permissions: [Permission.STUDENT_LIST], - }); - const studentRoles = roleFactory.build({ name: RoleName.STUDENT, permissions: [] }); + const { adminAccount, adminUser } = UserAndAccountTestFactory.buildAdmin({ school }); + studentUser1 = userFactory.withRole(studentRole).buildWithId({ school }); - adminUser = userFactory.buildWithId({ school, roles: [adminRoles] }); - studentUser1 = userFactory.buildWithId({ - firstName: 'Marla', - school, - roles: [studentRoles], - consent: { - userConsent: { - form: 'digital', - privacyConsent: true, - termsOfUseConsent: true, - dateOfPrivacyConsent: new Date('2017-01-01T00:06:37.148Z'), - dateOfTermsOfUseConsent: new Date('2017-01-01T00:06:37.148Z'), - }, - parentConsents: [ - { - _id: new ObjectId('5fa31aacb229544f2c697b48'), - form: 'digital', - privacyConsent: true, - termsOfUseConsent: true, - dateOfPrivacyConsent: new Date('2017-01-01T00:06:37.148Z'), - dateOfTermsOfUseConsent: new Date('2017-01-01T00:06:37.148Z'), - }, - ], - }, - }); + const studentAccount1 = accountFactory.withUser(studentUser1).build(); + studentUser2 = userFactory.withRole(studentRole).buildWithId({ school }); - studentUser2 = userFactory.buildWithId({ - firstName: 'Test', + await em.persistAndFlush([ + studentRole, school, - roles: [studentRoles], - consent: { - userConsent: { - form: 'digital', - privacyConsent: true, - termsOfUseConsent: true, - dateOfPrivacyConsent: new Date('2017-01-01T00:06:37.148Z'), - dateOfTermsOfUseConsent: new Date('2017-01-01T00:06:37.148Z'), - }, - }, - }); - - const studentClass = classEntityFactory.buildWithId({ - name: 'Group A', - schoolId: school.id, - year: currentYear.id, - userIds: [studentUser1._id], - gradeLevel: 12, - }); + currentYear, + adminAccount, + adminUser, + studentUser1, + studentAccount1, + studentUser2, + ]); + em.clear(); - const mapUserToAccount = (user: User): AccountEntity => - accountFactory.buildWithId({ - userId: user.id, - username: user.email, - password: defaultPasswordHash, - }); - adminAccount = mapUserToAccount(adminUser); - studentAccount1 = mapUserToAccount(studentUser1); - studentAccount2 = mapUserToAccount(studentUser2); - - em.persist(school); - em.persist(currentYear); - em.persist([adminRoles, studentRoles]); - em.persist([adminUser, studentUser1, studentUser2]); - em.persist([adminAccount, studentAccount1, studentAccount2]); - em.persist(studentClass); - await em.flush(); + loggedInAdminClient = await apiClient.login(adminAccount); + loggedInStudentClient = await apiClient.login(studentAccount1); + + return { + adminUser, + adminAccount, + studentUser1, + studentAccount1, + studentUser2, + loggedInAdminClient, + loggedInStudentClient, + }; }; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); + }).compile(); app = moduleFixture.createNestApplication(); await app.init(); em = app.get(EntityManager); - await setupDb(); + apiClient = new TestApiClient(app, basePath); + + await setup(); }); afterAll(async () => { @@ -144,15 +83,8 @@ describe('Users Admin Students Controller (API)', () => { describe('[GET] :id', () => { describe('when student exists', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(adminUser, adminAccount); - }; - it('should return student ', async () => { - setup(); - const response = await request(app.getHttpServer()) // - .get(`${basePath}/${studentUser1.id}`) - .expect(200); + const response = await loggedInAdminClient.get(studentUser1.id).expect(200); // eslint-disable-next-line @typescript-eslint/naming-convention const { _id } = response.body as UserResponse; @@ -162,54 +94,27 @@ describe('Users Admin Students Controller (API)', () => { }); describe('when user has no right permission', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(studentUser1, studentAccount1); - }; - it('should reject request', async () => { - setup(); - await request(app.getHttpServer()) // - .get(`${basePath}/${studentUser1.id}`) - .expect(403); + await loggedInStudentClient.get(studentUser1.id).expect(403); }); }); describe('when student does not exists', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(adminUser, adminAccount); - }; - it('should reject request ', async () => { - setup(); - await request(app.getHttpServer()) // - .get(`${basePath}/000000000000000000000000`) - .expect(404); + await loggedInAdminClient.get(`000000000000000000000000`).expect(404); }); }); }); describe('[GET]', () => { describe('when sort param is provided', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(adminUser, adminAccount); + it('should return students in correct order', async () => { const query: UsersSearchQueryParams = { $skip: 0, $limit: 5, $sort: { firstName: 1 }, }; - - return { - query, - }; - }; - - it('should return students in correct order', async () => { - const { query } = setup(); - const response = await request(app.getHttpServer()) // - .get(`${basePath}`) - .query(query) - .set('Accept', 'application/json') - .expect(200); + const response = await loggedInAdminClient.get().query(query).expect(200); const { data, total } = response.body as UserListResponse; @@ -221,26 +126,14 @@ describe('Users Admin Students Controller (API)', () => { }); describe('when sorting by classes', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(adminUser, adminAccount); + it('should return students', async () => { const query: UsersSearchQueryParams = { $skip: 0, $limit: 5, $sort: { classes: 1 }, }; - return { - query, - }; - }; - - it('should return students', async () => { - const { query } = setup(); - const response = await request(app.getHttpServer()) // - .get(`${basePath}`) - .query(query) - .set('Accept', 'application/json') - .expect(200); + const response = await loggedInAdminClient.get().query(query).expect(200); const { data, total } = response.body as UserListResponse; @@ -250,26 +143,13 @@ describe('Users Admin Students Controller (API)', () => { }); describe('when sorting by consentStatus', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(adminUser, adminAccount); + it('should return students', async () => { const query: UsersSearchQueryParams = { $skip: 0, $limit: 5, $sort: { consentStatus: 1 }, }; - - return { - query, - }; - }; - - it('should return students', async () => { - const { query } = setup(); - const response = await request(app.getHttpServer()) // - .get(`${basePath}`) - .query(query) - .set('Accept', 'application/json') - .expect(200); + const response = await loggedInAdminClient.get().query(query).expect(200); const { data, total } = response.body as UserListResponse; @@ -279,27 +159,14 @@ describe('Users Admin Students Controller (API)', () => { }); describe('when searching for users by wrong params', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(adminUser, adminAccount); + it('should return empty list', async () => { const query: UsersSearchQueryParams = { $skip: 0, $limit: 5, $sort: { firstName: 1 }, classes: ['1A'], }; - - return { - query, - }; - }; - - it('should return empty list', async () => { - const { query } = setup(); - const response = await request(app.getHttpServer()) // - .get(`${basePath}`) - .query(query) - .set('Accept', 'application/json') - .expect(200); + const response = await loggedInAdminClient.get().query(query).expect(200); const { data, total } = response.body as UserListResponse; @@ -309,26 +176,14 @@ describe('Users Admin Students Controller (API)', () => { }); describe('when user has no right permission', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(studentUser1, studentAccount1); + it('should reject request', async () => { const query: UsersSearchQueryParams = { $skip: 0, $limit: 5, $sort: { firstName: 1 }, }; - return { - query, - }; - }; - - it('should reject request', async () => { - const { query } = setup(); - await request(app.getHttpServer()) // - .get(`${basePath}`) - .query(query) - .send() - .expect(403); + await loggedInStudentClient.get().query(query).send().expect(403); }); }); }); diff --git a/apps/server/src/modules/user/legacy/controller/api-test/admin-api-teachers.api.spec.ts b/apps/server/src/modules/user/legacy/controller/api-test/admin-api-teachers.api.spec.ts index dec6fcf809d..0e52967dbe0 100644 --- a/apps/server/src/modules/user/legacy/controller/api-test/admin-api-teachers.api.spec.ts +++ b/apps/server/src/modules/user/legacy/controller/api-test/admin-api-teachers.api.spec.ts @@ -1,21 +1,16 @@ -import { ICurrentUser, JwtAuthGuard } from '@infra/auth-guard'; import { EntityManager } from '@mikro-orm/core'; -import { ExecutionContext, INestApplication } from '@nestjs/common'; +import { INestApplication } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; -import { Permission, RoleName } from '@shared/domain/interface'; -import { - mapUserToCurrentUser, - roleFactory, - schoolEntityFactory, - schoolYearFactory, - userFactory, -} from '@shared/testing'; -import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; +import { RoleName } from '@shared/domain/interface'; import { accountFactory } from '@src/modules/account/testing'; import { ServerTestModule } from '@src/modules/server/server.module'; -import { Request } from 'express'; -import request from 'supertest'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { TestApiClient } from '@testing/test-api-client'; import { UserListResponse, UserResponse, UsersSearchQueryParams } from '../dto'; describe('Users Admin Teachers Controller (API)', () => { @@ -23,81 +18,61 @@ describe('Users Admin Teachers Controller (API)', () => { let app: INestApplication; let em: EntityManager; + let apiClient: TestApiClient; - let adminAccount: AccountEntity; - let teacherAccount1: AccountEntity; - let teacherAccount2: AccountEntity; - - let adminUser: User; let teacherUser1: User; let teacherUser2: User; + let loggedInAdminClient: TestApiClient; + let loggedInTeacherClient: TestApiClient; - let currentUser: ICurrentUser; - - const defaultPasswordHash = '$2a$10$/DsztV5o6P5piW2eWJsxw.4nHovmJGBA.QNwiTmuZ/uvUc40b.Uhu'; - - const setupDb = async () => { + const setup = async () => { const currentYear = schoolYearFactory.withStartYear(2002).buildWithId(); const school = schoolEntityFactory.buildWithId({ currentYear }); - const adminRoles = roleFactory.build({ - name: RoleName.ADMINISTRATOR, - permissions: [Permission.TEACHER_LIST], - }); - const teacherRoles = roleFactory.build({ name: RoleName.TEACHER, permissions: [] }); + const { adminAccount, adminUser } = UserAndAccountTestFactory.buildAdmin({ school }); - adminUser = userFactory.buildWithId({ school, roles: [adminRoles] }); - teacherUser1 = userFactory.buildWithId({ - firstName: 'Marla', - school, - roles: [teacherRoles], - consent: {}, - }); + const teacherRole = roleFactory.buildWithId({ name: RoleName.TEACHER, permissions: [] }); + teacherUser1 = userFactory.withRole(teacherRole).buildWithId({ school }); + const teacherAccount1 = accountFactory.withUser(teacherUser1).build(); - teacherUser2 = userFactory.buildWithId({ - firstName: 'Test', + teacherUser2 = userFactory.withRole(teacherRole).buildWithId({ school }); + + await em.persistAndFlush([ + currentYear, school, - roles: [teacherRoles], - consent: {}, - }); + adminAccount, + adminUser, + teacherUser1, + teacherAccount1, + teacherUser2, + ]); + em.clear(); - const mapUserToAccount = (user: User): AccountEntity => - accountFactory.buildWithId({ - userId: user.id, - username: user.email, - password: defaultPasswordHash, - }); - adminAccount = mapUserToAccount(adminUser); - teacherAccount1 = mapUserToAccount(teacherUser1); - teacherAccount2 = mapUserToAccount(teacherUser2); - - em.persist(school); - em.persist(currentYear); - em.persist([adminRoles, teacherRoles]); - em.persist([adminUser, teacherUser1, teacherUser2]); - em.persist([adminAccount, teacherAccount1, teacherAccount2]); - await em.flush(); + loggedInAdminClient = await apiClient.login(adminAccount); + loggedInTeacherClient = await apiClient.login(teacherAccount1); + + return { + adminUser, + adminAccount, + teacherUser1, + teacherAccount1, + teacherUser2, + loggedInAdminClient, + loggedInTeacherClient, + }; }; beforeAll(async () => { const moduleFixture: TestingModule = await Test.createTestingModule({ imports: [ServerTestModule], - }) - .overrideGuard(JwtAuthGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.user = currentUser; - return true; - }, - }) - .compile(); + }).compile(); app = moduleFixture.createNestApplication(); await app.init(); em = app.get(EntityManager); + apiClient = new TestApiClient(app, basePath); - await setupDb(); + await setup(); }); afterAll(async () => { @@ -107,15 +82,8 @@ describe('Users Admin Teachers Controller (API)', () => { describe('[GET] :id', () => { describe('when teacher exists', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(adminUser, adminAccount); - }; - it('should return teacher ', async () => { - setup(); - const response = await request(app.getHttpServer()) // - .get(`${basePath}/${teacherUser1.id}`) - .expect(200); + const response = await loggedInAdminClient.get(teacherUser1.id).expect(200); // eslint-disable-next-line @typescript-eslint/naming-convention const { _id } = response.body as UserResponse; @@ -125,54 +93,32 @@ describe('Users Admin Teachers Controller (API)', () => { }); describe('when user has no right permission', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(teacherUser1, teacherAccount1); - }; - it('should reject request', async () => { - setup(); - await request(app.getHttpServer()) // - .get(`${basePath}/${teacherUser1.id}`) - .expect(403); + const response = await loggedInTeacherClient.get(teacherUser1.id); + + expect(response.status).toBe(403); }); }); describe('when teacher does not exists', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(adminUser, adminAccount); - }; - it('should reject request ', async () => { - setup(); - await request(app.getHttpServer()) // - .get(`${basePath}/000000000000000000000000`) - .expect(404); + const response = await loggedInAdminClient.get('000000000000000000000000'); + + expect(response.status).toBe(404); }); }); }); describe('[GET]', () => { describe('when sort param is provided', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(adminUser, adminAccount); + it('should return teachers in correct order', async () => { const query: UsersSearchQueryParams = { $skip: 0, $limit: 5, $sort: { firstName: 1 }, }; - return { - query, - }; - }; - - it('should return teachers in correct order', async () => { - const { query } = setup(); - const response = await request(app.getHttpServer()) // - .get(`${basePath}`) - .query(query) - .set('Accept', 'application/json') - .expect(200); + const response = await loggedInAdminClient.get('').query(query).set('Accept', 'application/json').expect(200); const { data, total } = response.body as UserListResponse; @@ -182,27 +128,16 @@ describe('Users Admin Teachers Controller (API)', () => { expect(data[1]._id).toBe(teacherUser2._id.toString()); }); }); + describe('when user has no right permission', () => { - const setup = () => { - currentUser = mapUserToCurrentUser(teacherUser1, teacherAccount1); + it('should reject request', async () => { const query: UsersSearchQueryParams = { $skip: 0, $limit: 5, $sort: { firstName: 1 }, }; - return { - query, - }; - }; - - it('should reject request', async () => { - const { query } = setup(); - await request(app.getHttpServer()) // - .get(`${basePath}`) - .query(query) - .send() - .expect(403); + await loggedInTeacherClient.get('').query(query).send().expect(403); }); }); }); diff --git a/apps/server/src/modules/user/legacy/repo/users-admin.repo.spec.ts b/apps/server/src/modules/user/legacy/repo/users-admin.repo.spec.ts index dd678250dc0..55e9f6915b3 100644 --- a/apps/server/src/modules/user/legacy/repo/users-admin.repo.spec.ts +++ b/apps/server/src/modules/user/legacy/repo/users-admin.repo.spec.ts @@ -4,9 +4,12 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { Role, SchoolEntity, SchoolYearEntity, User } from '@shared/domain/entity'; import { Permission, RoleName } from '@shared/domain/interface'; -import { roleFactory, schoolEntityFactory, schoolYearFactory, userFactory } from '@shared/testing'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { accountFactory } from '@src/modules/account/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { classEntityFactory } from '../../../class/entity/testing'; import { UserListResponse, UserResponse, UsersSearchQueryParams } from '../controller/dto'; import { UsersAdminRepo } from './users-admin.repo'; diff --git a/apps/server/src/modules/user/loggable/addSecondarySchoolToUserErrorLoggableException.spec.ts b/apps/server/src/modules/user/loggable/addSecondarySchoolToUserErrorLoggableException.spec.ts index ca66771b8cc..c06f6630104 100644 --- a/apps/server/src/modules/user/loggable/addSecondarySchoolToUserErrorLoggableException.spec.ts +++ b/apps/server/src/modules/user/loggable/addSecondarySchoolToUserErrorLoggableException.spec.ts @@ -1,4 +1,4 @@ -import { roleFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; import { AddSecondarySchoolToUsersRoleErrorLoggableException } from './addSecondarySchoolToUserError.loggable'; describe('AddSecondarySchoolToUsersRoleErrorLoggableException', () => { diff --git a/apps/server/src/modules/user/mapper/resolved-user.mapper.spec.ts b/apps/server/src/modules/user/mapper/resolved-user.mapper.spec.ts index bafc0afd142..fe0dc9affa4 100644 --- a/apps/server/src/modules/user/mapper/resolved-user.mapper.spec.ts +++ b/apps/server/src/modules/user/mapper/resolved-user.mapper.spec.ts @@ -1,6 +1,8 @@ -import { userFactory, roleFactory, setupEntities } from '@shared/testing'; -import { ResolvedUserMapper } from './resolved-user.mapper'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ResolvedUserResponse } from '../controller/dto'; +import { ResolvedUserMapper } from './resolved-user.mapper'; describe('ResolvedUserMapper', () => { beforeAll(async () => { diff --git a/apps/server/src/modules/user/mapper/user.mapper.spec.ts b/apps/server/src/modules/user/mapper/user.mapper.spec.ts index afc6ff1e655..eafa882b643 100644 --- a/apps/server/src/modules/user/mapper/user.mapper.spec.ts +++ b/apps/server/src/modules/user/mapper/user.mapper.spec.ts @@ -1,7 +1,9 @@ import { UserMapper } from '@modules/user/mapper/user.mapper'; import { UserDto } from '@modules/user/uc/dto/user.dto'; import { User } from '@shared/domain/entity'; -import { roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; describe('UserMapper', () => { let userEntity: User; diff --git a/apps/server/src/modules/user/service/user.service.spec.ts b/apps/server/src/modules/user/service/user.service.spec.ts index ec71f6a8486..aa58e05903f 100644 --- a/apps/server/src/modules/user/service/user.service.spec.ts +++ b/apps/server/src/modules/user/service/user.service.spec.ts @@ -24,9 +24,12 @@ import { IFindOptions, LanguageType, Permission, RoleName, SortOrder } from '@sh import { EntityId } from '@shared/domain/types'; import { UserRepo } from '@shared/repo'; import { UserDORepo } from '@shared/repo/user/user-do.repo'; -import { roleFactory, setupEntities, userDoFactory, userFactory } from '@shared/testing'; import { Logger } from '@src/core/logger'; import { schoolFactory } from '@src/modules/school/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserDto } from '../uc/dto/user.dto'; import { UserDiscoverableQuery, UserQuery } from './user-query.type'; import { UserService } from './user.service'; diff --git a/apps/server/src/modules/user/uc/admin-api-user.uc.spec.ts b/apps/server/src/modules/user/uc/admin-api-user.uc.spec.ts index da8bb777ae4..930769eeabe 100644 --- a/apps/server/src/modules/user/uc/admin-api-user.uc.spec.ts +++ b/apps/server/src/modules/user/uc/admin-api-user.uc.spec.ts @@ -2,9 +2,11 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { AccountService } from '@modules/account'; import { Test, TestingModule } from '@nestjs/testing'; import { RoleName } from '@shared/domain/interface'; -import { roleFactory, setupEntities, userDoFactory } from '@shared/testing'; import { accountDoFactory } from '@src/modules/account/testing'; import { RoleService } from '@src/modules/role'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserService } from '../service/user.service'; import { AdminApiUserUc } from './admin-api-user.uc'; diff --git a/apps/server/src/modules/user/uc/user.uc.spec.ts b/apps/server/src/modules/user/uc/user.uc.spec.ts index 0bdd80a99f1..662f5decaf5 100644 --- a/apps/server/src/modules/user/uc/user.uc.spec.ts +++ b/apps/server/src/modules/user/uc/user.uc.spec.ts @@ -6,7 +6,9 @@ import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; import { LanguageType, Permission } from '@shared/domain/interface'; import { UserRepo } from '@shared/repo'; -import { roleFactory, setupEntities, userFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { UserUc } from './user.uc'; describe('UserUc', () => { diff --git a/apps/server/src/modules/video-conference/bbb/bbb.service.spec.ts b/apps/server/src/modules/video-conference/bbb/bbb.service.spec.ts index 258f06f10c6..13073e45310 100644 --- a/apps/server/src/modules/video-conference/bbb/bbb.service.spec.ts +++ b/apps/server/src/modules/video-conference/bbb/bbb.service.spec.ts @@ -3,8 +3,8 @@ import { HttpService } from '@nestjs/axios'; import { InternalServerErrorException } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { Test, TestingModule } from '@nestjs/testing'; -import { axiosResponseFactory } from '@shared/testing'; import { ErrorUtils } from '@src/core/error/utils'; +import { axiosResponseFactory } from '@testing/factory/axios-response.factory'; import { AxiosResponse } from 'axios'; import crypto, { Hash } from 'crypto'; import { of } from 'rxjs'; diff --git a/apps/server/src/modules/video-conference/controller/api-test/video-conference-course.api.spec.ts b/apps/server/src/modules/video-conference/controller/api-test/video-conference-course.api.spec.ts index b7c8ca7c4bc..e3d619c969d 100644 --- a/apps/server/src/modules/video-conference/controller/api-test/video-conference-course.api.spec.ts +++ b/apps/server/src/modules/video-conference/controller/api-test/video-conference-course.api.spec.ts @@ -5,18 +5,16 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Course, Role, SchoolEntity, TargetModels, User, VideoConference } from '@shared/domain/entity'; import { Permission, RoleName, VideoConferenceScope } from '@shared/domain/interface'; import { SchoolFeature } from '@shared/domain/types'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - courseFactory, - roleFactory, - schoolEntityFactory, - userFactory, -} from '@shared/testing'; -import { videoConferenceFactory } from '@shared/testing/factory/video-conference.factory'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { accountFactory } from '@src/modules/account/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { videoConferenceFactory } from '@testing/factory/video-conference.factory'; +import { TestApiClient } from '@testing/test-api-client'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { Response } from 'supertest'; diff --git a/apps/server/src/modules/video-conference/controller/api-test/video-conference-room.api.spec.ts b/apps/server/src/modules/video-conference/controller/api-test/video-conference-room.api.spec.ts index a9eae2a7741..1af5337bdd7 100644 --- a/apps/server/src/modules/video-conference/controller/api-test/video-conference-room.api.spec.ts +++ b/apps/server/src/modules/video-conference/controller/api-test/video-conference-room.api.spec.ts @@ -5,23 +5,21 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Role, SchoolEntity, TargetModels, User, VideoConference } from '@shared/domain/entity'; import { Permission, RoleName, VideoConferenceScope } from '@shared/domain/interface'; import { SchoolFeature } from '@shared/domain/types'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, - userFactory, -} from '@shared/testing'; -import { videoConferenceFactory } from '@shared/testing/factory/video-conference.factory'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { accountFactory } from '@src/modules/account/testing'; +import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; +import { roomEntityFactory } from '@src/modules/room/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { videoConferenceFactory } from '@testing/factory/video-conference.factory'; +import { TestApiClient } from '@testing/test-api-client'; import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import { Response } from 'supertest'; -import { roomEntityFactory } from '@src/modules/room/testing'; -import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; import { VideoConferenceCreateParams, VideoConferenceJoinResponse } from '../dto'; describe('VideoConferenceController (API)', () => { diff --git a/apps/server/src/modules/video-conference/controller/api-test/video-conference-video-conference-element.api.spec.ts b/apps/server/src/modules/video-conference/controller/api-test/video-conference-video-conference-element.api.spec.ts index a622a760219..37c2323b3c7 100644 --- a/apps/server/src/modules/video-conference/controller/api-test/video-conference-video-conference-element.api.spec.ts +++ b/apps/server/src/modules/video-conference/controller/api-test/video-conference-video-conference-element.api.spec.ts @@ -5,30 +5,28 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Role, SchoolEntity, TargetModels, User, VideoConference } from '@shared/domain/entity'; import { Permission, RoleName, VideoConferenceScope } from '@shared/domain/interface'; import { SchoolFeature } from '@shared/domain/types'; -import { - TestApiClient, - UserAndAccountTestFactory, - cleanupCollections, - groupEntityFactory, - roleFactory, - schoolEntityFactory, - userFactory, -} from '@shared/testing'; -import { videoConferenceFactory } from '@shared/testing/factory/video-conference.factory'; import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; import { accountFactory } from '@src/modules/account/testing'; -import axios from 'axios'; -import MockAdapter from 'axios-mock-adapter'; -import { Response } from 'supertest'; -import { roomEntityFactory } from '@src/modules/room/testing'; -import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; import { BoardExternalReferenceType } from '@src/modules/board'; import { + cardEntityFactory, columnBoardEntityFactory, columnEntityFactory, - cardEntityFactory, videoConferenceElementEntityFactory, } from '@src/modules/board/testing'; +import { roomMembershipEntityFactory } from '@src/modules/room-membership/testing'; +import { roomEntityFactory } from '@src/modules/room/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { groupEntityFactory } from '@testing/factory/group-entity.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { UserAndAccountTestFactory } from '@testing/factory/user-and-account.test.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { videoConferenceFactory } from '@testing/factory/video-conference.factory'; +import { TestApiClient } from '@testing/test-api-client'; +import axios from 'axios'; +import MockAdapter from 'axios-mock-adapter'; +import { Response } from 'supertest'; import { VideoConferenceCreateParams, VideoConferenceJoinResponse } from '../dto'; describe('VideoConferenceController (API)', () => { diff --git a/apps/server/src/modules/video-conference/controller/video-conference-deprecated.controller.spec.ts b/apps/server/src/modules/video-conference/controller/video-conference-deprecated.controller.spec.ts index b0bc50275c8..68166041189 100644 --- a/apps/server/src/modules/video-conference/controller/video-conference-deprecated.controller.spec.ts +++ b/apps/server/src/modules/video-conference/controller/video-conference-deprecated.controller.spec.ts @@ -1,7 +1,7 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Test, TestingModule } from '@nestjs/testing'; import { VideoConferenceScope } from '@shared/domain/interface'; -import { currentUserFactory } from '@shared/testing'; +import { currentUserFactory } from '@testing/factory/currentuser.factory'; import { BBBBaseResponse, BBBCreateResponse } from '../bbb'; import { defaultVideoConferenceOptions } from '../interface'; import { VideoConferenceDeprecatedUc } from '../uc'; diff --git a/apps/server/src/modules/video-conference/service/video-conference.service.spec.ts b/apps/server/src/modules/video-conference/service/video-conference.service.spec.ts index 1ee7f27ddb0..dc8616e77e1 100644 --- a/apps/server/src/modules/video-conference/service/video-conference.service.spec.ts +++ b/apps/server/src/modules/video-conference/service/video-conference.service.spec.ts @@ -14,18 +14,23 @@ import { Course, TeamUserEntity } from '@shared/domain/entity'; import { Permission, RoleName, VideoConferenceScope } from '@shared/domain/interface'; import { EntityId, SchoolFeature } from '@shared/domain/types'; import { TeamsRepo, VideoConferenceRepo } from '@shared/repo'; -import { courseFactory, groupFactory, roleFactory, setupEntities, userDoFactory, userFactory } from '@shared/testing'; -import { teamFactory } from '@shared/testing/factory/team.factory'; -import { teamUserFactory } from '@shared/testing/factory/teamuser.factory'; -import { videoConferenceDOFactory } from '@shared/testing/factory/video-conference.do.factory'; import { BoardNodeAuthorizable, BoardNodeAuthorizableService, BoardNodeService, BoardRoles } from '@src/modules/board'; +import { VideoConferenceElement } from '@src/modules/board/domain'; +import { columnBoardFactory, videoConferenceElementFactory } from '@src/modules/board/testing'; +import { GroupTypes } from '@src/modules/group'; import { RoomService } from '@src/modules/room'; import { RoomMembershipService } from '@src/modules/room-membership'; -import { GroupTypes } from '@src/modules/group'; import { roomMembershipFactory } from '@src/modules/room-membership/testing'; import { roomFactory } from '@src/modules/room/testing'; -import { columnBoardFactory, videoConferenceElementFactory } from '@src/modules/board/testing'; -import { VideoConferenceElement } from '@src/modules/board/domain'; +import { courseFactory } from '@testing/factory/course.factory'; +import { groupFactory } from '@testing/factory/domainobject'; +import { roleFactory } from '@testing/factory/role.factory'; +import { teamFactory } from '@testing/factory/team.factory'; +import { teamUserFactory } from '@testing/factory/teamuser.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { videoConferenceDOFactory } from '@testing/factory/video-conference.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { BBBRole } from '../bbb'; import { ErrorStatus } from '../error'; import { VideoConferenceOptions } from '../interface'; diff --git a/apps/server/src/modules/video-conference/uc/video-conference-create.uc.spec.ts b/apps/server/src/modules/video-conference/uc/video-conference-create.uc.spec.ts index a2781a75a47..b81a6d55f16 100644 --- a/apps/server/src/modules/video-conference/uc/video-conference-create.uc.spec.ts +++ b/apps/server/src/modules/video-conference/uc/video-conference-create.uc.spec.ts @@ -1,12 +1,12 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; +import { ObjectId } from '@mikro-orm/mongodb'; import { UserService } from '@modules/user'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { UserDO } from '@shared/domain/domainobject'; import {} from '@shared/domain/entity'; import { VideoConferenceScope } from '@shared/domain/interface'; -import { userDoFactory } from '@shared/testing'; -import { ObjectId } from '@mikro-orm/mongodb'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { BBBCreateResponse, BBBMeetingInfoResponse, BBBResponse, BBBRole, BBBStatus } from '../bbb'; import { ErrorStatus } from '../error/error-status.enum'; import { VideoConferenceOptions } from '../interface'; diff --git a/apps/server/src/modules/video-conference/uc/video-conference-deprecated.uc.spec.ts b/apps/server/src/modules/video-conference/uc/video-conference-deprecated.uc.spec.ts index 2225a0ffbda..a3732a78556 100644 --- a/apps/server/src/modules/video-conference/uc/video-conference-deprecated.uc.spec.ts +++ b/apps/server/src/modules/video-conference/uc/video-conference-deprecated.uc.spec.ts @@ -14,8 +14,10 @@ import { Course, Role, TeamEntity } from '@shared/domain/entity'; import { Permission, RoleName, VideoConferenceScope } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; import { TeamsRepo, VideoConferenceRepo } from '@shared/repo'; -import { roleFactory, setupEntities, userDoFactory } from '@shared/testing'; -import { teamFactory } from '@shared/testing/factory/team.factory'; +import { roleFactory } from '@testing/factory/role.factory'; +import { teamFactory } from '@testing/factory/team.factory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { setupEntities } from '@testing/setup-entities'; import { BBBBaseMeetingConfig, BBBBaseResponse, diff --git a/apps/server/src/modules/video-conference/uc/video-conference-end.uc.spec.ts b/apps/server/src/modules/video-conference/uc/video-conference-end.uc.spec.ts index 2c640f3980a..3515abf9f94 100644 --- a/apps/server/src/modules/video-conference/uc/video-conference-end.uc.spec.ts +++ b/apps/server/src/modules/video-conference/uc/video-conference-end.uc.spec.ts @@ -1,12 +1,12 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; +import { ObjectId } from '@mikro-orm/mongodb'; import { UserService } from '@modules/user'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { UserDO } from '@shared/domain/domainobject'; import {} from '@shared/domain/entity'; import { VideoConferenceScope } from '@shared/domain/interface'; -import { userDoFactory } from '@shared/testing'; -import { ObjectId } from '@mikro-orm/mongodb'; +import { userDoFactory } from '@testing/factory/user.do.factory'; import { BBBBaseResponse, BBBResponse, BBBRole, BBBStatus } from '../bbb'; import { ErrorStatus } from '../error/error-status.enum'; import { BBBService, VideoConferenceService } from '../service'; diff --git a/apps/server/src/modules/video-conference/uc/video-conference-info.uc.spec.ts b/apps/server/src/modules/video-conference/uc/video-conference-info.uc.spec.ts index fd7a4e2ceb8..2b30e1cf03b 100644 --- a/apps/server/src/modules/video-conference/uc/video-conference-info.uc.spec.ts +++ b/apps/server/src/modules/video-conference/uc/video-conference-info.uc.spec.ts @@ -1,13 +1,13 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; +import { ObjectId } from '@mikro-orm/mongodb'; import { UserService } from '@modules/user'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { UserDO, VideoConferenceDO } from '@shared/domain/domainobject'; import {} from '@shared/domain/entity'; import { Permission, VideoConferenceScope } from '@shared/domain/interface'; -import { userDoFactory } from '@shared/testing'; -import { videoConferenceDOFactory } from '@shared/testing/factory/video-conference.do.factory'; -import { ObjectId } from '@mikro-orm/mongodb'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { videoConferenceDOFactory } from '@testing/factory/video-conference.do.factory'; import { BBBMeetingInfoResponse, BBBResponse, BBBRole, BBBStatus } from '../bbb'; import { ErrorStatus } from '../error/error-status.enum'; import { defaultVideoConferenceOptions, VideoConferenceOptions } from '../interface'; diff --git a/apps/server/src/modules/video-conference/uc/video-conference-join.uc.spec.ts b/apps/server/src/modules/video-conference/uc/video-conference-join.uc.spec.ts index 655532d0cf2..8ecedf6ed5f 100644 --- a/apps/server/src/modules/video-conference/uc/video-conference-join.uc.spec.ts +++ b/apps/server/src/modules/video-conference/uc/video-conference-join.uc.spec.ts @@ -1,13 +1,13 @@ import { DeepMocked, createMock } from '@golevelup/ts-jest'; +import { ObjectId } from '@mikro-orm/mongodb'; import { UserService } from '@modules/user'; import { ForbiddenException } from '@nestjs/common'; import { Test, TestingModule } from '@nestjs/testing'; import { UserDO, VideoConferenceDO } from '@shared/domain/domainobject'; import {} from '@shared/domain/entity'; import { Permission, VideoConferenceScope } from '@shared/domain/interface'; -import { userDoFactory } from '@shared/testing'; -import { videoConferenceDOFactory } from '@shared/testing/factory/video-conference.do.factory'; -import { ObjectId } from '@mikro-orm/mongodb'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { videoConferenceDOFactory } from '@testing/factory/video-conference.do.factory'; import { BBBJoinConfig, BBBJoinResponse, BBBResponse, BBBRole } from '../bbb'; import { ErrorStatus } from '../error/error-status.enum'; import { VideoConferenceOptions } from '../interface'; diff --git a/apps/server/src/shared/common/interceptor/duration-logging.interceptor.spec.ts b/apps/server/src/shared/common/interceptor/duration-logging.interceptor.spec.ts index 4181041f1cd..3c19d4f6763 100644 --- a/apps/server/src/shared/common/interceptor/duration-logging.interceptor.spec.ts +++ b/apps/server/src/shared/common/interceptor/duration-logging.interceptor.spec.ts @@ -1,10 +1,10 @@ import { createMock, DeepMocked } from '@golevelup/ts-jest'; import { Controller, Get, HttpStatus, INestApplication } from '@nestjs/common'; -import { LegacyLogger } from '@src/core/logger'; -import { Test } from '@nestjs/testing'; import { APP_INTERCEPTOR } from '@nestjs/core'; +import { Test } from '@nestjs/testing'; +import { LegacyLogger } from '@src/core/logger'; +import { TestApiClient } from '@testing/test-api-client'; import { DurationLoggingInterceptor } from './duration-logging.interceptor'; -import { TestApiClient } from '../../testing'; @Controller() class TestController { diff --git a/apps/server/src/shared/common/interceptor/timeout.interceptor.spec.ts b/apps/server/src/shared/common/interceptor/timeout.interceptor.spec.ts index f3370927aab..c510d326524 100644 --- a/apps/server/src/shared/common/interceptor/timeout.interceptor.spec.ts +++ b/apps/server/src/shared/common/interceptor/timeout.interceptor.spec.ts @@ -4,7 +4,7 @@ import { ConfigService } from '@nestjs/config'; import { APP_INTERCEPTOR } from '@nestjs/core'; import { Test } from '@nestjs/testing'; import { RequestTimeout, TimeoutInterceptor } from '@shared/common'; -import { TestApiClient } from '@shared/testing'; +import { TestApiClient } from '@testing/test-api-client'; const delay = (ms: number) => new Promise((resolve) => { diff --git a/apps/server/src/shared/domain/entity/all-entities.spec.ts b/apps/server/src/shared/domain/entity/all-entities.spec.ts index 3c92153fc72..2cebc14a9c4 100644 --- a/apps/server/src/shared/domain/entity/all-entities.spec.ts +++ b/apps/server/src/shared/domain/entity/all-entities.spec.ts @@ -2,7 +2,7 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { MikroORM } from '@mikro-orm/core'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; -import { createCollections } from '@shared/testing'; +import { createCollections } from '@testing/create-collections'; import { ALL_ENTITIES } from '.'; describe('BaseRepo', () => { diff --git a/apps/server/src/shared/domain/entity/base.entity.spec.ts b/apps/server/src/shared/domain/entity/base.entity.spec.ts index dec7f12a5b1..c3806238b2f 100644 --- a/apps/server/src/shared/domain/entity/base.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/base.entity.spec.ts @@ -1,6 +1,6 @@ import { Entity } from '@mikro-orm/core'; import { ObjectId } from '@mikro-orm/mongodb'; -import { setupEntities } from '@shared/testing'; +import { setupEntities } from '@testing/setup-entities'; import { BaseEntity } from './base.entity'; @Entity() diff --git a/apps/server/src/shared/domain/entity/column-board-node.entity.spec.ts b/apps/server/src/shared/domain/entity/column-board-node.entity.spec.ts index b632cdbf500..cfbd3bbd3d8 100644 --- a/apps/server/src/shared/domain/entity/column-board-node.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/column-board-node.entity.spec.ts @@ -1,4 +1,4 @@ -import { columnBoardNodeFactory } from '@shared/testing'; +import { columnBoardNodeFactory } from '@testing/factory/column-board-node.factory'; import { ColumnBoardNode } from './column-board-node.entity'; describe(ColumnBoardNode.name, () => { diff --git a/apps/server/src/shared/domain/entity/course.entity.spec.ts b/apps/server/src/shared/domain/entity/course.entity.spec.ts index 0b7f7f432eb..39e1a92ae93 100644 --- a/apps/server/src/shared/domain/entity/course.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/course.entity.spec.ts @@ -1,7 +1,11 @@ import { MikroORM } from '@mikro-orm/core'; -import { InternalServerErrorException } from '@nestjs/common'; -import { courseFactory, courseGroupFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { InternalServerErrorException } from '@nestjs/common'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Course } from './course.entity'; import { CourseGroup } from './coursegroup.entity'; diff --git a/apps/server/src/shared/domain/entity/coursegroup.entity.spec.ts b/apps/server/src/shared/domain/entity/coursegroup.entity.spec.ts index 390457a4c87..633c715e760 100644 --- a/apps/server/src/shared/domain/entity/coursegroup.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/coursegroup.entity.spec.ts @@ -1,4 +1,7 @@ -import { courseFactory, courseGroupFactory, setupEntities, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { CourseGroup } from './coursegroup.entity'; describe('CourseGroupEntity', () => { diff --git a/apps/server/src/shared/domain/entity/legacy-board/boardElement.entity.spec.ts b/apps/server/src/shared/domain/entity/legacy-board/boardElement.entity.spec.ts index dc9524bded0..0d01b00ef64 100644 --- a/apps/server/src/shared/domain/entity/legacy-board/boardElement.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/legacy-board/boardElement.entity.spec.ts @@ -1,4 +1,7 @@ -import { columnBoardNodeFactory, lessonFactory, setupEntities, taskFactory } from '@shared/testing'; +import { columnBoardNodeFactory } from '@testing/factory/column-board-node.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ColumnboardBoardElement } from './column-board-boardelement'; import { LegacyBoardElementType } from './legacy-boardelement.entity'; import { LessonBoardElement } from './lesson-boardelement.entity'; diff --git a/apps/server/src/shared/domain/entity/legacy-board/legacy-board.entity.spec.ts b/apps/server/src/shared/domain/entity/legacy-board/legacy-board.entity.spec.ts index 9b7373bd79e..379349e67ba 100644 --- a/apps/server/src/shared/domain/entity/legacy-board/legacy-board.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/legacy-board/legacy-board.entity.spec.ts @@ -1,17 +1,16 @@ +import { columnBoardFactory } from '@modules/board/testing'; import { BadRequestException } from '@nestjs/common'; +import { boardFactory } from '@testing/factory/board.factory'; import { - boardFactory, columnboardBoardElementFactory, - columnBoardNodeFactory, - courseFactory, lessonBoardElementFactory, - lessonFactory, - setupEntities, taskBoardElementFactory, - taskFactory, -} from '@shared/testing'; - -import { columnBoardFactory } from '@modules/board/testing'; +} from '@testing/factory/boardelement.factory'; +import { columnBoardNodeFactory } from '@testing/factory/column-board-node.factory'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; describe('Board Entity', () => { beforeAll(async () => { diff --git a/apps/server/src/shared/domain/entity/lesson.entity.spec.ts b/apps/server/src/shared/domain/entity/lesson.entity.spec.ts index daca93d86e5..4a790d9e0a1 100644 --- a/apps/server/src/shared/domain/entity/lesson.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/lesson.entity.spec.ts @@ -1,13 +1,11 @@ import { MikroORM } from '@mikro-orm/core'; import { ObjectId } from '@mikro-orm/mongodb'; -import { - courseFactory, - courseGroupFactory, - lessonFactory, - materialFactory, - setupEntities, - taskFactory, -} from '../../testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { materialFactory } from '@testing/factory/material.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { setupEntities } from '@testing/setup-entities'; import { ComponentProperties, ComponentType } from './lesson.entity'; import { Material } from './materials.entity'; import { Task } from './task.entity'; diff --git a/apps/server/src/shared/domain/entity/ltitool.entity.spec.ts b/apps/server/src/shared/domain/entity/ltitool.entity.spec.ts index 257b5e72106..5935260b2b4 100644 --- a/apps/server/src/shared/domain/entity/ltitool.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/ltitool.entity.spec.ts @@ -1,6 +1,6 @@ import { LtiPrivacyPermission, LtiTool } from '@shared/domain/entity'; -import { setupEntities } from '@shared/testing'; -import { ltiToolFactory } from '@shared/testing/factory/ltitool.factory'; +import { ltiToolFactory } from '@testing/factory/ltitool.factory'; +import { setupEntities } from '@testing/setup-entities'; describe('Ltitool Entity', () => { beforeAll(async () => { diff --git a/apps/server/src/shared/domain/entity/news.entity.spec.ts b/apps/server/src/shared/domain/entity/news.entity.spec.ts index 36ced085831..9079fef4b95 100644 --- a/apps/server/src/shared/domain/entity/news.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/news.entity.spec.ts @@ -1,4 +1,6 @@ -import { setupEntities, teamNewsFactory, userFactory } from '@shared/testing'; +import { teamNewsFactory } from '@testing/factory/news.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { News } from './news.entity'; describe(News.name, () => { diff --git a/apps/server/src/shared/domain/entity/role.entity.spec.ts b/apps/server/src/shared/domain/entity/role.entity.spec.ts index c7cbd19bb2e..d696423200a 100644 --- a/apps/server/src/shared/domain/entity/role.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/role.entity.spec.ts @@ -1,6 +1,7 @@ import { MikroORM } from '@mikro-orm/core'; -import { roleFactory, setupEntities } from '@shared/testing'; import { ObjectId } from '@mikro-orm/mongodb'; +import { roleFactory } from '@testing/factory/role.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Permission, RoleName } from '../interface'; import { Role } from './role.entity'; // import { Permission, } from '..'; diff --git a/apps/server/src/shared/domain/entity/schoolyear.entity.spec.ts b/apps/server/src/shared/domain/entity/schoolyear.entity.spec.ts index f4677727a2d..d05b1d5bad9 100644 --- a/apps/server/src/shared/domain/entity/schoolyear.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/schoolyear.entity.spec.ts @@ -1,5 +1,5 @@ -import { setupEntities } from '@shared/testing'; -import { schoolYearFactory } from '@shared/testing/factory/schoolyear.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { setupEntities } from '@testing/setup-entities'; import { SchoolYearEntity } from './schoolyear.entity'; describe('schoolyear entity', () => { diff --git a/apps/server/src/shared/domain/entity/submission.entity.spec.ts b/apps/server/src/shared/domain/entity/submission.entity.spec.ts index f6320e1fdd9..492f4ea7b04 100644 --- a/apps/server/src/shared/domain/entity/submission.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/submission.entity.spec.ts @@ -1,13 +1,11 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { InternalServerErrorException } from '@nestjs/common'; -import { - courseGroupFactory, - schoolEntityFactory, - setupEntities, - submissionFactory, - taskFactory, - userFactory, -} from '@shared/testing'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Submission } from './submission.entity'; describe('Submission entity', () => { diff --git a/apps/server/src/shared/domain/entity/task.entity.spec.ts b/apps/server/src/shared/domain/entity/task.entity.spec.ts index 9686164769c..a8e8e9165f7 100644 --- a/apps/server/src/shared/domain/entity/task.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/task.entity.spec.ts @@ -1,14 +1,12 @@ import { InternalServerErrorException } from '@nestjs/common'; -import { - courseFactory, - courseGroupFactory, - lessonFactory, - schoolEntityFactory, - setupEntities, - submissionFactory, - taskFactory, - userFactory, -} from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; describe('Task Entity', () => { beforeAll(async () => { diff --git a/apps/server/src/shared/domain/entity/user.entity.spec.ts b/apps/server/src/shared/domain/entity/user.entity.spec.ts index b638577e196..1cfef86c4a7 100644 --- a/apps/server/src/shared/domain/entity/user.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/user.entity.spec.ts @@ -2,7 +2,10 @@ import { Configuration } from '@hpi-schul-cloud/commons/lib'; import { MikroORM } from '@mikro-orm/core'; import { ObjectId } from '@mikro-orm/mongodb'; import { ReferenceNotPopulatedLoggableException } from '@shared/common/loggable-exception/reference-not-populated.loggable-exception'; -import { roleFactory, schoolEntityFactory, setupEntities, userFactory } from '@shared/testing'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { userFactory } from '@testing/factory/user.factory'; +import { setupEntities } from '@testing/setup-entities'; import { Role, SchoolEntity } from '.'; import { LanguageType, Permission, RoleName } from '../interface'; import { User } from './user.entity'; diff --git a/apps/server/src/shared/domain/entity/video-conference.entity.spec.ts b/apps/server/src/shared/domain/entity/video-conference.entity.spec.ts index a71944002dd..fde2c2f7b17 100644 --- a/apps/server/src/shared/domain/entity/video-conference.entity.spec.ts +++ b/apps/server/src/shared/domain/entity/video-conference.entity.spec.ts @@ -1,6 +1,6 @@ import { VideoConference, VideoConferenceOptions } from '@shared/domain/entity/video-conference.entity'; -import { setupEntities } from '@shared/testing'; -import { videoConferenceFactory } from '@shared/testing/factory/video-conference.factory'; +import { videoConferenceFactory } from '@testing/factory/video-conference.factory'; +import { setupEntities } from '@testing/setup-entities'; describe('Video Conference Entity', () => { beforeAll(async () => { diff --git a/apps/server/src/shared/repo/contextexternaltool/context-external-tool.repo.spec.ts b/apps/server/src/shared/repo/contextexternaltool/context-external-tool.repo.spec.ts index b96b2150517..12689dbf507 100644 --- a/apps/server/src/shared/repo/contextexternaltool/context-external-tool.repo.spec.ts +++ b/apps/server/src/shared/repo/contextexternaltool/context-external-tool.repo.spec.ts @@ -17,7 +17,8 @@ import { Test, TestingModule } from '@nestjs/testing'; import { SchoolEntity } from '@shared/domain/entity'; import { ExternalToolRepoMapper } from '@shared/repo/externaltool/external-tool.repo.mapper'; import { LegacyLogger } from '@src/core/logger'; -import { cleanupCollections, schoolEntityFactory } from '../../testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; import { ContextExternalToolRepo } from './context-external-tool.repo'; describe(ContextExternalToolRepo.name, () => { diff --git a/apps/server/src/shared/repo/course/course.repo.integration.spec.ts b/apps/server/src/shared/repo/course/course.repo.integration.spec.ts index df17fe2acc6..c6bf6c9291f 100644 --- a/apps/server/src/shared/repo/course/course.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/course/course.repo.integration.spec.ts @@ -5,7 +5,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Course } from '@shared/domain/entity'; import { SortOrder } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; -import { cleanupCollections, courseFactory, courseGroupFactory, userFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { CourseRepo } from './course.repo'; const checkEqualIds = (arr1: { id: EntityId }[], arr2: { id: EntityId }[]): boolean => { diff --git a/apps/server/src/shared/repo/coursegroup/coursegroup.repo.integration.spec.ts b/apps/server/src/shared/repo/coursegroup/coursegroup.repo.integration.spec.ts index ccf48f9182f..47ce338dedd 100644 --- a/apps/server/src/shared/repo/coursegroup/coursegroup.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/coursegroup/coursegroup.repo.integration.spec.ts @@ -3,7 +3,8 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { Course, CourseGroup } from '@shared/domain/entity'; import { EntityId } from '@shared/domain/types'; -import { courseFactory, courseGroupFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; import { CourseGroupRepo } from './coursegroup.repo'; const checkEqualIds = (arr1: { id: EntityId }[], arr2: { id: EntityId }[]): boolean => { diff --git a/apps/server/src/shared/repo/dashboard/dashboard.model.mapper.spec.ts b/apps/server/src/shared/repo/dashboard/dashboard.model.mapper.spec.ts index 9399da2542c..eb135751d8d 100644 --- a/apps/server/src/shared/repo/dashboard/dashboard.model.mapper.spec.ts +++ b/apps/server/src/shared/repo/dashboard/dashboard.model.mapper.spec.ts @@ -10,7 +10,8 @@ import { GridElement, } from '@shared/domain/entity'; import { LearnroomMetadata, LearnroomTypes } from '@shared/domain/types'; -import { courseFactory, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { DashboardModelMapper } from './dashboard.model.mapper'; describe('dashboard model mapper', () => { diff --git a/apps/server/src/shared/repo/dashboard/dashboard.repo.integration.spec.ts b/apps/server/src/shared/repo/dashboard/dashboard.repo.integration.spec.ts index 4f16c9c83cc..0f9efbe4c48 100644 --- a/apps/server/src/shared/repo/dashboard/dashboard.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/dashboard/dashboard.repo.integration.spec.ts @@ -2,7 +2,8 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { DashboardEntity, DashboardGridElementModel, GridElement } from '@shared/domain/entity'; -import { courseFactory, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { DashboardModelMapper } from './dashboard.model.mapper'; import { DashboardRepo } from './dashboard.repo'; diff --git a/apps/server/src/shared/repo/dashboard/dashboardElement.repo.spec.ts b/apps/server/src/shared/repo/dashboard/dashboardElement.repo.spec.ts index 7c416193b2b..c97056439aa 100644 --- a/apps/server/src/shared/repo/dashboard/dashboardElement.repo.spec.ts +++ b/apps/server/src/shared/repo/dashboard/dashboardElement.repo.spec.ts @@ -2,7 +2,8 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { DashboardGridElementModel, DashboardModelEntity } from '@shared/domain/entity'; -import { courseFactory, userFactory } from '@shared/testing'; +import { courseFactory } from '@testing/factory/course.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { DashboardElementRepo } from './dashboardElement.repo'; describe(DashboardElementRepo.name, () => { diff --git a/apps/server/src/shared/repo/externaltool/external-tool.repo.spec.ts b/apps/server/src/shared/repo/externaltool/external-tool.repo.spec.ts index d538e13efed..21810ba4416 100644 --- a/apps/server/src/shared/repo/externaltool/external-tool.repo.spec.ts +++ b/apps/server/src/shared/repo/externaltool/external-tool.repo.spec.ts @@ -18,8 +18,8 @@ import { Test, TestingModule } from '@nestjs/testing'; import { Page } from '@shared/domain/domainobject'; import { IFindOptions, SortOrder } from '@shared/domain/interface'; import { ExternalToolRepo, ExternalToolRepoMapper } from '@shared/repo'; -import { cleanupCollections } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { cleanupCollections } from '@testing/cleanup-collections'; describe(ExternalToolRepo.name, () => { let module: TestingModule; diff --git a/apps/server/src/shared/repo/federalstate/federal-state.repo.spec.ts b/apps/server/src/shared/repo/federalstate/federal-state.repo.spec.ts index 7755eefb4b4..c38298d646c 100644 --- a/apps/server/src/shared/repo/federalstate/federal-state.repo.spec.ts +++ b/apps/server/src/shared/repo/federalstate/federal-state.repo.spec.ts @@ -2,7 +2,8 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { FederalStateEntity } from '@shared/domain/entity'; -import { cleanupCollections, federalStateFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { federalStateFactory } from '@testing/factory/federal-state.factory'; import { FederalStateRepo } from './federal-state.repo'; describe('FederalStateRepo', () => { diff --git a/apps/server/src/shared/repo/legacy-board/legacy-board.repo.spec.ts b/apps/server/src/shared/repo/legacy-board/legacy-board.repo.spec.ts index dbe1aaf12d9..0bbc0fd801a 100644 --- a/apps/server/src/shared/repo/legacy-board/legacy-board.repo.spec.ts +++ b/apps/server/src/shared/repo/legacy-board/legacy-board.repo.spec.ts @@ -1,14 +1,11 @@ import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { LegacyBoard, LessonEntity, Task } from '@shared/domain/entity'; -import { - boardFactory, - cleanupCollections, - courseFactory, - lessonBoardElementFactory, - lessonFactory, - taskBoardElementFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { boardFactory } from '@testing/factory/board.factory'; +import { lessonBoardElementFactory, taskBoardElementFactory } from '@testing/factory/boardelement.factory'; +import { courseFactory } from '@testing/factory/course.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; import { MongoMemoryDatabaseModule } from '@infra/database'; diff --git a/apps/server/src/shared/repo/ltitool/ltitool.repo.spec.ts b/apps/server/src/shared/repo/ltitool/ltitool.repo.spec.ts index 78ec3852ea3..258b6c57354 100644 --- a/apps/server/src/shared/repo/ltitool/ltitool.repo.spec.ts +++ b/apps/server/src/shared/repo/ltitool/ltitool.repo.spec.ts @@ -1,15 +1,15 @@ import { createMock } from '@golevelup/ts-jest'; -import { EntityData, NotFoundError } from '@mikro-orm/core'; import { MongoMemoryDatabaseModule } from '@infra/database'; +import { EntityData, NotFoundError } from '@mikro-orm/core'; import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { LtiToolDO } from '@shared/domain/domainobject/ltitool.do'; import { LtiTool } from '@shared/domain/entity'; import { LtiPrivacyPermission, LtiRoleType } from '@shared/domain/entity/ltitool.entity'; import { LtiToolRepo } from '@shared/repo/ltitool/ltitool.repo'; -import { cleanupCollections } from '@shared/testing'; -import { ltiToolFactory } from '@shared/testing/factory/ltitool.factory'; import { LegacyLogger } from '@src/core/logger'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { ltiToolFactory } from '@testing/factory/ltitool.factory'; class LtiToolRepoSpec extends LtiToolRepo { mapEntityToDOSpec(entity: LtiTool): LtiToolDO { diff --git a/apps/server/src/shared/repo/materials/materials.repo.integration.spec.ts b/apps/server/src/shared/repo/materials/materials.repo.integration.spec.ts index 0b6b26ff39f..687ee659314 100644 --- a/apps/server/src/shared/repo/materials/materials.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/materials/materials.repo.integration.spec.ts @@ -1,8 +1,8 @@ +import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { Material } from '@shared/domain/entity/materials.entity'; -import { MongoMemoryDatabaseModule } from '@infra/database'; -import { cleanupCollections } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { MaterialsRepo } from './materials.repo'; describe('MaterialsRepo', () => { diff --git a/apps/server/src/shared/repo/news/news-inheritance.spec.ts b/apps/server/src/shared/repo/news/news-inheritance.spec.ts index cb4cdd155b8..be70a8eca9b 100644 --- a/apps/server/src/shared/repo/news/news-inheritance.spec.ts +++ b/apps/server/src/shared/repo/news/news-inheritance.spec.ts @@ -3,7 +3,7 @@ import { Collection, Entity, Enum, ManyToMany, ManyToOne, Property } from '@mikr import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { BaseEntityWithTimestamps } from '@shared/domain/entity'; -import { cleanupCollections } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; @Entity({ tableName: 'users' }) class User extends BaseEntityWithTimestamps { diff --git a/apps/server/src/shared/repo/news/news.repo.integration.spec.ts b/apps/server/src/shared/repo/news/news.repo.integration.spec.ts index 25240d5a1c6..c442c445d6e 100644 --- a/apps/server/src/shared/repo/news/news.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/news/news.repo.integration.spec.ts @@ -5,16 +5,16 @@ import { Test, TestingModule } from '@nestjs/testing'; import { News } from '@shared/domain/entity'; import { SortOrder } from '@shared/domain/interface'; import { NewsTargetModel } from '@shared/domain/types'; +import { cleanupCollections } from '@testing/cleanup-collections'; import { - cleanupCollections, courseNewsFactory, courseUnpublishedNewsFactory, schoolNewsFactory, schoolUnpublishedNewsFactory, teamNewsFactory, teamUnpublishedNewsFactory, - userFactory, -} from '@shared/testing'; +} from '@testing/factory/news.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { NewsRepo } from './news.repo'; describe('NewsRepo', () => { diff --git a/apps/server/src/shared/repo/role/role.repo.integration.spec.ts b/apps/server/src/shared/repo/role/role.repo.integration.spec.ts index 91df9f230a7..3d1b0e6c61a 100644 --- a/apps/server/src/shared/repo/role/role.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/role/role.repo.integration.spec.ts @@ -4,7 +4,8 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { Role } from '@shared/domain/entity'; import { RoleName } from '@shared/domain/interface'; -import { cleanupCollections, roleFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { roleFactory } from '@testing/factory/role.factory'; import { RoleRepo } from './role.repo'; describe('role repo', () => { diff --git a/apps/server/src/shared/repo/school/legacy-school.repo.integration.spec.ts b/apps/server/src/shared/repo/school/legacy-school.repo.integration.spec.ts index f3d0ea619a3..5c10a3b6559 100644 --- a/apps/server/src/shared/repo/school/legacy-school.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/school/legacy-school.repo.integration.spec.ts @@ -13,14 +13,12 @@ import { SchoolYearEntity, UserLoginMigrationEntity, } from '@shared/domain/entity'; -import { - legacySchoolDoFactory, - schoolEntityFactory, - schoolYearFactory, - systemEntityFactory, - userLoginMigrationFactory, -} from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { legacySchoolDoFactory } from '@testing/factory/domainobject'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { schoolYearFactory } from '@testing/factory/schoolyear.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userLoginMigrationFactory } from '@testing/factory/user-login-migration.factory'; import { LegacySchoolRepo } from './legacy-school.repo'; describe('LegacySchoolRepo', () => { diff --git a/apps/server/src/shared/repo/schoolexternaltool/school-external-tool.repo.spec.ts b/apps/server/src/shared/repo/schoolexternaltool/school-external-tool.repo.spec.ts index 7cc8596c6e5..cc0c4dcf479 100644 --- a/apps/server/src/shared/repo/schoolexternaltool/school-external-tool.repo.spec.ts +++ b/apps/server/src/shared/repo/schoolexternaltool/school-external-tool.repo.spec.ts @@ -11,8 +11,9 @@ import { SchoolExternalToolQuery } from '@modules/tool/school-external-tool/uc/d import { Test, TestingModule } from '@nestjs/testing'; import { type SchoolEntity } from '@shared/domain/entity'; import { ExternalToolRepoMapper } from '@shared/repo/externaltool/external-tool.repo.mapper'; -import { cleanupCollections, schoolEntityFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; import { SchoolExternalToolRepo } from './school-external-tool.repo'; describe(SchoolExternalToolRepo.name, () => { diff --git a/apps/server/src/shared/repo/storageprovider/storageprovider.repo.spec.ts b/apps/server/src/shared/repo/storageprovider/storageprovider.repo.spec.ts index 6e71c3d1d93..f9445a45a42 100644 --- a/apps/server/src/shared/repo/storageprovider/storageprovider.repo.spec.ts +++ b/apps/server/src/shared/repo/storageprovider/storageprovider.repo.spec.ts @@ -2,7 +2,8 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { StorageProviderEntity } from '@shared/domain/entity'; -import { cleanupCollections, storageProviderFactory } from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { storageProviderFactory } from '@testing/factory/storageprovider.factory'; import { StorageProviderRepo } from './storageprovider.repo'; describe('StorageProviderRepo', () => { diff --git a/apps/server/src/shared/repo/submission/submission.repo.integration.spec.ts b/apps/server/src/shared/repo/submission/submission.repo.integration.spec.ts index 9e9c7b9213a..036af493c24 100644 --- a/apps/server/src/shared/repo/submission/submission.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/submission/submission.repo.integration.spec.ts @@ -2,15 +2,13 @@ import { MongoMemoryDatabaseModule } from '@infra/database'; import { EntityManager } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { Submission } from '@shared/domain/entity'; -import { - cleanupCollections, - courseFactory, - courseGroupFactory, - lessonFactory, - submissionFactory, - taskFactory, - userFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { SubmissionRepo } from './submission.repo'; describe('submission repo', () => { diff --git a/apps/server/src/shared/repo/task/task.repo.integration.spec.ts b/apps/server/src/shared/repo/task/task.repo.integration.spec.ts index 7b383c427bc..a394dc61b4b 100644 --- a/apps/server/src/shared/repo/task/task.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/task/task.repo.integration.spec.ts @@ -3,15 +3,13 @@ import { EntityManager, ObjectId } from '@mikro-orm/mongodb'; import { Test, TestingModule } from '@nestjs/testing'; import { Task } from '@shared/domain/entity'; import { SortOrder } from '@shared/domain/interface'; -import { - cleanupCollections, - courseFactory, - courseGroupFactory, - lessonFactory, - submissionFactory, - taskFactory, - userFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { courseFactory } from '@testing/factory/course.factory'; +import { courseGroupFactory } from '@testing/factory/coursegroup.factory'; +import { lessonFactory } from '@testing/factory/lesson.factory'; +import { submissionFactory } from '@testing/factory/submission.factory'; +import { taskFactory } from '@testing/factory/task.factory'; +import { userFactory } from '@testing/factory/user.factory'; import { TaskRepo } from './task.repo'; const yesterday = new Date(Date.now() - 86400000); diff --git a/apps/server/src/shared/repo/teams/team.repo.integration.spec.ts b/apps/server/src/shared/repo/teams/team.repo.integration.spec.ts index 3e6a07bbf66..acf6e5271b5 100644 --- a/apps/server/src/shared/repo/teams/team.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/teams/team.repo.integration.spec.ts @@ -5,9 +5,10 @@ import { Test, TestingModule } from '@nestjs/testing'; import { TeamEntity, TeamUserEntity } from '@shared/domain/entity'; import { EntityId } from '@shared/domain/types'; import { TeamsRepo } from '@shared/repo'; -import { cleanupCollections, roleFactory } from '@shared/testing'; -import { teamFactory } from '@shared/testing/factory/team.factory'; -import { teamUserFactory } from '@shared/testing/factory/teamuser.factory'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { roleFactory } from '@testing/factory/role.factory'; +import { teamFactory } from '@testing/factory/team.factory'; +import { teamUserFactory } from '@testing/factory/teamuser.factory'; describe('team repo', () => { let module: TestingModule; diff --git a/apps/server/src/shared/repo/user/user-do.repo.integration.spec.ts b/apps/server/src/shared/repo/user/user-do.repo.integration.spec.ts index fc3beb920b4..3b129dbd218 100644 --- a/apps/server/src/shared/repo/user/user-do.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/user/user-do.repo.integration.spec.ts @@ -14,15 +14,13 @@ import { UserDO } from '@shared/domain/domainobject/user.do'; import { Role, SchoolEntity, User } from '@shared/domain/entity'; import { IFindOptions, LanguageType, RoleName, SortOrder } from '@shared/domain/interface'; import { UserDORepo } from '@shared/repo/user/user-do.repo'; -import { - cleanupCollections, - roleFactory, - schoolEntityFactory, - systemEntityFactory, - userDoFactory, - userFactory, -} from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userDoFactory } from '@testing/factory/user.do.factory'; +import { userFactory } from '@testing/factory/user.factory'; describe('UserRepo', () => { let module: TestingModule; diff --git a/apps/server/src/shared/repo/user/user.repo.integration.spec.ts b/apps/server/src/shared/repo/user/user.repo.integration.spec.ts index 8dc1ce48565..544413a6736 100644 --- a/apps/server/src/shared/repo/user/user.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/user/user.repo.integration.spec.ts @@ -6,13 +6,11 @@ import { Test, TestingModule } from '@nestjs/testing'; import { User } from '@shared/domain/entity'; import { UserParentsEntityProps } from '@shared/domain/entity/user-parents.entity'; import { SortOrder } from '@shared/domain/interface'; -import { - cleanupCollections, - roleFactory, - schoolEntityFactory, - systemEntityFactory, - userFactory, -} from '@shared/testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { roleFactory } from '@testing/factory/role.factory'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userFactory } from '@testing/factory/user.factory'; import { UserRepo } from './user.repo'; describe('user repo', () => { diff --git a/apps/server/src/shared/repo/userloginmigration/user-login-migration.repo.integration.spec.ts b/apps/server/src/shared/repo/userloginmigration/user-login-migration.repo.integration.spec.ts index 993f72aedb4..458710ad0c1 100644 --- a/apps/server/src/shared/repo/userloginmigration/user-login-migration.repo.integration.spec.ts +++ b/apps/server/src/shared/repo/userloginmigration/user-login-migration.repo.integration.spec.ts @@ -7,9 +7,11 @@ import { Test, TestingModule } from '@nestjs/testing'; import { UserLoginMigrationDO } from '@shared/domain/domainobject'; import { SchoolEntity } from '@shared/domain/entity'; import { UserLoginMigrationEntity } from '@shared/domain/entity/user-login-migration.entity'; -import { cleanupCollections, schoolEntityFactory, systemEntityFactory } from '@shared/testing'; import { LegacyLogger } from '@src/core/logger'; -import { userLoginMigrationFactory } from '../../testing'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { schoolEntityFactory } from '@testing/factory/school-entity.factory'; +import { systemEntityFactory } from '@testing/factory/systemEntityFactory'; +import { userLoginMigrationFactory } from '@testing/factory/user-login-migration.factory'; import { UserLoginMigrationRepo } from './user-login-migration.repo'; describe('UserLoginMigrationRepo', () => { diff --git a/apps/server/src/shared/repo/videoconference/video-conference.repo.spec.ts b/apps/server/src/shared/repo/videoconference/video-conference.repo.spec.ts index 13e7a810c5e..9238ee80db9 100644 --- a/apps/server/src/shared/repo/videoconference/video-conference.repo.spec.ts +++ b/apps/server/src/shared/repo/videoconference/video-conference.repo.spec.ts @@ -7,9 +7,9 @@ import { VideoConferenceDO, VideoConferenceOptionsDO } from '@shared/domain/doma import { TargetModels, VideoConference, VideoConferenceOptions } from '@shared/domain/entity'; import { VideoConferenceScope } from '@shared/domain/interface'; import { VideoConferenceRepo } from '@shared/repo'; -import { cleanupCollections } from '@shared/testing'; -import { videoConferenceFactory } from '@shared/testing/factory/video-conference.factory'; import { LegacyLogger } from '@src/core/logger'; +import { cleanupCollections } from '@testing/cleanup-collections'; +import { videoConferenceFactory } from '@testing/factory/video-conference.factory'; class VideoConferenceRepoSpec extends VideoConferenceRepo { mapEntityToDOSpec(entity: VideoConference): VideoConferenceDO { diff --git a/apps/server/src/shared/testing/factory/index.ts b/apps/server/src/shared/testing/factory/index.ts deleted file mode 100644 index d0d2e9568d9..00000000000 --- a/apps/server/src/shared/testing/factory/index.ts +++ /dev/null @@ -1,43 +0,0 @@ -export * from './axios-error.factory'; -export * from './axios-response.factory'; -export * from './base.factory'; -export * from './board.factory'; -export * from './boardelement.factory'; -export * from './column-board-node.factory'; -export { countyEmbeddableFactory } from './county.embeddable.factory'; -export * from './course.factory'; -export * from './coursegroup.factory'; -export * from './currentuser.factory'; -export * from './domainobject'; -export * from './entity.factory'; -export * from './external-group-dto.factory'; -export { externalSchoolDtoFactory } from './external-school-dto.factory'; -export * from './external-tool-pseudonym.factory'; -export * from './federal-state.factory'; -export * from './filerecord.factory'; -export * from './group-entity.factory'; -export * from './h5p-content.factory'; -export * from './import-user.factory'; -export * from './jwt.test.factory'; -export * from './jwtpayload.factory'; -export * from './legacy-file-entity-mock.factory'; -export * from './lesson.factory'; -export * from './material.factory'; -export * from './news.factory'; -export * from './role-dto.factory'; -export * from './role.factory'; -export * from './school-entity.factory'; -export { schoolSystemOptionsEntityFactory } from './school-system-options-entity.factory'; -export * from './schoolyear.factory'; -export * from './share-token.do.factory'; -export * from './storageprovider.factory'; -export * from './submission.factory'; -export * from './systemEntityFactory'; -export * from './task.factory'; -export * from './team.factory'; -export * from './teamuser.factory'; -export * from './tldraw-file-dto.factory'; -export * from './user-and-account.test.factory'; -export * from './user-login-migration.factory'; -export * from './user.do.factory'; -export * from './user.factory'; diff --git a/apps/server/src/shared/testing/index.ts b/apps/server/src/shared/testing/index.ts deleted file mode 100644 index c891be689a6..00000000000 --- a/apps/server/src/shared/testing/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export * from './factory'; -export * from './setup-entities'; -export * from './create-collections'; -export * from './cleanup-collections'; -export * from './map-user-to-current-user'; -export * from './test-api-client'; -export * from './web-socket-ready-state-enum'; -export { DateToString } from './date-to-string'; diff --git a/apps/server/src/shared/testing/test-socket-api-client.ts b/apps/server/src/shared/testing/test-socket-api-client.ts deleted file mode 100644 index 1d00578d68a..00000000000 --- a/apps/server/src/shared/testing/test-socket-api-client.ts +++ /dev/null @@ -1,51 +0,0 @@ -import { EntityManager } from '@mikro-orm/mongodb'; -import { INestApplication } from '@nestjs/common'; - -import { User } from '@shared/domain/entity'; -import { accountFactory } from '@modules/account/testing'; -import { LocalAuthorizationBodyParams } from '@modules/authentication/controllers/dto'; -import { Socket, io } from 'socket.io-client'; -import request from 'supertest'; - -export async function waitForEvent(socket: Socket, eventName: string): Promise { - return new Promise((resolve) => { - socket.on(eventName, (data: unknown) => { - resolve(data); - }); - }); -} - -export async function getSocketApiClient(app: INestApplication, user: User) { - const em = app.get(EntityManager); - const defaultPassword = 'DummyPasswd!1'; - const defaultPasswordHash = '$2a$10$/DsztV5o6P5piW2eWJsxw.4nHovmJGBA.QNwiTmuZ/uvUc40b.Uhu'; - const account = accountFactory.buildWithId({ - userId: user.id, - username: user.email, - password: defaultPasswordHash, - }); - - await em.persistAndFlush([account]); - - const params: LocalAuthorizationBodyParams = { - username: user.email, - password: defaultPassword, - }; - const response = await request(app.getHttpServer()).post(`/authentication/local`).send(params).expect(200); - const jwt = (response.body as { accessToken: string }).accessToken; - - const url = await app.getUrl(); - - const ioClient = io(url, { - autoConnect: false, - path: '/board-collaboration', - transports: ['websocket', 'polling'], - extraHeaders: { - Cookie: `jwt=${jwt}`, - }, - }); - - ioClient.connect(); - - return ioClient; -} diff --git a/apps/server/src/shared/testing/cleanup-collections.ts b/apps/server/src/testing/cleanup-collections.ts similarity index 100% rename from apps/server/src/shared/testing/cleanup-collections.ts rename to apps/server/src/testing/cleanup-collections.ts diff --git a/apps/server/src/shared/testing/create-collections.ts b/apps/server/src/testing/create-collections.ts similarity index 100% rename from apps/server/src/shared/testing/create-collections.ts rename to apps/server/src/testing/create-collections.ts diff --git a/apps/server/src/shared/testing/date-to-string.ts b/apps/server/src/testing/date-to-string.ts similarity index 100% rename from apps/server/src/shared/testing/date-to-string.ts rename to apps/server/src/testing/date-to-string.ts diff --git a/apps/server/src/shared/testing/factory/axios-error.factory.ts b/apps/server/src/testing/factory/axios-error.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/axios-error.factory.ts rename to apps/server/src/testing/factory/axios-error.factory.ts diff --git a/apps/server/src/shared/testing/factory/axios-response.factory.ts b/apps/server/src/testing/factory/axios-response.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/axios-response.factory.ts rename to apps/server/src/testing/factory/axios-response.factory.ts diff --git a/apps/server/src/shared/testing/factory/base.factory.spec.ts b/apps/server/src/testing/factory/base.factory.spec.ts similarity index 100% rename from apps/server/src/shared/testing/factory/base.factory.spec.ts rename to apps/server/src/testing/factory/base.factory.spec.ts diff --git a/apps/server/src/shared/testing/factory/base.factory.ts b/apps/server/src/testing/factory/base.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/base.factory.ts rename to apps/server/src/testing/factory/base.factory.ts diff --git a/apps/server/src/shared/testing/factory/board.factory.ts b/apps/server/src/testing/factory/board.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/board.factory.ts rename to apps/server/src/testing/factory/board.factory.ts diff --git a/apps/server/src/shared/testing/factory/boardelement.factory.ts b/apps/server/src/testing/factory/boardelement.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/boardelement.factory.ts rename to apps/server/src/testing/factory/boardelement.factory.ts diff --git a/apps/server/src/shared/testing/factory/column-board-node.factory.ts b/apps/server/src/testing/factory/column-board-node.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/column-board-node.factory.ts rename to apps/server/src/testing/factory/column-board-node.factory.ts diff --git a/apps/server/src/shared/testing/factory/county.embeddable.factory.ts b/apps/server/src/testing/factory/county.embeddable.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/county.embeddable.factory.ts rename to apps/server/src/testing/factory/county.embeddable.factory.ts diff --git a/apps/server/src/shared/testing/factory/course.factory.ts b/apps/server/src/testing/factory/course.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/course.factory.ts rename to apps/server/src/testing/factory/course.factory.ts diff --git a/apps/server/src/shared/testing/factory/coursegroup.factory.ts b/apps/server/src/testing/factory/coursegroup.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/coursegroup.factory.ts rename to apps/server/src/testing/factory/coursegroup.factory.ts diff --git a/apps/server/src/shared/testing/factory/currentuser.factory.ts b/apps/server/src/testing/factory/currentuser.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/currentuser.factory.ts rename to apps/server/src/testing/factory/currentuser.factory.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/do-base.factory.spec.ts b/apps/server/src/testing/factory/domainobject/do-base.factory.spec.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/do-base.factory.spec.ts rename to apps/server/src/testing/factory/domainobject/do-base.factory.spec.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/do-base.factory.ts b/apps/server/src/testing/factory/domainobject/do-base.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/do-base.factory.ts rename to apps/server/src/testing/factory/domainobject/do-base.factory.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/domain-object.factory.spec.ts b/apps/server/src/testing/factory/domainobject/domain-object.factory.spec.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/domain-object.factory.spec.ts rename to apps/server/src/testing/factory/domainobject/domain-object.factory.spec.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/domain-object.factory.ts b/apps/server/src/testing/factory/domainobject/domain-object.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/domain-object.factory.ts rename to apps/server/src/testing/factory/domainobject/domain-object.factory.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/groups/group.factory.ts b/apps/server/src/testing/factory/domainobject/groups/group.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/groups/group.factory.ts rename to apps/server/src/testing/factory/domainobject/groups/group.factory.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/groups/index.ts b/apps/server/src/testing/factory/domainobject/groups/index.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/groups/index.ts rename to apps/server/src/testing/factory/domainobject/groups/index.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/index.ts b/apps/server/src/testing/factory/domainobject/index.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/index.ts rename to apps/server/src/testing/factory/domainobject/index.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/legacy-school.factory.ts b/apps/server/src/testing/factory/domainobject/legacy-school.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/legacy-school.factory.ts rename to apps/server/src/testing/factory/domainobject/legacy-school.factory.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/lti-tool.factory.ts b/apps/server/src/testing/factory/domainobject/lti-tool.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/lti-tool.factory.ts rename to apps/server/src/testing/factory/domainobject/lti-tool.factory.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/pseudonym.factory.ts b/apps/server/src/testing/factory/domainobject/pseudonym.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/pseudonym.factory.ts rename to apps/server/src/testing/factory/domainobject/pseudonym.factory.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/school-system-options/school-system-options.factory.ts b/apps/server/src/testing/factory/domainobject/school-system-options/school-system-options.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/school-system-options/school-system-options.factory.ts rename to apps/server/src/testing/factory/domainobject/school-system-options/school-system-options.factory.ts diff --git a/apps/server/src/shared/testing/factory/domainobject/user-login-migration-do.factory.ts b/apps/server/src/testing/factory/domainobject/user-login-migration-do.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/domainobject/user-login-migration-do.factory.ts rename to apps/server/src/testing/factory/domainobject/user-login-migration-do.factory.ts diff --git a/apps/server/src/shared/testing/factory/entity.factory.ts b/apps/server/src/testing/factory/entity.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/entity.factory.ts rename to apps/server/src/testing/factory/entity.factory.ts diff --git a/apps/server/src/shared/testing/factory/external-group-dto.factory.ts b/apps/server/src/testing/factory/external-group-dto.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/external-group-dto.factory.ts rename to apps/server/src/testing/factory/external-group-dto.factory.ts diff --git a/apps/server/src/shared/testing/factory/external-school-dto.factory.ts b/apps/server/src/testing/factory/external-school-dto.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/external-school-dto.factory.ts rename to apps/server/src/testing/factory/external-school-dto.factory.ts diff --git a/apps/server/src/shared/testing/factory/external-tool-pseudonym.factory.ts b/apps/server/src/testing/factory/external-tool-pseudonym.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/external-tool-pseudonym.factory.ts rename to apps/server/src/testing/factory/external-tool-pseudonym.factory.ts diff --git a/apps/server/src/shared/testing/factory/federal-state.factory.ts b/apps/server/src/testing/factory/federal-state.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/federal-state.factory.ts rename to apps/server/src/testing/factory/federal-state.factory.ts diff --git a/apps/server/src/shared/testing/factory/filerecord.factory.ts b/apps/server/src/testing/factory/filerecord.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/filerecord.factory.ts rename to apps/server/src/testing/factory/filerecord.factory.ts diff --git a/apps/server/src/shared/testing/factory/group-entity.factory.ts b/apps/server/src/testing/factory/group-entity.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/group-entity.factory.ts rename to apps/server/src/testing/factory/group-entity.factory.ts diff --git a/apps/server/src/shared/testing/factory/h5p-content.factory.ts b/apps/server/src/testing/factory/h5p-content.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/h5p-content.factory.ts rename to apps/server/src/testing/factory/h5p-content.factory.ts diff --git a/apps/server/src/shared/testing/factory/import-user.factory.ts b/apps/server/src/testing/factory/import-user.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/import-user.factory.ts rename to apps/server/src/testing/factory/import-user.factory.ts diff --git a/apps/server/src/testing/factory/index.ts b/apps/server/src/testing/factory/index.ts new file mode 100644 index 00000000000..66caa305250 --- /dev/null +++ b/apps/server/src/testing/factory/index.ts @@ -0,0 +1,4 @@ +/** + Import external dependencies directly, not from here. + Do not re-export here. +*/ diff --git a/apps/server/src/testing/factory/jwt-authentication.factory.ts b/apps/server/src/testing/factory/jwt-authentication.factory.ts new file mode 100644 index 00000000000..39adcb130c6 --- /dev/null +++ b/apps/server/src/testing/factory/jwt-authentication.factory.ts @@ -0,0 +1,28 @@ +import { Configuration } from '@hpi-schul-cloud/commons/lib'; +import { CreateJwtPayload } from '@infra/auth-guard'; +import jwt, { Algorithm } from 'jsonwebtoken'; + +const privateKey = Configuration.get('JWT_PRIVATE_KEY') as string; +const domain = Configuration.get('SC_DOMAIN') as string; +const algorithm = Configuration.get('JWT_SIGNING_ALGORITHM') as Algorithm; + +export class JwtAuthenticationFactory { + public static createJwt(params: CreateJwtPayload): string { + const validJwt = jwt.sign( + { + sub: params.accountId, + iss: domain, + aud: domain, + jti: 'jti', + iat: Date.now() / 1000, + exp: (Date.now() + 1000000) / 1000, + ...params, + }, + privateKey, + { + algorithm, + } + ); + return validJwt; + } +} diff --git a/apps/server/src/shared/testing/factory/jwt.test.factory.ts b/apps/server/src/testing/factory/jwt.test.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/jwt.test.factory.ts rename to apps/server/src/testing/factory/jwt.test.factory.ts diff --git a/apps/server/src/shared/testing/factory/jwtpayload.factory.ts b/apps/server/src/testing/factory/jwtpayload.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/jwtpayload.factory.ts rename to apps/server/src/testing/factory/jwtpayload.factory.ts diff --git a/apps/server/src/shared/testing/factory/legacy-file-entity-mock.factory.ts b/apps/server/src/testing/factory/legacy-file-entity-mock.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/legacy-file-entity-mock.factory.ts rename to apps/server/src/testing/factory/legacy-file-entity-mock.factory.ts diff --git a/apps/server/src/shared/testing/factory/lesson.factory.ts b/apps/server/src/testing/factory/lesson.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/lesson.factory.ts rename to apps/server/src/testing/factory/lesson.factory.ts diff --git a/apps/server/src/shared/testing/factory/ltitool.factory.ts b/apps/server/src/testing/factory/ltitool.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/ltitool.factory.ts rename to apps/server/src/testing/factory/ltitool.factory.ts diff --git a/apps/server/src/shared/testing/factory/material.factory.ts b/apps/server/src/testing/factory/material.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/material.factory.ts rename to apps/server/src/testing/factory/material.factory.ts diff --git a/apps/server/src/shared/testing/factory/news.factory.ts b/apps/server/src/testing/factory/news.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/news.factory.ts rename to apps/server/src/testing/factory/news.factory.ts diff --git a/apps/server/src/shared/testing/factory/pseudonym.factory.ts b/apps/server/src/testing/factory/pseudonym.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/pseudonym.factory.ts rename to apps/server/src/testing/factory/pseudonym.factory.ts diff --git a/apps/server/src/shared/testing/factory/readable-stream-with-file-type.factory.ts b/apps/server/src/testing/factory/readable-stream-with-file-type.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/readable-stream-with-file-type.factory.ts rename to apps/server/src/testing/factory/readable-stream-with-file-type.factory.ts diff --git a/apps/server/src/shared/testing/factory/role-dto.factory.ts b/apps/server/src/testing/factory/role-dto.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/role-dto.factory.ts rename to apps/server/src/testing/factory/role-dto.factory.ts diff --git a/apps/server/src/shared/testing/factory/role.factory.ts b/apps/server/src/testing/factory/role.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/role.factory.ts rename to apps/server/src/testing/factory/role.factory.ts diff --git a/apps/server/src/shared/testing/factory/school-entity.factory.ts b/apps/server/src/testing/factory/school-entity.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/school-entity.factory.ts rename to apps/server/src/testing/factory/school-entity.factory.ts diff --git a/apps/server/src/shared/testing/factory/school-system-options-entity.factory.ts b/apps/server/src/testing/factory/school-system-options-entity.factory.ts similarity index 89% rename from apps/server/src/shared/testing/factory/school-system-options-entity.factory.ts rename to apps/server/src/testing/factory/school-system-options-entity.factory.ts index ee6de609250..92d62571996 100644 --- a/apps/server/src/shared/testing/factory/school-system-options-entity.factory.ts +++ b/apps/server/src/testing/factory/school-system-options-entity.factory.ts @@ -1,5 +1,5 @@ import { SchoolSystemOptionsEntity, SchoolSystemOptionsEntityProps } from '@modules/legacy-school/entity'; -import { SystemProvisioningStrategy } from '../../domain/interface/system-provisioning.strategy'; +import { SystemProvisioningStrategy } from '@shared/domain/interface/system-provisioning.strategy'; import { BaseFactory } from './base.factory'; import { schoolEntityFactory } from './school-entity.factory'; import { systemEntityFactory } from './systemEntityFactory'; diff --git a/apps/server/src/shared/testing/factory/schoolyear.factory.ts b/apps/server/src/testing/factory/schoolyear.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/schoolyear.factory.ts rename to apps/server/src/testing/factory/schoolyear.factory.ts diff --git a/apps/server/src/shared/testing/factory/share-token.do.factory.ts b/apps/server/src/testing/factory/share-token.do.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/share-token.do.factory.ts rename to apps/server/src/testing/factory/share-token.do.factory.ts diff --git a/apps/server/src/shared/testing/factory/storageprovider.factory.ts b/apps/server/src/testing/factory/storageprovider.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/storageprovider.factory.ts rename to apps/server/src/testing/factory/storageprovider.factory.ts diff --git a/apps/server/src/shared/testing/factory/submission.factory.ts b/apps/server/src/testing/factory/submission.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/submission.factory.ts rename to apps/server/src/testing/factory/submission.factory.ts diff --git a/apps/server/src/shared/testing/factory/systemEntityFactory.ts b/apps/server/src/testing/factory/systemEntityFactory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/systemEntityFactory.ts rename to apps/server/src/testing/factory/systemEntityFactory.ts diff --git a/apps/server/src/shared/testing/factory/task.factory.ts b/apps/server/src/testing/factory/task.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/task.factory.ts rename to apps/server/src/testing/factory/task.factory.ts diff --git a/apps/server/src/shared/testing/factory/team.factory.ts b/apps/server/src/testing/factory/team.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/team.factory.ts rename to apps/server/src/testing/factory/team.factory.ts diff --git a/apps/server/src/shared/testing/factory/teamuser.factory.ts b/apps/server/src/testing/factory/teamuser.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/teamuser.factory.ts rename to apps/server/src/testing/factory/teamuser.factory.ts diff --git a/apps/server/src/shared/testing/factory/tldraw-file-dto.factory.ts b/apps/server/src/testing/factory/tldraw-file-dto.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/tldraw-file-dto.factory.ts rename to apps/server/src/testing/factory/tldraw-file-dto.factory.ts diff --git a/apps/server/src/shared/testing/factory/user-and-account.test.factory.spec.ts b/apps/server/src/testing/factory/user-and-account.test.factory.spec.ts similarity index 100% rename from apps/server/src/shared/testing/factory/user-and-account.test.factory.spec.ts rename to apps/server/src/testing/factory/user-and-account.test.factory.spec.ts diff --git a/apps/server/src/shared/testing/factory/user-and-account.test.factory.ts b/apps/server/src/testing/factory/user-and-account.test.factory.ts similarity index 91% rename from apps/server/src/shared/testing/factory/user-and-account.test.factory.ts rename to apps/server/src/testing/factory/user-and-account.test.factory.ts index ff86513ded0..76af4652dfa 100644 --- a/apps/server/src/shared/testing/factory/user-and-account.test.factory.ts +++ b/apps/server/src/testing/factory/user-and-account.test.factory.ts @@ -1,10 +1,10 @@ import { ObjectId } from '@mikro-orm/mongodb'; -import { AccountEntity } from '@src/modules/account/domain/entity/account.entity'; +import { AccountEntity } from '@modules/account/domain/entity/account.entity'; +import { accountFactory } from '@modules/account/testing/account.factory'; import { SchoolEntity, User } from '@shared/domain/entity'; -import { Permission } from '@shared/domain/interface'; +import { LanguageType, Permission } from '@shared/domain/interface'; import { EntityId } from '@shared/domain/types'; import _ from 'lodash'; -import { accountFactory } from '@src/modules/account/testing/account.factory'; import { userFactory } from './user.factory'; interface UserParams { @@ -13,6 +13,7 @@ interface UserParams { email?: string; school?: SchoolEntity; externalId?: string; + language?: LanguageType; } interface AccountParams { diff --git a/apps/server/src/shared/testing/factory/user-login-migration.factory.ts b/apps/server/src/testing/factory/user-login-migration.factory.ts similarity index 80% rename from apps/server/src/shared/testing/factory/user-login-migration.factory.ts rename to apps/server/src/testing/factory/user-login-migration.factory.ts index 66e8ab94a57..f8dee30ae45 100644 --- a/apps/server/src/shared/testing/factory/user-login-migration.factory.ts +++ b/apps/server/src/testing/factory/user-login-migration.factory.ts @@ -1,4 +1,4 @@ -import { IUserLoginMigration, UserLoginMigrationEntity } from '../../domain/entity/user-login-migration.entity'; +import { UserLoginMigrationEntity, IUserLoginMigration } from '@shared/domain/entity'; import { BaseFactory } from './base.factory'; import { schoolEntityFactory } from './school-entity.factory'; import { systemEntityFactory } from './systemEntityFactory'; diff --git a/apps/server/src/shared/testing/factory/user.do.factory.ts b/apps/server/src/testing/factory/user.do.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/user.do.factory.ts rename to apps/server/src/testing/factory/user.do.factory.ts diff --git a/apps/server/src/shared/testing/factory/user.factory.ts b/apps/server/src/testing/factory/user.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/user.factory.ts rename to apps/server/src/testing/factory/user.factory.ts diff --git a/apps/server/src/shared/testing/factory/video-conference.do.factory.ts b/apps/server/src/testing/factory/video-conference.do.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/video-conference.do.factory.ts rename to apps/server/src/testing/factory/video-conference.do.factory.ts diff --git a/apps/server/src/shared/testing/factory/video-conference.factory.ts b/apps/server/src/testing/factory/video-conference.factory.ts similarity index 100% rename from apps/server/src/shared/testing/factory/video-conference.factory.ts rename to apps/server/src/testing/factory/video-conference.factory.ts diff --git a/apps/server/src/testing/index.ts b/apps/server/src/testing/index.ts new file mode 100644 index 00000000000..66caa305250 --- /dev/null +++ b/apps/server/src/testing/index.ts @@ -0,0 +1,4 @@ +/** + Import external dependencies directly, not from here. + Do not re-export here. +*/ diff --git a/apps/server/src/shared/testing/map-user-to-current-user.ts b/apps/server/src/testing/map-user-to-current-user.ts similarity index 100% rename from apps/server/src/shared/testing/map-user-to-current-user.ts rename to apps/server/src/testing/map-user-to-current-user.ts diff --git a/apps/server/src/shared/testing/setup-entities.ts b/apps/server/src/testing/setup-entities.ts similarity index 100% rename from apps/server/src/shared/testing/setup-entities.ts rename to apps/server/src/testing/setup-entities.ts diff --git a/apps/server/src/shared/testing/test-api-client.spec.ts b/apps/server/src/testing/test-api-client.spec.ts similarity index 96% rename from apps/server/src/shared/testing/test-api-client.spec.ts rename to apps/server/src/testing/test-api-client.spec.ts index 553aecbe1d8..42f84a896f2 100644 --- a/apps/server/src/shared/testing/test-api-client.spec.ts +++ b/apps/server/src/testing/test-api-client.spec.ts @@ -2,7 +2,6 @@ import { ObjectId } from '@mikro-orm/mongodb'; import { Controller, Delete, - ExecutionContext, Get, Headers, HttpStatus, @@ -14,7 +13,6 @@ import { } from '@nestjs/common'; import { Test } from '@nestjs/testing'; -import { XApiKeyGuard } from '@infra/auth-guard'; import { accountFactory } from '@src/modules/account/testing'; import { TestApiClient } from './test-api-client'; @@ -261,16 +259,7 @@ describe(TestApiClient.name, () => { beforeAll(async () => { const moduleFixture = await Test.createTestingModule({ controllers: [TestXApiKeyController], - }) - .overrideGuard(XApiKeyGuard) - .useValue({ - canActivate(context: ExecutionContext) { - const req: Request = context.switchToHttp().getRequest(); - req.headers['X-API-KEY'] = API_KEY; - return true; - }, - }) - .compile(); + }).compile(); app = moduleFixture.createNestApplication(); diff --git a/apps/server/src/shared/testing/test-api-client.ts b/apps/server/src/testing/test-api-client.ts similarity index 100% rename from apps/server/src/shared/testing/test-api-client.ts rename to apps/server/src/testing/test-api-client.ts diff --git a/apps/server/src/testing/test-socket-api-client.ts b/apps/server/src/testing/test-socket-api-client.ts new file mode 100644 index 00000000000..f70bafbc260 --- /dev/null +++ b/apps/server/src/testing/test-socket-api-client.ts @@ -0,0 +1,28 @@ +import { INestApplication } from '@nestjs/common'; + +import { Socket, io } from 'socket.io-client'; + +export async function waitForEvent(socket: Socket, eventName: string): Promise { + return new Promise((resolve) => { + socket.on(eventName, (data: unknown) => { + resolve(data); + }); + }); +} + +export async function getSocketApiClient(app: INestApplication, authValue?: string): Promise { + const url = await app.getUrl(); + + const ioClient = io(url, { + autoConnect: false, + path: '/board-collaboration', + transports: ['websocket', 'polling'], + extraHeaders: { + Cookie: `jwt=${authValue || ''}`, + }, + }); + + ioClient.connect(); + + return ioClient; +} diff --git a/apps/server/src/shared/testing/user-role-permissions.ts b/apps/server/src/testing/user-role-permissions.ts similarity index 100% rename from apps/server/src/shared/testing/user-role-permissions.ts rename to apps/server/src/testing/user-role-permissions.ts diff --git a/apps/server/src/shared/testing/web-socket-ready-state-enum.ts b/apps/server/src/testing/web-socket-ready-state-enum.ts similarity index 100% rename from apps/server/src/shared/testing/web-socket-ready-state-enum.ts rename to apps/server/src/testing/web-socket-ready-state-enum.ts diff --git a/jest.config.ts b/jest.config.ts index fd916706db8..851876febd7 100644 --- a/jest.config.ts +++ b/jest.config.ts @@ -27,6 +27,7 @@ let config: Config.InitialOptions = { '^@src/(.*)$': '/apps/server/src/$1', '^@modules/(.*)$': '/apps/server/src/modules/$1', '^@infra/(.*)$': '/apps/server/src/infra/$1', + '^@testing/(.*)$': '/apps/server/src/testing/$1', }, maxWorkers: 2, // limited for not taking all workers within of a single github action workerIdleMemoryLimit: '1.5GB', // without this, jest can lead to big memory leaks and out of memory errors diff --git a/package-lock.json b/package-lock.json index 4aee4aa2569..2cfe57c1701 100644 --- a/package-lock.json +++ b/package-lock.json @@ -70,7 +70,6 @@ "commander": "^8.1.0", "compression": "^1.6.2", "cors": "^2.8.1", - "cross-env": "^7.0.0", "crypto-js": "^4.2.0", "disposable-email-domains": "^1.0.56", "es6-promisify": "^7.0.0", @@ -80,7 +79,6 @@ "feathers-hooks-common": "^8.1.1", "feathers-swagger": "^3.0.0", "file-type": "^18.5.0", - "freeport": "^1.0.5", "gm": "^1.25.0", "html-entities": "^2.3.2", "i18next": "^23.3.0", @@ -175,6 +173,7 @@ "chai": "^4.2.0", "chai-as-promised": "^7.1.1", "chai-http": "^4.2.0", + "cross-env": "^7.0.0", "esbuild": "^0.17.10", "esbuild-plugin-d.ts": "^1.3.0", "eslint": "^8.57.0", @@ -190,6 +189,7 @@ "eslint-plugin-prettier": "^4.2.1", "eslint-plugin-promise": "^7.1.0", "fishery": "^2.2.2", + "freeport": "^1.0.5", "jest": "^29.2.2", "jwt-decode": "^3.1.2", "mocha": "^9.1.3", @@ -11807,6 +11807,7 @@ }, "node_modules/cross-env": { "version": "7.0.3", + "dev": true, "license": "MIT", "dependencies": { "cross-spawn": "^7.0.1" @@ -11823,6 +11824,7 @@ }, "node_modules/cross-spawn": { "version": "7.0.3", + "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -11835,6 +11837,7 @@ }, "node_modules/cross-spawn/node_modules/which": { "version": "2.0.2", + "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -14707,6 +14710,7 @@ }, "node_modules/freeport": { "version": "1.0.5", + "dev": true, "license": "Apache-2.0" }, "node_modules/fresh": { @@ -21193,6 +21197,7 @@ }, "node_modules/path-key": { "version": "3.1.1", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -23293,6 +23298,7 @@ }, "node_modules/shebang-command": { "version": "2.0.0", + "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -23303,6 +23309,7 @@ }, "node_modules/shebang-regex": { "version": "3.0.0", + "dev": true, "license": "MIT", "engines": { "node": ">=8" diff --git a/package.json b/package.json index 15853ed6626..df8c267b310 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,6 @@ "setup:idm": "npm run setup:idm:seed && npm run setup:idm:configure", "build": "npm run nest:build", "postinstall": "node ./esbuild/esmodules-bundler.js", - "copy-files": "copyfiles src/**/*.yaml build", "inspect": "npm run build && node --inspect=5959 build/src/", "inspect-container": "npm run build && node --inspect=0.0.0.0:5959 build/src/", "start": "npm run nest:start:prod", @@ -188,7 +187,6 @@ "commander": "^8.1.0", "compression": "^1.6.2", "cors": "^2.8.1", - "cross-env": "^7.0.0", "crypto-js": "^4.2.0", "disposable-email-domains": "^1.0.56", "es6-promisify": "^7.0.0", @@ -198,7 +196,6 @@ "feathers-hooks-common": "^8.1.1", "feathers-swagger": "^3.0.0", "file-type": "^18.5.0", - "freeport": "^1.0.5", "gm": "^1.25.0", "html-entities": "^2.3.2", "i18next": "^23.3.0", @@ -257,6 +254,8 @@ "yaml": "^2.5.0" }, "devDependencies": { + "cross-env": "^7.0.0", + "freeport": "^1.0.5", "@aws-sdk/client-s3": "^3.617.0", "@faker-js/faker": "^8.0.2", "@feathersjs/adapter-tests": "^5.0.29", diff --git a/sonar-project.properties b/sonar-project.properties index 9ec5f4c132b..9a61e473c22 100644 --- a/sonar-project.properties +++ b/sonar-project.properties @@ -4,7 +4,7 @@ sonar.sources=. sonar.tests=. sonar.test.inclusions=**/*.spec.ts sonar.exclusions=**/*.js,jest.config.ts,globalSetup.ts,globalTeardown.ts,**/*.app.ts,**/seed-data/*.ts,**/migrations/mikro-orm/*.ts,**/etherpad-api-client/**/*.ts,**/authorization-api-client/**/*.ts,**/board-api-client/**/*.ts,**/generated/**/*.ts,**/room-api-client/**/*.ts,**/cards-api-client/**/*.ts,**/lessons-api-client/**/*.ts -sonar.coverage.exclusions=**/board-management.uc.ts,**/*.module.ts,**/*.factory.ts,**/migrations/mikro-orm/*.ts,**/globalSetup.ts,**/globalTeardown.ts,**/etherpad-api-client/**/*.ts,**/authorization-api-client/**/*.ts,**/board-api-client/**/*.ts,**/generated/**/*.ts,**/room-api-client/**/*.ts,apps/server/src/console/console.ts -sonar.cpd.exclusions=**/controller/dto/**/*.ts,**/api/dto/**/*.ts,**/shared/testing/factory/*.factory.ts +sonar.coverage.exclusions=**/board-management.uc.ts,**/*.module.ts,**/*.factory.ts,**/testing/**/*.ts,**/migrations/mikro-orm/*.ts,**/globalSetup.ts,**/globalTeardown.ts,**/etherpad-api-client/**/*.ts,**/authorization-api-client/**/*.ts,**/board-api-client/**/*.ts,**/generated/**/*.ts,**/room-api-client/**/*.ts,apps/server/src/console/console.ts +sonar.cpd.exclusions=**/controller/dto/**/*.ts,**/api/dto/**/*.ts,**/testing/factory/*.factory.ts sonar.javascript.lcov.reportPaths=merged-lcov.info sonar.typescript.tsconfigPaths=tsconfig.json,src/apps/server/tsconfig.app.json diff --git a/tsconfig.json b/tsconfig.json index 576c315cb61..8486cdabef1 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -21,7 +21,8 @@ "@shared/*": ["apps/server/src/shared/*"], "@src/*": ["apps/server/src/*"], "@modules/*": ["apps/server/src/modules/*"], - "@infra/*": ["apps/server/src/infra/*"] + "@infra/*": ["apps/server/src/infra/*"], + "@testing/*": ["apps/server/src/testing/*"], } } }