Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

test: remove-users #406

Merged
merged 1 commit into from
Oct 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 95 additions & 3 deletions backend/src/auth/facade/auth.facade.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { CreateUserDto } from 'src/users/dto/create-user.dto';
import {
BadRequestException,
ConflictException,
ForbiddenException,
NotFoundException,
UnauthorizedException,
} from '@nestjs/common';
Expand All @@ -18,6 +19,7 @@ import { Role } from 'src/users/entities/role.entity';
import { TokenResponse } from '../api/response/token.response';
import { EmailService } from '../../email/service/email.service';
import { UserStatusEnum } from '../../users/enums/user-status.enum';
import { PermissionEnum } from 'src/users/enums/permission.enum';

describe('AuthFacade', () => {
let facade: AuthFacade;
Expand Down Expand Up @@ -135,6 +137,20 @@ describe('AuthFacade', () => {
createdAt: null,
updatedAt: null,
},
{
id: '3',
name: 'Test User 3',
email: '[email protected]',
description: 'Lorem ipsum dolor sit amet 3',
profilePhotoUrl: 'https://example3.com/profile.jpg',
status: UserStatusEnum.PENDING,
hotAddresses: ['addr1', 'addr2'],
role: mockRoles[2].code,
permissions: [],
deactivatedAt: null,
createdAt: null,
updatedAt: null,
},
];

const mockTokenResponse: TokenResponse = {
Expand Down Expand Up @@ -233,6 +249,7 @@ describe('AuthFacade', () => {
}
return user;
}),
checkRoleManagedByPermission: jest.fn(),
};

const mockAuthService = {
Expand Down Expand Up @@ -408,7 +425,7 @@ describe('AuthFacade', () => {
});

describe('Validate User', () => {
it('should validate user by email', async () => {
it('should find user by email', async () => {
const email = '[email protected]';
const userDto: UserDto = {
id: '1',
Expand All @@ -425,7 +442,7 @@ describe('AuthFacade', () => {
updatedAt: null,
};

const result = await facade.validateUser(email);
const result = await facade.findUserByEmail(email);

expect(result).toEqual(userDto);
expect(mockUserService.findByEmail).toHaveBeenCalledWith(email);
Expand All @@ -435,7 +452,7 @@ describe('AuthFacade', () => {
const email = '[email protected]';

try {
await facade.validateUser(email);
await facade.findUserByEmail(email);
} catch (e) {
expect(e).toBeInstanceOf(NotFoundException);
expect(e.message).toBe(`User with this email address not found`);
Expand Down Expand Up @@ -534,4 +551,79 @@ describe('AuthFacade', () => {
);
});
});

describe('Check Ability Resend Register Invite', () => {
it('should call checkRoleManagedByPermission if user status is PENDING', async () => {
const mockUser = mockUsers[2];
jest.spyOn(facade, 'findUserByEmail').mockResolvedValue(mockUser);
const permissions = [PermissionEnum.MANAGE_CC_MEMBERS];

await facade.checkAbilityResendRegisterInvite(
mockUser.email,
permissions,
);

expect(facade.findUserByEmail).toHaveBeenCalledWith(mockUser.email);
expect(mockUserService.checkRoleManagedByPermission).toHaveBeenCalledWith(
mockUser.role,
permissions,
);
});

it(`should throw error if user's status is not PENDING`, async () => {
const mockUser = mockUsers[1];
jest.spyOn(facade, 'findUserByEmail').mockResolvedValue(mockUser);
const permissions = [PermissionEnum.MANAGE_CC_MEMBERS];

try {
await facade.checkAbilityResendRegisterInvite(
mockUser.email,
permissions,
);
} catch (e) {
expect(e).toBeInstanceOf(ConflictException);
expect(e.status).toEqual(409);
expect(e.message).toEqual(`Unable to resend register invite`);
}
});

it('should throw NotFoundException if user with given email is not found', async () => {
const mockUser = mockUsers[2];
mockUser.email = '[email protected]';
jest
.spyOn(facade, 'findUserByEmail')
.mockRejectedValue(
new NotFoundException(`User with this email address not found`),
);
const permissions = [PermissionEnum.MANAGE_CC_MEMBERS];
try {
await facade.checkAbilityResendRegisterInvite(
mockUser.email,
permissions,
);
} catch (e) {
expect(e).toBeInstanceOf(NotFoundException);
expect(e.status).toEqual(404);
expect(e.message).toEqual(`User with this email address not found`);
}
});

it('should call checkRoleManagedByPermission if user status is PENDING', async () => {
const mockUser = mockUsers[2];
mockUser.role = RoleEnum.ADMIN;
jest.spyOn(facade, 'findUserByEmail').mockResolvedValue(mockUser);
const permissions = [PermissionEnum.ADD_CONSTITUTION];

try {
await facade.checkAbilityResendRegisterInvite(
mockUser.email,
permissions,
);
} catch (e) {
expect(e).toBeInstanceOf(ForbiddenException);
expect(e.status).toEqual(403);
expect(e.message).toEqual(`You have no permission for this action`);
}
});
});
});
6 changes: 6 additions & 0 deletions backend/src/constitution/facade/constitution.facade.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,12 +59,16 @@ describe('ConstitutionFacade', () => {
const mockFirstConstitutionMetadataResponse: ConstitutionMetadataResponse = {
title: 'Revision 1',
cid: 'bafkreibxlpnlpsg6ewqzxhslwyhzl4p4vc6bifj3nb4k2lxhbnfaojbmwy',
blake2b: 'f6f811fbde53b09c1b653766f27578cc867e9b634b9142800f56e282b041de00',
url: 'https://ipfs.io/ipfs/bafkreibxlpnlpsg6ewqzxhslwyhzl4p4vc6bifj3nb4k2lxhbnfaojbmwy',
version: '1713769514',
createdDate: '2024-04-21 11:21:59.334',
};

const mockFirstConstitutionResponse: ConstitutionResponse = {
cid: 'bafkreibxlpnlpsg6ewqzxhslwyhzl4p4vc6bifj3nb4k2lxhbnfaojbmwy',
blake2b: 'f6f811fbde53b09c1b653766f27578cc867e9b634b9142800f56e282b041de00',
url: 'https://ipfs.io/ipfs/bafkreibxlpnlpsg6ewqzxhslwyhzl4p4vc6bifj3nb4k2lxhbnfaojbmwy',
version: '1713769514',
contents:
'The morning sun cast a golden glow over the tranquil village, painting the cobblestone streets with warmth. Birds chirped melodiously, adding to the serene ambiance that enveloped the small community. Life moved at a leisurely pace here, far removed from the hustle and bustle of the city. Neighbors greeted each other with smiles and friendly nods as they went about their daily routines, weaving a tight-knit tapestry of camaraderie.\n',
Expand Down Expand Up @@ -93,6 +97,8 @@ describe('ConstitutionFacade', () => {
const mockSecondConstitutionMetadataResponse: ConstitutionMetadataResponse = {
title: 'Revision 2',
cid: 'bafkreich5c3rbz4amwevqy676czysmr27ctby46zdhja7gnpzriyqwdv4i',
blake2b: 'f6f811fbde53b09c1b653766f27578cc867e9b634b9142800f56e282b041de00',
url: 'https://ipfs.io/ipfs/bafkreich5c3rbz4amwevqy676czysmr27ctby46zdhja7gnpzriyqwdv4i',
version: '1713769479',
createdDate: '2024-04-22 11:21:59.334',
};
Expand Down
23 changes: 20 additions & 3 deletions backend/src/governance/facade/governance.facade.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ describe('GovernanceFacade', () => {
status: UserStatusEnum.ACTIVE,
role: null,
permissions: [],
rationales: null,
votes: null,
createdAt: null,
updatedAt: null,
deactivatedAt: null,
Expand All @@ -50,6 +52,8 @@ describe('GovernanceFacade', () => {
status: UserStatusEnum.ACTIVE,
role: null,
permissions: [],
rationales: null,
votes: null,
createdAt: null,
updatedAt: null,
deactivatedAt: null,
Expand All @@ -69,6 +73,8 @@ describe('GovernanceFacade', () => {
hasRationale: null,
submitTime: null,
endTime: null,
votedBy: null,
rationaleBy: null,
},
{
id: '2',
Expand All @@ -82,6 +88,8 @@ describe('GovernanceFacade', () => {
hasRationale: null,
submitTime: null,
endTime: null,
votedBy: null,
rationaleBy: null,
},
];

Expand Down Expand Up @@ -568,7 +576,7 @@ describe('GovernanceFacade', () => {

expect(
mockGovernanceService.searchGovActionProposals,
).toHaveBeenCalledWith(query, userId);
).toHaveBeenCalledWith(query);
});

it('should return an empty array - not found by userId', async () => {
Expand All @@ -578,13 +586,22 @@ describe('GovernanceFacade', () => {
limit: 10,
path: 'randomPath',
};
mockGovernanceService.searchGovActionProposals.mockReturnValueOnce({
items: [],
itemCount: 0,
pageOptions: {
page: query.page,
perPage: query.limit,
skip: 10,
},
} as PaginatedDto<GovActionProposalDto>);

const result = await facade.searchGovActionProposals(query, userId);

expect(result.data).toEqual([]);
expect(
mockGovernanceService.searchGovActionProposals,
).toHaveBeenCalledWith(query, userId);
).toHaveBeenCalledWith(query);
});

it('should return an empty array - not found by search parameter', async () => {
Expand All @@ -601,7 +618,7 @@ describe('GovernanceFacade', () => {
expect(result.data).toEqual([]);
expect(
mockGovernanceService.searchGovActionProposals,
).toHaveBeenCalledWith(query, userId);
).toHaveBeenCalledWith(query);
});
});
});
41 changes: 35 additions & 6 deletions backend/src/governance/services/governance.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ import { PaginatedDto } from 'src/util/pagination/dto/paginated.dto';
import { VoteDto } from '../dto/vote.dto';
import { VoteStatus } from '../enums/vote-status.enum';
import { VoteValue } from '../enums/vote-value.enum';
import { User } from 'src/users/entities/user.entity';
import { UserStatusEnum } from 'src/users/enums/user-status.enum';
import { RoleEnum } from 'src/users/enums/role.enum';

describe('IpfsService', () => {
let service: GovernanceService;
Expand All @@ -30,6 +33,8 @@ describe('IpfsService', () => {
hasRationale: null,
submitTime: null,
endTime: null,
votedBy: null,
rationaleBy: null,
},
{
id: '2',
Expand All @@ -43,6 +48,8 @@ describe('IpfsService', () => {
hasRationale: null,
submitTime: null,
endTime: null,
votedBy: null,
rationaleBy: null,
},
];

Expand Down Expand Up @@ -92,9 +99,34 @@ describe('IpfsService', () => {
},
];

const mockUser: User = {
id: 'userId',
name: 'John Doe',
email: 'mockedEmail',
description: 'mockedDescription',
profilePhotoUrl: 'mockedProfilePhoto',
status: UserStatusEnum.ACTIVE,
role: {
id: 'roleId3',
code: RoleEnum.USER,
users: [],
permissions: [],
createdAt: null,
updatedAt: null,
},
permissions: null,
hotAddresses: null,
rationales: null,
votes: null,
deactivatedAt: null,
createdAt: null,
updatedAt: null,
};

const vote: Vote = {
id: '1',
userId: 'userId',
user: mockUser,
hotAddress: 'hotAddress_1',
govActionProposal: mockGovActionProposals[0],
vote: VoteValue.Yes,
Expand All @@ -109,6 +141,7 @@ describe('IpfsService', () => {
{
id: 'Vote_1',
userId: 'User_1',
user: mockUser,
hotAddress: 'hotAddress_1',
govActionProposal: mockGovActionProposals[0],
vote: VoteValue.Yes,
Expand All @@ -121,6 +154,7 @@ describe('IpfsService', () => {
{
id: 'Vote_2',
userId: 'User_1',
user: mockUser,
hotAddress: 'hotAddress_1',
govActionProposal: mockGovActionProposals[1],
vote: VoteValue.Yes,
Expand Down Expand Up @@ -448,9 +482,6 @@ describe('IpfsService', () => {
search: 'govActionProposal_Title',
path: 'randomPath',
};
jest
.spyOn<any, any>(service, 'returnGapQuery')
.mockResolvedValueOnce(mockGovActionProposals[0]);
mockPaginator.paginate.mockResolvedValue(paginatedValueGap);
const gapPaginatedDto: PaginatedDto<GovActionProposalDto> =
await service.searchGovActionProposals(query);
Expand All @@ -468,7 +499,6 @@ describe('IpfsService', () => {
search: 'NotExisting',
path: 'randomPath',
};
jest.spyOn<any, any>(service, 'returnGapQuery').mockResolvedValueOnce([]);
mockPaginator.paginate.mockResolvedValueOnce(paginatedEmptyValueGap);
const gapPaginatedDto: PaginatedDto<GovActionProposalDto> =
await service.searchGovActionProposals(query);
Expand Down Expand Up @@ -502,10 +532,9 @@ describe('IpfsService', () => {
limit: 10,
path: 'randomPath',
};
const userId = 'user1';
mockPaginator.paginate.mockResolvedValueOnce(paginatedMultiValueGap);
const gapPaginatedDto: PaginatedDto<GovActionProposalDto> =
await service.searchGovActionProposals(query, userId);
await service.searchGovActionProposals(query);
expect(gapPaginatedDto.items[0].title).toEqual(
mockGovActionProposals[0].title,
);
Expand Down
10 changes: 7 additions & 3 deletions backend/src/s3/service/s3.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ const mockBucket = {
};

const mockConfigService = {
get: jest.fn().mockImplementation((minioBucked) => {
if (minioBucked === 'MINIO_BUCKET') {
get: jest.fn().mockImplementation((variable) => {
if (variable === 'MINIO_BUCKET') {
return 'cc-portal';
}
if (variable === 'S3_BASE_URL') {
return 'https://cc-portal.s3.amazonaws.com';
}
}),
};

Expand Down Expand Up @@ -88,13 +91,14 @@ describe('S3Service', () => {
const result = await service.uploadFile(context, fileName, file);

expect(result).toBe(
'https://cc-portal.s3.amazonaws.com/profile-photo-test-upload.txt',
'https://cc-portal.s3.amazonaws.com/cc-portal/profile-photo-test-upload.txt',
);
expect(mockMinioClient.putObject).toHaveBeenCalledWith(
'cc-portal',
'profile-photo-test-upload.txt',
expect.any(Buffer),
100,
{ 'Content-Type': undefined },
);
});

Expand Down
Loading
Loading