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

Semkiv/chat remake #1244

Merged
merged 24 commits into from
Oct 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
9a91685
created endpoint to get or create chatroom by applicationID
min4uk Sep 22, 2023
860257d
Changed method, to return full chatRoomWorkshopDto
min4uk Sep 22, 2023
964b143
Added ChatRoomId parameter to messageCreateDto
min4uk Sep 22, 2023
3127fc9
Changed CreateOrReturnExisting method to GetById for chatRoomDto
min4uk Sep 22, 2023
94055ea
added check for chatRoom existing in sendmessage method
min4uk Sep 22, 2023
2496067
Fix for ChatWorkshopController
min4uk Sep 22, 2023
50f47fd
removed redundant request to database
min4uk Sep 22, 2023
064c680
fix positive test
min4uk Sep 22, 2023
720f7b8
Removed unused endpoints for ministry admin
min4uk Sep 22, 2023
c5d8eb0
removed unused method for ministryAdmin
min4uk Sep 25, 2023
7b6d049
corrected spelling
min4uk Sep 25, 2023
da38ac5
added Provider validation for GetById method in applicationService
min4uk Sep 28, 2023
126aa5d
added new endpoint for getting chatroom for parent from workshop page
min4uk Sep 28, 2023
8524383
changed parent validation
min4uk Sep 28, 2023
331c70e
removed test, that was checking the logic that was changed
min4uk Sep 29, 2023
04f8df3
added obsolete attribute to unused endpoints and methods
min4uk Sep 29, 2023
b202d8f
fixed test
min4uk Oct 6, 2023
08f75b6
Added test to return fail message to sender when ChatRoom not exist
min4uk Oct 6, 2023
fc3a1e5
added obsolete attribute to unused methods
min4uk Oct 6, 2023
ccb37f2
Added ignore attributes for tests of methods that are not used
min4uk Oct 10, 2023
7230c3c
Added negative test
min4uk Oct 10, 2023
19e4a0b
Add tests for GetChatRoomIdsByWorkshopIdsAsync method
min4uk Oct 10, 2023
4b6f468
removed code smells
min4uk Oct 10, 2023
801784d
fixed incorect test
min4uk Oct 11, 2023
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
57 changes: 14 additions & 43 deletions OutOfSchool/OutOfSchool.WebApi.Tests/Hubs/ChatWorkshopHubTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -163,10 +163,12 @@ public async Task SendMessageToOthersInGroup_WhenUserSetsNotOwnParentId_ShouldWr

var invalidParentId = Guid.NewGuid();

var chatNewMessage = $"{{'workshopId':'{Guid.NewGuid()}', 'parentId':'{invalidParentId}', 'text':'hi', 'senderRoleIsProvider':false}}";
var chatNewMessage = $"{{'workshopId':'{Guid.NewGuid()}', 'parentId':'{invalidParentId}', 'chatRoomId':'{Guid.NewGuid()}', 'text':'hi', 'senderRoleIsProvider':false}}";

validationServiceMock.Setup(x => x.UserIsParentOwnerAsync(UserId, invalidParentId)).ReturnsAsync(false);

roomServiceMock.Setup(x => x.GetByIdAsync(It.IsAny<Guid>())).ReturnsAsync(new ChatRoomWorkshopDto());

clientsMock.Setup(clients => clients.Caller).Returns(clientProxyMock.Object);

// Act
Expand All @@ -187,10 +189,13 @@ public async Task SendMessageToOthersInGroup_WhenParamsAreValidAndChatRoomExists

var validWorkshopId = Guid.NewGuid();
var validParentId = Guid.NewGuid();
var validNewMessage = $"{{'workshopId':'{validWorkshopId}', 'parentId':'{validParentId}', 'text':'hi', 'senderRoleIsProvider':true}}";
var validChatRoomId = Guid.NewGuid();
var validNewMessage = $"{{'workshopId':'{validWorkshopId}', 'parentId':'{validParentId}', 'chatRoomId':'{validChatRoomId}', 'text':'hi', 'senderRoleIsProvider':true}}";

validationServiceMock.Setup(x => x.UserIsWorkshopOwnerAsync(UserId, validWorkshopId, Subrole.None)).ReturnsAsync(true);

roomServiceMock.Setup(x => x.GetByIdAsync(validChatRoomId)).ReturnsAsync(new ChatRoomWorkshopDto());

var validCreatedMessage = new ChatMessageWorkshopDto()
{
Id = Guid.NewGuid(),
Expand Down Expand Up @@ -227,54 +232,20 @@ public async Task SendMessageToOthersInGroup_WhenParamsAreValidAndChatRoomExists
}

[Test]
public async Task SendMessageToOthersInGroup_WhenParamsAreValidAndChatRoomDoesNotExists_ShouldSaveMessageAndSendMessageToGroup()
public async Task SendMessageToOthersInGroup_WhenChatRoomDoesNotExist_ShouldWriteMessageToCallerWithException()
{
// Arrange
var userRole = Role.Parent.ToString();
hubCallerContextMock.Setup(x => x.User.FindFirst(IdentityResourceClaimsTypes.Role))
.Returns(new Claim(IdentityResourceClaimsTypes.Role, userRole));

var validParentId = Guid.NewGuid();

var validNewMessage = $"{{'workshopId':'{Guid.NewGuid()}', 'parentId':'{validParentId}', 'text':'hi', 'senderRoleIsProvider':false}}";

validationServiceMock.Setup(x => x.UserIsParentOwnerAsync(UserId, validParentId)).ReturnsAsync(true);

var validChatRoom = new ChatRoomWorkshopDto() { Id = Guid.NewGuid(), WorkshopId = Guid.NewGuid(), ParentId = validParentId, };
roomServiceMock.Setup(x => x.CreateOrReturnExistingAsync(It.IsAny<Guid>(), It.IsAny<Guid>()))
.ReturnsAsync(validChatRoom);

var validCreatedMessage = new ChatMessageWorkshopDto()
{
Id = Guid.NewGuid(),
SenderRoleIsProvider = false,
Text = "hi",
ChatRoomId = validChatRoom.Id,
CreatedDateTime = DateTimeOffset.UtcNow,
ReadDateTime = null,
};
messageServiceMock.Setup(x => x.CreateAsync(It.IsAny<ChatMessageWorkshopCreateDto>(), It.IsAny<Role>()))
.ReturnsAsync(validCreatedMessage);

var validParent = new Parent() { Id = validParentId, UserId = UserId };
parentRepositoryMock.Setup(x => x.GetById(validParentId)).ReturnsAsync(validParent);

var validWorkshops = new List<Workshop>() { new Workshop() { Id = validChatRoom.WorkshopId, Provider = new Provider() { UserId = "someId" } } };
workshopRepositoryMock.Setup(x => x.GetByFilter(It.IsAny<Expression<Func<Workshop, bool>>>(), It.IsAny<string>())).ReturnsAsync(validWorkshops);

groupsMock.Setup(x => x.AddToGroupAsync(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<CancellationToken>()))
.Returns(Task.CompletedTask);
var chatNewMessage = $"{{'workshopId':'{Guid.NewGuid()}', 'parentId':'{Guid.NewGuid()}', 'chatRoomId':'{Guid.NewGuid()}', 'text':'hi', 'senderRoleIsProvider':false}}";

clientsMock.Setup(clients => clients.Group(It.IsAny<string>())).Returns(clientProxyMock.Object);
roomServiceMock.Setup(x => x.GetByIdAsync(It.IsAny<Guid>())).ReturnsAsync(null as ChatRoomWorkshopDto);

var validProviderAdmins = new List<ProviderAdmin>();
providerAdminRepositoryMock.Setup(x => x.GetByFilter(It.IsAny<Expression<Func<ProviderAdmin, bool>>>(), It.IsAny<string>())).ReturnsAsync(validProviderAdmins);
clientsMock.Setup(clients => clients.Caller).Returns(clientProxyMock.Object);

// Act
await chatHub.SendMessageToOthersInGroupAsync(validNewMessage).ConfigureAwait(false);
await chatHub.SendMessageToOthersInGroupAsync(chatNewMessage).ConfigureAwait(false);

// Assert
messageServiceMock.Verify(x => x.CreateAsync(It.IsAny<ChatMessageWorkshopCreateDto>(), It.IsAny<Role>()), Times.Once);
clientsMock.Verify(clients => clients.Group(validChatRoom.Id.ToString()), Times.Once);
clientsMock.Verify(clients => clients.Caller, Times.Once);
clientsMock.Verify(clients => clients.Group(It.IsAny<string>()), Times.Never);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ public async Task GetApplications_WhenCalled_ShouldReturnApplications()
var result = await service.GetAll(new ApplicationFilter());

// Assert
Assert.AreEqual(result.Entities.Count, application.Count());
Assert.AreEqual(result.Entities.Count, application.Count);
}

[Test]
Expand Down Expand Up @@ -300,16 +300,33 @@ public void CreateApplication_WhenModelIsNull_ShouldThrowArgumentException()
}

[Test]
public void CreateApplication_WhenLimitIsExceeded_ShouldThrowArgumentException()
public async Task CreateApplication_WhenLimitIsExceeded_ShouldThrowArgumentException()
{
// Arrange
var application = new ApplicationCreate()
{
WorkshopId = new Guid("0083633f-4e5b-4c09-a89d-52d8a9b89cdb"),
};

// Act and Assert
service.Invoking(w => w.Create(application)).Should().ThrowAsync<ArgumentException>();
currentUserServiceMock.Setup(x => x.UserHasRights(It.IsAny<ParentRights>())).Returns(() => Task.FromResult(true));

workshopServiceCombinerMock.Setup(x => x.GetById(application.WorkshopId)).Returns(Task.FromResult(new WorkshopDto()));

var applications = new List<Application>
{
new Application(),
new Application(),
new Application(),
};

applicationRepositoryMock.Setup(x => x.GetByFilter(It.IsAny<Expression<Func<Application, bool>>>(), It.IsAny<string>())).ReturnsAsync(applications.AsEnumerable());

// Act
var result = await service.Create(application);

// Assert
Assert.That(result.Model is null);
Assert.That(result.Description != string.Empty);
}

[Test]
Expand Down Expand Up @@ -519,14 +536,12 @@ public async Task GetAllByChild_WhenIdIsNotValid_ShouldReturnEmptyCollection()
Assert.That(result, Is.Null);
}


[Test]
public async Task UpdateApplication_WhenIdIsValid_ShouldReturnApplication()
{
// Arrange
var id = new Guid("1745d16a-6181-43d7-97d0-a1d6cc34a8bd");
var changedEntity = WithApplication(id);
var userId = Guid.NewGuid().ToString();

var applicationsMock = WithApplicationsList().AsQueryable().BuildMock();

Expand Down Expand Up @@ -587,7 +602,6 @@ public async Task UpdateApplication_WhenIdIsValidAndNeedUpdateWorkshopStatus_Sho
var id = new Guid("1745d16a-6181-43d7-97d0-a1d6cc34a8bd");
var entity = WithApplication(id);
var changedEntity = WithApplication(id, ApplicationStatus.Approved);
var userId = Guid.NewGuid().ToString();
var workshop = WithWorkshop(new Guid("0083633f-4e5b-4c09-a89d-52d8a9b89cdb"));

applicationRepositoryMock.Setup(a => a.Update(It.IsAny<Application>(), It.IsAny<Action<Application>>()))
Expand Down Expand Up @@ -627,7 +641,7 @@ public async Task UpdateApplication_WhenIdIsValidAndNeedUpdateWorkshopStatus_Sho
workshopRepositoryMock.Setup(w => w.GetAvailableSeats(It.IsAny<Guid>())).ReturnsAsync(uint.MaxValue);

currentUserServiceMock.Setup(c => c.UserRole).Returns("provider");
currentUserServiceMock.Setup(c => c.UserSubRole).Returns("");
currentUserServiceMock.Setup(c => c.UserSubRole).Returns(string.Empty);

// Act
var result = await service.Update(update, Guid.NewGuid()).ConfigureAwait(false);
Expand All @@ -640,7 +654,6 @@ public async Task UpdateApplication_WhenIdIsValidAndNeedUpdateWorkshopStatus_Sho
public async Task UpdateApplication_WhenThereIsNoApplicationWithId_ShouldReturnNotSucceeded()
{
// Arrange
var userId = Guid.NewGuid().ToString();
var application = new ApplicationUpdate()
{
Id = new Guid("1745d16a-6181-43d7-97d0-a1d6cc34a8bd"),
Expand All @@ -659,7 +672,6 @@ public async Task UpdateApplication_WhenThereIsAlreadyApprovedWorkshop_ShouldRet
var id = new Guid("08da8609-a211-4d74-82c0-dc89ea1fb2a7");
var entity = WithApplication(id);
var changedEntity = WithApplication(id, ApplicationStatus.Approved);
var userId = Guid.NewGuid().ToString();
var workshop = WithWorkshop(new Guid("08da85ea-5b3c-4991-8416-2673d9421ca9"));

applicationRepositoryMock.Setup(a => a.Update(It.IsAny<Application>(), It.IsAny<Action<Application>>()))
Expand All @@ -674,7 +686,6 @@ public async Task UpdateApplication_WhenThereIsAlreadyApprovedWorkshop_ShouldRet
mapper.Setup(m => m.Map<ApplicationDto>(It.IsAny<Application>())).Returns(new ApplicationDto()
{Id = id, Status = ApplicationStatus.Approved});

var expected = new ApplicationDto() {Id = id, Status = ApplicationStatus.Approved};
var update = new ApplicationUpdate
{
Id = id,
Expand Down Expand Up @@ -704,7 +715,7 @@ public async Task UpdateApplication_WhenThereIsAlreadyApprovedWorkshop_ShouldRet
workshopRepositoryMock.Setup(w => w.GetAvailableSeats(It.IsAny<Guid>())).ReturnsAsync(uint.MaxValue);

currentUserServiceMock.Setup(c => c.UserRole).Returns("provider");
currentUserServiceMock.Setup(c => c.UserSubRole).Returns("");
currentUserServiceMock.Setup(c => c.UserSubRole).Returns(string.Empty);

applicationRepositoryMock.Setup(a => a.Count(It.IsAny<Expression<Func<Application, bool>>>())).ReturnsAsync(int.MaxValue);

Expand All @@ -719,7 +730,6 @@ public async Task UpdateApplication_WhenThereIsNoAlreadyApprovedWorkshop_Succeed
var id = new Guid("08da8609-a211-4d74-82c0-dc89ea1fb2a7");
var entity = WithApplication(id);
var changedEntity = WithApplication(id, ApplicationStatus.Approved);
var userId = Guid.NewGuid().ToString();
var workshop = WithWorkshop(new Guid("08da85ea-5b3c-4991-8416-2673d9421ca9"));

applicationRepositoryMock.Setup(a => a.Update(It.IsAny<Application>(), It.IsAny<Action<Application>>()))
Expand All @@ -734,7 +744,6 @@ public async Task UpdateApplication_WhenThereIsNoAlreadyApprovedWorkshop_Succeed
mapper.Setup(m => m.Map<ApplicationDto>(It.IsAny<Application>())).Returns(new ApplicationDto()
{Id = id, Status = ApplicationStatus.Approved});

var expected = new ApplicationDto() {Id = id, Status = ApplicationStatus.Approved};
var update = new ApplicationUpdate
{
Id = id,
Expand Down Expand Up @@ -764,7 +773,7 @@ public async Task UpdateApplication_WhenThereIsNoAlreadyApprovedWorkshop_Succeed
workshopRepositoryMock.Setup(w => w.GetAvailableSeats(It.IsAny<Guid>())).ReturnsAsync(uint.MaxValue);

currentUserServiceMock.Setup(c => c.UserRole).Returns("provider");
currentUserServiceMock.Setup(c => c.UserSubRole).Returns("");
currentUserServiceMock.Setup(c => c.UserSubRole).Returns(string.Empty);

applicationRepositoryMock.Setup(a => a.Count(It.IsAny<Expression<Func<Application, bool>>>())).ReturnsAsync(int.MinValue);

Expand All @@ -776,7 +785,6 @@ public async Task UpdateApplication_WhenThereIsNoAlreadyApprovedWorkshop_Succeed
public void UpdateApplication_WhenModelIsNull_ShouldThrowArgumentException()
{
// Act and Assert
var userId = Guid.NewGuid().ToString();
service.Invoking(s => s.Update(null, Guid.NewGuid())).Should().ThrowAsync<ArgumentException>();
}

Expand Down Expand Up @@ -814,7 +822,7 @@ private void SetupCreate(Application application)
mapper.Setup(m => m.Map<Application>(It.IsAny<ApplicationCreate>()))
.Returns(application);
mapper.Setup(m => m.Map<ApplicationDto>(It.IsAny<Application>()))
.Returns(new ApplicationDto() {Id = new Guid("1745d16a-6181-43d7-97d0-a1d6cc34a8bd")});
.Returns(new ApplicationDto() {Id = new Guid("1745d16a-6181-43d7-97d0-a1d6cc34a8bd") });
}

private void SetupGetAll(List<Application> apps)
Expand All @@ -824,8 +832,8 @@ private void SetupGetAll(List<Application> apps)
It.IsAny<int>(),
It.IsAny<int>(),
It.IsAny<string>(),
It.IsAny<Expression<Func<Application,bool>>>(),
It.IsAny<Dictionary<Expression<Func<Application,object>>,SortDirection>>(),
It.IsAny<Expression<Func<Application, bool>>>(),
It.IsAny<Dictionary<Expression<Func<Application, object>>, SortDirection>>(),
It.IsAny<bool>()))
.Returns(new List<Application> { apps.First() }.AsTestAsyncEnumerableQuery());
mapper.Setup(m => m.Map<List<ApplicationDto>>(It.IsAny<List<Application>>())).Returns(mappedDtos);
Expand Down Expand Up @@ -861,7 +869,7 @@ private void SetupGetAllBy(IEnumerable<Application> apps)
applicationRepositoryMock.Setup(a => a.GetByFilter(
It.IsAny<Expression<Func<Application, bool>>>(),
It.IsAny<string>()))
.Returns(Task.FromResult<IEnumerable<Application>>(new List<Application> {apps.First()}));
.Returns(Task.FromResult<IEnumerable<Application>>(new List<Application> {apps.First() }));
mapper.Setup(m => m.Map<List<ApplicationDto>>(It.IsAny<List<Application>>())).Returns(mappedDtos);
}

Expand All @@ -871,7 +879,7 @@ private void SetupGetAllByWorkshop(List<Application> apps)
var mappedDtos = apps.Select(a => new ApplicationDto() {Id = a.Id}).ToList();

currentUserServiceMock.Setup(c => c.IsAdmin()).Returns(false);
currentUserServiceMock.Setup(c => c.UserHasRights(new IUserRights[] {new ProviderRights(apps.First().Workshop.ProviderId)}))
currentUserServiceMock.Setup(c => c.UserHasRights(new IUserRights[] {new ProviderRights(apps.First().Workshop.ProviderId) }))
.Verifiable();

applicationRepositoryMock.Setup(r => r.Get(
Expand Down Expand Up @@ -1074,8 +1082,6 @@ private List<Application> WithApplicationsList()
};
}



private Application WithApplication(Guid id, ApplicationStatus status = ApplicationStatus.Pending)
{
return new Application()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ public async Task Create_WhenMessageIsValid_ShouldSaveMessageInDatabase()

#region GetMessagesForChatRoomAsync
[Test]
[Ignore("Testing of unused method")]
public void GetMessagesForChatRoomAsync_WhenOffsetfilterIsNull_ShouldNotThrowException()
{
// Arrange
Expand All @@ -123,6 +124,7 @@ public void GetMessagesForChatRoomAsync_WhenOffsetfilterIsNull_ShouldNotThrowExc
}

[Test]
[Ignore("Testing of unused method")]
public async Task GetMessagesForChatRoomAsync_WhenCalledWithAllValidParameters_ShouldReturnFoundMessages()
{
// Arrange
Expand All @@ -141,6 +143,7 @@ public async Task GetMessagesForChatRoomAsync_WhenCalledWithAllValidParameters_S
}

[Test]
[Ignore("Testing of unused method")]
public async Task GetMessagesForChatRoomAsync_WhenCalledWithUnexistedRoomId_ShouldReturnEmptyList()
{
// Arrange
Expand Down Expand Up @@ -193,6 +196,19 @@ public async Task GetMessagesForChatRoomAndSetReadDateTimeIfItIsNullAsync_WhenCa
Assert.AreEqual(existingChatRoomId, result.FirstOrDefault()?.ChatRoomId);
});
}

[Test]
public async Task GetMessagesForChatRoomAndSetReadDateTimeIfItIsNullAsync_WhenCalledWithInValidParameters_ShouldReturnEmptyList()
{
// Arrange
var invalidChatRoomId = Guid.NewGuid();

// Act
var result = await messageService.GetMessagesForChatRoomAndSetReadDateTimeIfItIsNullAsync(invalidChatRoomId, new OffsetFilter(), Role.Provider).ConfigureAwait(false);

// Assert
Assert.IsEmpty(result);
}
#endregion

private void SeedDatabase()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,7 @@ public async Task GetByProviderIdAsync_WhenRoomDoesNotExist_ShouldReturnNull()

#region GetByWorkshopIdAsync
[Test]
[Ignore("Testing of unused method")]
public async Task GetByWorkshopIdAsync_WhenRoomExist_ShouldReturnFoundEntity()
{
// Arrange
Expand All @@ -298,6 +299,7 @@ public async Task GetByWorkshopIdAsync_WhenRoomExist_ShouldReturnFoundEntity()
}

[Test]
[Ignore("Testing of unused method")]
public async Task GetByWorkshopIdAsync_WhenRoomDoesNotExist_ShouldReturnNull()
{
// Arrange
Expand Down Expand Up @@ -380,6 +382,38 @@ public async Task GetChatRoomIdsByProviderIdAsync_WhenRoomDoesNotExist_ShouldRet
}
#endregion

#region GetChatRoomIdsByWorkshopIdsAsync
[Test]
public async Task GetChatRoomIdsByWorkshopIdsAsync_WhenRoomExist_ShouldReturnFoundEntity()
{
// Arrange
var existingworkshopIds = workshops.Select(x => x.Id);

// Act
var result = await roomService.GetChatRoomIdsByWorkshopIdsAsync(existingworkshopIds).ConfigureAwait(false);

// Assert
Assert.IsInstanceOf<IEnumerable<Guid>>(result);
Assert.IsNotNull(result);
Assert.IsTrue(result.Any());
}

[Test]
public async Task GetChatRoomIdsByWorkshopIdsAsync_WhenRoomDoesNotExist_ShouldReturnNull()
{
// Arrange
var notExistingWorkshopIds = new Guid[] { Guid.NewGuid(), Guid.NewGuid() };

// Act
var result = await roomService.GetChatRoomIdsByWorkshopIdsAsync(notExistingWorkshopIds).ConfigureAwait(false);

// Assert
Assert.IsInstanceOf<IEnumerable<Guid>>(result);
Assert.IsNotNull(result);
Assert.IsFalse(result.Any());
}
#endregion

#region GetUniqueChatRoomAsync
[Test]
public async Task GetUniqueChatRoom_WhenRoomExists_ShouldReturnFoundEntity()
Expand Down
Loading
Loading