mirror of
https://github.com/hexastack/hexabot
synced 2025-06-26 18:27:28 +00:00
fix: unit tests
This commit is contained in:
parent
7bc5270551
commit
93bb9ee04f
@ -11,7 +11,6 @@ import { ForbiddenException, Injectable, Optional } from '@nestjs/common';
|
||||
import { InjectModel } from '@nestjs/mongoose';
|
||||
import { Document, Model, Query, TFilterQuery } from 'mongoose';
|
||||
|
||||
import { LoggerService } from '@/logger/logger.service';
|
||||
import { BaseRepository, DeleteResult } from '@/utils/generics/base-repository';
|
||||
|
||||
import { Category } from '../schemas/category.schema';
|
||||
@ -19,17 +18,13 @@ import { BlockService } from '../services/block.service';
|
||||
|
||||
@Injectable()
|
||||
export class CategoryRepository extends BaseRepository<Category> {
|
||||
private readonly logger: LoggerService;
|
||||
|
||||
private readonly blockService: BlockService;
|
||||
|
||||
constructor(
|
||||
@InjectModel(Category.name) readonly model: Model<Category>,
|
||||
@Optional() blockService?: BlockService,
|
||||
@Optional() logger?: LoggerService,
|
||||
) {
|
||||
super(model, Category);
|
||||
this.logger = logger;
|
||||
this.blockService = blockService;
|
||||
}
|
||||
|
||||
|
@ -16,6 +16,7 @@ import { BaseRepository, DeleteResult } from '@/utils/generics/base-repository';
|
||||
|
||||
import {
|
||||
Label,
|
||||
LABEL_POPULATE,
|
||||
LabelDocument,
|
||||
LabelFull,
|
||||
LabelPopulate,
|
||||
@ -31,7 +32,7 @@ export class LabelRepository extends BaseRepository<
|
||||
@InjectModel(Label.name) readonly model: Model<Label>,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
) {
|
||||
super(model, Label);
|
||||
super(model, Label, LABEL_POPULATE, LabelFull);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -19,6 +19,7 @@ import { BaseRepository } from '@/utils/generics/base-repository';
|
||||
|
||||
import {
|
||||
Message,
|
||||
MESSAGE_POPULATE,
|
||||
MessageFull,
|
||||
MessagePopulate,
|
||||
} from '../schemas/message.schema';
|
||||
@ -40,7 +41,12 @@ export class MessageRepository extends BaseRepository<
|
||||
@Optional() nlpSampleService?: NlpSampleService,
|
||||
@Optional() logger?: LoggerService,
|
||||
) {
|
||||
super(model, Message as new () => AnyMessage);
|
||||
super(
|
||||
model,
|
||||
Message as new () => AnyMessage,
|
||||
MESSAGE_POPULATE,
|
||||
MessageFull,
|
||||
);
|
||||
this.logger = logger;
|
||||
this.nlpSampleService = nlpSampleService;
|
||||
}
|
||||
|
@ -24,6 +24,7 @@ import { BaseRepository } from '@/utils/generics/base-repository';
|
||||
import { SubscriberUpdateDto } from '../dto/subscriber.dto';
|
||||
import {
|
||||
Subscriber,
|
||||
SUBSCRIBER_POPULATE,
|
||||
SubscriberDocument,
|
||||
SubscriberFull,
|
||||
SubscriberPopulate,
|
||||
@ -39,7 +40,7 @@ export class SubscriberRepository extends BaseRepository<
|
||||
@InjectModel(Subscriber.name) readonly model: Model<Subscriber>,
|
||||
private readonly eventEmitter: EventEmitter2,
|
||||
) {
|
||||
super(model, Subscriber);
|
||||
super(model, Subscriber, SUBSCRIBER_POPULATE, SubscriberFull);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -177,7 +177,10 @@ describe('BlockService', () => {
|
||||
blockFixture.name === 'hasNextBlocks' ? [hasPreviousBlocks] : [],
|
||||
}));
|
||||
|
||||
expect(blockRepository.findAndPopulate).toHaveBeenCalledWith({});
|
||||
expect(blockRepository.findAndPopulate).toHaveBeenCalledWith(
|
||||
{},
|
||||
undefined,
|
||||
);
|
||||
expect(result).toEqualPayload(blocksWithCategory);
|
||||
});
|
||||
});
|
||||
|
@ -31,7 +31,7 @@ export class NlpSampleRepository extends BaseRepository<
|
||||
@InjectModel(NlpSample.name) readonly model: Model<NlpSample>,
|
||||
private readonly nlpSampleEntityRepository: NlpSampleEntityRepository,
|
||||
) {
|
||||
super(model, NlpSample, NLP_SAMPLE_POPULATE);
|
||||
super(model, NlpSample, NLP_SAMPLE_POPULATE, NlpSampleFull);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -12,10 +12,18 @@ import { Injectable } from '@nestjs/common';
|
||||
import { BaseSeeder } from '@/utils/generics/base-seeder';
|
||||
|
||||
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
|
||||
import { NlpEntity } from '../schemas/nlp-entity.schema';
|
||||
import {
|
||||
NlpEntity,
|
||||
NlpEntityFull,
|
||||
NlpEntityPopulate,
|
||||
} from '../schemas/nlp-entity.schema';
|
||||
|
||||
@Injectable()
|
||||
export class NlpEntitySeeder extends BaseSeeder<NlpEntity> {
|
||||
export class NlpEntitySeeder extends BaseSeeder<
|
||||
NlpEntity,
|
||||
NlpEntityPopulate,
|
||||
NlpEntityFull
|
||||
> {
|
||||
constructor(nlpEntityRepository: NlpEntityRepository) {
|
||||
super(nlpEntityRepository);
|
||||
}
|
||||
|
@ -14,10 +14,18 @@ import { BaseSeeder } from '@/utils/generics/base-seeder';
|
||||
|
||||
import { NlpEntityRepository } from '../repositories/nlp-entity.repository';
|
||||
import { NlpValueRepository } from '../repositories/nlp-value.repository';
|
||||
import { NlpValue } from '../schemas/nlp-value.schema';
|
||||
import {
|
||||
NlpValue,
|
||||
NlpValueFull,
|
||||
NlpValuePopulate,
|
||||
} from '../schemas/nlp-value.schema';
|
||||
|
||||
@Injectable()
|
||||
export class NlpValueSeeder extends BaseSeeder<NlpValue> {
|
||||
export class NlpValueSeeder extends BaseSeeder<
|
||||
NlpValue,
|
||||
NlpValuePopulate,
|
||||
NlpValueFull
|
||||
> {
|
||||
constructor(
|
||||
nlpValueRepository: NlpValueRepository,
|
||||
private readonly nlpEntityRepository: NlpEntityRepository,
|
||||
|
@ -92,10 +92,8 @@ describe('ModelController', () => {
|
||||
describe('find', () => {
|
||||
it('should find models', async () => {
|
||||
jest.spyOn(modelService, 'findAndPopulate');
|
||||
const result = await modelController.find([], {});
|
||||
expect(modelService.findAndPopulate).toHaveBeenCalledWith({}, [
|
||||
'permissions',
|
||||
]);
|
||||
const result = await modelController.find(['permissions'], {});
|
||||
expect(modelService.findAndPopulate).toHaveBeenCalledWith({});
|
||||
expect(result).toEqualPayload(
|
||||
modelFixtures.map((modelFixture) => ({
|
||||
...modelFixture,
|
||||
@ -122,9 +120,7 @@ describe('ModelController', () => {
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
expect(modelService.findAndPopulate).toHaveBeenCalledWith({}, [
|
||||
'permissions',
|
||||
]);
|
||||
expect(modelService.findAndPopulate).toHaveBeenCalledWith({});
|
||||
expect(result).toEqualPayload(modelsWithPermissionsAndUsers);
|
||||
});
|
||||
});
|
||||
|
@ -148,9 +148,7 @@ describe('UserController', () => {
|
||||
it('should find one user and populate its roles', async () => {
|
||||
jest.spyOn(userService, 'findOneAndPopulate');
|
||||
const result = await userController.findOne(user.id, ['roles']);
|
||||
expect(userService.findOneAndPopulate).toHaveBeenCalledWith(user.id, [
|
||||
'roles',
|
||||
]);
|
||||
expect(userService.findOneAndPopulate).toHaveBeenCalledWith(user.id);
|
||||
expect(result).toEqualPayload(
|
||||
{
|
||||
...userFixtures.find(({ username }) => username === 'admin'),
|
||||
@ -166,9 +164,7 @@ describe('UserController', () => {
|
||||
|
||||
it('should find users, and for each user populate the corresponding roles', async () => {
|
||||
jest.spyOn(userService, 'findPageAndPopulate');
|
||||
const result = await userService.findPageAndPopulate({}, pageQuery, [
|
||||
'roles',
|
||||
]);
|
||||
const result = await userService.findPageAndPopulate({}, pageQuery);
|
||||
|
||||
const usersWithRoles = userFixtures.reduce((acc, currUser) => {
|
||||
acc.push({
|
||||
@ -181,7 +177,6 @@ describe('UserController', () => {
|
||||
expect(userService.findPageAndPopulate).toHaveBeenCalledWith(
|
||||
{},
|
||||
pageQuery,
|
||||
['roles'],
|
||||
);
|
||||
expect(result).toEqualPayload(usersWithRoles, [
|
||||
...IGNORED_FIELDS,
|
||||
|
@ -23,7 +23,7 @@ import { Model as ModelType } from './../schemas/model.schema';
|
||||
import { ModelRepository } from '../repositories/model.repository';
|
||||
import { PermissionRepository } from '../repositories/permission.repository';
|
||||
import { ModelModel } from '../schemas/model.schema';
|
||||
import { PermissionModel, Permission } from '../schemas/permission.schema';
|
||||
import { Permission, PermissionModel } from '../schemas/permission.schema';
|
||||
|
||||
describe('ModelRepository', () => {
|
||||
let modelRepository: ModelRepository;
|
||||
@ -69,7 +69,7 @@ describe('ModelRepository', () => {
|
||||
jest.spyOn(modelModel, 'find');
|
||||
const allModels = await modelRepository.findAll();
|
||||
const allPermissions = await permissionRepository.findAll();
|
||||
const result = await modelRepository.findAndPopulate({}, ['permissions']);
|
||||
const result = await modelRepository.findAndPopulate({});
|
||||
const modelsWithPermissions = allModels.reduce((acc, currModel) => {
|
||||
acc.push({
|
||||
...currModel,
|
||||
|
@ -13,6 +13,7 @@ import { MongooseModule, getModelToken } from '@nestjs/mongoose';
|
||||
import { Test, TestingModule } from '@nestjs/testing';
|
||||
import { Model } from 'mongoose';
|
||||
|
||||
import { AttachmentModel } from '@/attachment/schemas/attachment.schema';
|
||||
import { LoggerService } from '@/logger/logger.service';
|
||||
import { IGNORED_TEST_FIELDS } from '@/utils/test/constants';
|
||||
import { installPermissionFixtures } from '@/utils/test/fixtures/permission';
|
||||
@ -53,7 +54,12 @@ describe('UserRepository', () => {
|
||||
const module: TestingModule = await Test.createTestingModule({
|
||||
imports: [
|
||||
rootMongooseTestModule(installPermissionFixtures),
|
||||
MongooseModule.forFeature([UserModel, PermissionModel, RoleModel]),
|
||||
MongooseModule.forFeature([
|
||||
UserModel,
|
||||
PermissionModel,
|
||||
RoleModel,
|
||||
AttachmentModel,
|
||||
]),
|
||||
],
|
||||
providers: [
|
||||
LoggerService,
|
||||
@ -85,9 +91,7 @@ describe('UserRepository', () => {
|
||||
describe('findOneAndPopulate', () => {
|
||||
it('should find one user and populate its role', async () => {
|
||||
jest.spyOn(userModel, 'findById');
|
||||
const result = await userRepository.findOneAndPopulate(user.id, [
|
||||
'roles',
|
||||
]);
|
||||
const result = await userRepository.findOneAndPopulate(user.id);
|
||||
expect(userModel.findById).toHaveBeenCalledWith(user.id);
|
||||
expect(result).toEqualPayload(
|
||||
{
|
||||
@ -106,9 +110,7 @@ describe('UserRepository', () => {
|
||||
jest.spyOn(userRepository, 'findPageAndPopulate');
|
||||
const allUsers = await userRepository.findAll();
|
||||
const allRoles = await roleRepository.findAll();
|
||||
const result = await userRepository.findPageAndPopulate({}, pageQuery, [
|
||||
'roles',
|
||||
]);
|
||||
const result = await userRepository.findPageAndPopulate({}, pageQuery);
|
||||
const usersWithRoles = allUsers.reduce((acc, currUser) => {
|
||||
acc.push({
|
||||
...currUser,
|
||||
|
@ -12,10 +12,10 @@ import { Injectable } from '@nestjs/common';
|
||||
import { BaseSeeder } from '@/utils/generics/base-seeder';
|
||||
|
||||
import { ModelRepository } from '../repositories/model.repository';
|
||||
import { Model } from '../schemas/model.schema';
|
||||
import { Model, ModelFull, ModelPopulate } from '../schemas/model.schema';
|
||||
|
||||
@Injectable()
|
||||
export class ModelSeeder extends BaseSeeder<Model> {
|
||||
export class ModelSeeder extends BaseSeeder<Model, ModelPopulate, ModelFull> {
|
||||
constructor(private readonly modelRepository: ModelRepository) {
|
||||
super(modelRepository);
|
||||
}
|
||||
|
@ -12,10 +12,18 @@ import { Injectable } from '@nestjs/common';
|
||||
import { BaseSeeder } from '@/utils/generics/base-seeder';
|
||||
|
||||
import { PermissionRepository } from '../repositories/permission.repository';
|
||||
import { Permission } from '../schemas/permission.schema';
|
||||
import {
|
||||
Permission,
|
||||
PermissionFull,
|
||||
PermissionPopulate,
|
||||
} from '../schemas/permission.schema';
|
||||
|
||||
@Injectable()
|
||||
export class PermissionSeeder extends BaseSeeder<Permission> {
|
||||
export class PermissionSeeder extends BaseSeeder<
|
||||
Permission,
|
||||
PermissionPopulate,
|
||||
PermissionFull
|
||||
> {
|
||||
constructor(private readonly permissionRepository: PermissionRepository) {
|
||||
super(permissionRepository);
|
||||
}
|
||||
|
@ -12,10 +12,10 @@ import { Injectable } from '@nestjs/common';
|
||||
import { BaseSeeder } from '@/utils/generics/base-seeder';
|
||||
|
||||
import { RoleRepository } from '../repositories/role.repository';
|
||||
import { Role } from '../schemas/role.schema';
|
||||
import { Role, RoleFull, RolePopulate } from '../schemas/role.schema';
|
||||
|
||||
@Injectable()
|
||||
export class RoleSeeder extends BaseSeeder<Role> {
|
||||
export class RoleSeeder extends BaseSeeder<Role, RolePopulate, RoleFull> {
|
||||
constructor(private readonly roleRepository: RoleRepository) {
|
||||
super(roleRepository);
|
||||
}
|
||||
|
@ -12,10 +12,10 @@ import { Injectable } from '@nestjs/common';
|
||||
import { BaseSeeder } from '@/utils/generics/base-seeder';
|
||||
|
||||
import { UserRepository } from '../repositories/user.repository';
|
||||
import { User } from '../schemas/user.schema';
|
||||
import { User, UserFull, UserPopulate } from '../schemas/user.schema';
|
||||
|
||||
@Injectable()
|
||||
export class UserSeeder extends BaseSeeder<User> {
|
||||
export class UserSeeder extends BaseSeeder<User, UserPopulate, UserFull> {
|
||||
constructor(private readonly userRepository: UserRepository) {
|
||||
super(userRepository);
|
||||
}
|
||||
|
@ -70,7 +70,7 @@ describe('ModelService', () => {
|
||||
jest.spyOn(modelRepository, 'findAndPopulate');
|
||||
const models = await modelRepository.findAll();
|
||||
const permissions = await permissionRepository.findAll();
|
||||
const result = await modelService.findAndPopulate({}, ['permissions']);
|
||||
const result = await modelService.findAndPopulate({});
|
||||
const modelsWithPermissions = models.reduce((acc, currModel) => {
|
||||
acc.push({
|
||||
...currModel,
|
||||
@ -80,9 +80,10 @@ describe('ModelService', () => {
|
||||
});
|
||||
return acc;
|
||||
}, []);
|
||||
expect(modelRepository.findAndPopulate).toHaveBeenCalledWith({}, [
|
||||
'permissions',
|
||||
]);
|
||||
expect(modelRepository.findAndPopulate).toHaveBeenCalledWith(
|
||||
{},
|
||||
undefined,
|
||||
);
|
||||
expect(result).toEqualPayload(modelsWithPermissions);
|
||||
});
|
||||
});
|
||||
|
@ -99,10 +99,8 @@ describe('UserService', () => {
|
||||
describe('findOneAndPopulate', () => {
|
||||
it('should find one user and populate its role', async () => {
|
||||
jest.spyOn(userRepository, 'findOneAndPopulate');
|
||||
const result = await userService.findOneAndPopulate(user.id, ['roles']);
|
||||
expect(userRepository.findOneAndPopulate).toHaveBeenCalledWith(user.id, [
|
||||
'roles',
|
||||
]);
|
||||
const result = await userService.findOneAndPopulate(user.id);
|
||||
expect(userRepository.findOneAndPopulate).toHaveBeenCalledWith(user.id);
|
||||
expect(result).toEqualPayload(
|
||||
{
|
||||
...userFixtures.find(({ username }) => username === 'admin'),
|
||||
@ -118,9 +116,7 @@ describe('UserService', () => {
|
||||
const pageQuery = getPageQuery<User>({ sort: ['_id', 'asc'] });
|
||||
jest.spyOn(userRepository, 'findPageAndPopulate');
|
||||
const allUsers = await userRepository.findAll();
|
||||
const result = await userService.findPageAndPopulate({}, pageQuery, [
|
||||
'roles',
|
||||
]);
|
||||
const result = await userService.findPageAndPopulate({}, pageQuery);
|
||||
const usersWithRoles = allUsers.reduce((acc, currUser) => {
|
||||
acc.push({
|
||||
...currUser,
|
||||
@ -132,7 +128,6 @@ describe('UserService', () => {
|
||||
expect(userRepository.findPageAndPopulate).toHaveBeenCalledWith(
|
||||
{},
|
||||
pageQuery,
|
||||
['roles'],
|
||||
);
|
||||
expect(result).toEqualPayload(usersWithRoles);
|
||||
});
|
||||
|
@ -7,7 +7,6 @@
|
||||
* 3. SaaS Restriction: This software, or any derivative of it, may not be used to offer a competing product or service (SaaS) without prior written consent from Hexastack. Offering the software as a service or using it in a commercial cloud environment without express permission is strictly prohibited.
|
||||
*/
|
||||
|
||||
import { LoggerService } from '@nestjs/common';
|
||||
import { Cache } from 'cache-manager';
|
||||
|
||||
export function Cacheable(cacheKey: string) {
|
||||
@ -20,7 +19,6 @@ export function Cacheable(cacheKey: string) {
|
||||
|
||||
descriptor.value = async function (...args: any[]) {
|
||||
const cache: Cache = this.cacheManager;
|
||||
const logger: LoggerService = this.logger; // Access the logger from the instance
|
||||
|
||||
if (!cache) {
|
||||
throw new Error(
|
||||
@ -28,19 +26,15 @@ export function Cacheable(cacheKey: string) {
|
||||
);
|
||||
}
|
||||
|
||||
if (!logger) {
|
||||
throw new Error('Cacheable() requires the the logger service.');
|
||||
}
|
||||
|
||||
// Try to get cached data
|
||||
try {
|
||||
const cachedResult = await cache.get(cacheKey);
|
||||
if (cachedResult) {
|
||||
logger.debug(`Cache hit for key: ${cacheKey}`);
|
||||
return cachedResult;
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(`Cache get error for key: ${cacheKey}:`, error);
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`Cache get error for key: ${cacheKey}:`, error);
|
||||
}
|
||||
|
||||
// Call the original method if cache miss
|
||||
@ -49,9 +43,9 @@ export function Cacheable(cacheKey: string) {
|
||||
// Set the new result in cache
|
||||
try {
|
||||
await cache.set(cacheKey, result);
|
||||
logger.debug(`Cache set for key: ${cacheKey}`);
|
||||
} catch (error) {
|
||||
logger.error(`Cache set error for key: ${cacheKey}:`, error);
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`Cache set error for key: ${cacheKey}:`, error);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
@ -161,9 +161,7 @@ export abstract class BaseRepository<
|
||||
}
|
||||
|
||||
async findOneAndPopulate(criteria: string | TFilterQuery<T>) {
|
||||
if (!this.populate || !this.clsPopulate) {
|
||||
throw new Error('Cannot populate query');
|
||||
}
|
||||
this.ensureCanPopulate();
|
||||
const query = this.findOneQuery(criteria).populate(this.populate);
|
||||
return await this.executeOne(query, this.clsPopulate);
|
||||
}
|
||||
|
@ -10,8 +10,12 @@
|
||||
import { BaseRepository } from './base-repository';
|
||||
import { BaseSchema } from './base-schema';
|
||||
|
||||
export abstract class BaseSeeder<T, P extends string = never> {
|
||||
constructor(protected readonly repository: BaseRepository<T, P>) {}
|
||||
export abstract class BaseSeeder<
|
||||
T,
|
||||
P extends string = never,
|
||||
TFull extends Omit<T, P> = never,
|
||||
> {
|
||||
constructor(protected readonly repository: BaseRepository<T, P, TFull>) {}
|
||||
|
||||
async findAll(): Promise<T[]> {
|
||||
return await this.repository.findAll();
|
||||
|
Loading…
Reference in New Issue
Block a user