From 7bd33f55cd044fd232f4b574d54ddeacfd6b5003 Mon Sep 17 00:00:00 2001 From: Danail Dimitrov Date: Tue, 26 Jan 2021 18:48:49 +0200 Subject: adding comment repository tests --- .../DevHive.Data.Tests/CommentRepository.Tests.cs | 98 ++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs (limited to 'src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs') diff --git a/src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs b/src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs new file mode 100644 index 0000000..2a8bb1f --- /dev/null +++ b/src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs @@ -0,0 +1,98 @@ +using System; +using System.Threading.Tasks; +using DevHive.Data.Models; +using DevHive.Data.Repositories; +using Microsoft.EntityFrameworkCore; +using NUnit.Framework; + +namespace DevHive.Data.Tests +{ + [TestFixture] + public class CommentRepositoryTests + { + private const string COMMENT_MESSAGE = "Comment message"; + + protected DevHiveContext Context { get; set; } + + protected CommentRepository CommentRepository { get; set; } + + #region Setups + [SetUp] + public void Setup() + { + var optionsBuilder = new DbContextOptionsBuilder() + .UseInMemoryDatabase(databaseName: "DevHive_Test_Database"); + + this.Context = new DevHiveContext(optionsBuilder.Options); + + CommentRepository = new CommentRepository(Context); + } + + [TearDown] + public void TearDown() + { + this.Context.Database.EnsureDeleted(); + } + #endregion + + #region GetCommentByIssuerAndTimeCreatedAsync + [Test] + public async Task GetCommentByCreatorAndTimeCreatedAsync_ReturnsTheCorrectComment_IfItExists() + { + Comment comment = await this.AddEntity(); + + Comment resultComment = await this.CommentRepository.GetCommentByIssuerAndTimeCreatedAsync(comment.CreatorId, comment.TimeCreated); + + Assert.AreEqual(comment.Id, resultComment.Id, "GetCommentByIssuerAndTimeCreatedAsync does not return the corect comment when it exists"); + } + + [Test] + public async Task GetPostByCreatorAndTimeCreatedAsync_ReturnsNull_IfThePostDoesNotExist() + { + Comment comment = await this.AddEntity(); + + Comment resultComment = await this.CommentRepository.GetCommentByIssuerAndTimeCreatedAsync(Guid.Empty, DateTime.Now); + + Assert.IsNull(resultComment, "GetCommentByIssuerAndTimeCreatedAsync does not return null when the comment does not exist"); + } + #endregion + + #region DoesCommentExist + [Test] + public async Task DoesCommentExist_ReturnsTrue_WhenTheCommentExists() + { + Comment comment = await this.AddEntity(); + + bool result = await this.CommentRepository.DoesCommentExist(comment.Id); + + Assert.IsTrue(result, "DoesCommentExist does not return true whenm the Comment exists"); + } + + [Test] + public async Task DoesCommentExist_ReturnsFalse_WhenTheCommentDoesNotExist() + { + bool result = await this.CommentRepository.DoesCommentExist(Guid.Empty); + + Assert.IsFalse(result, "DoesCommentExist does not return false whenm the Comment" + + " does not exist"); + } + #endregion + + #region HelperMethods + private async Task AddEntity(string name = COMMENT_MESSAGE) + { + Comment comment = new Comment + { + Message = COMMENT_MESSAGE, + CreatorId = Guid.NewGuid(), + TimeCreated = DateTime.Now + }; + + this.Context.Comments.Add(comment); + await this.Context.SaveChangesAsync(); + + return comment; + } + #endregion + } +} -- cgit v1.2.3 From 6b11b2001a227a09387548853071c63b6fe5c991 Mon Sep 17 00:00:00 2001 From: Danail Dimitrov Date: Thu, 28 Jan 2021 21:25:56 +0200 Subject: Refactored tests after the boys broke them --- src/DevHive.Services/Services/UserService.cs | 1 - .../DevHive.Data.Tests/CommentRepository.Tests.cs | 5 +- .../DevHive.Data.Tests/FeedRepository.Tests.cs | 9 +- .../DevHive.Data.Tests/PostRepository.Tests.cs | 5 +- .../DevHive.Data.Tests/UserRepositoryTests.cs | 22 ++- .../DevHive.Services.Tests/PostService.Tests.cs | 18 ++- .../DevHive.Services.Tests/UserService.Tests.cs | 173 +++++++++++++++++++++ 7 files changed, 216 insertions(+), 17 deletions(-) create mode 100644 src/DevHive.Tests/DevHive.Services.Tests/UserService.Tests.cs (limited to 'src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs') diff --git a/src/DevHive.Services/Services/UserService.cs b/src/DevHive.Services/Services/UserService.cs index dabad50..3f3d86e 100644 --- a/src/DevHive.Services/Services/UserService.cs +++ b/src/DevHive.Services/Services/UserService.cs @@ -42,7 +42,6 @@ namespace DevHive.Services.Services } #region Authentication - public async Task LoginUser(LoginServiceModel loginModel) { if (!await this._userRepository.DoesUsernameExistAsync(loginModel.UserName)) diff --git a/src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs b/src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs index 2a8bb1f..9cbb43b 100644 --- a/src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs +++ b/src/DevHive.Tests/DevHive.Data.Tests/CommentRepository.Tests.cs @@ -41,7 +41,7 @@ namespace DevHive.Data.Tests { Comment comment = await this.AddEntity(); - Comment resultComment = await this.CommentRepository.GetCommentByIssuerAndTimeCreatedAsync(comment.CreatorId, comment.TimeCreated); + Comment resultComment = await this.CommentRepository.GetCommentByIssuerAndTimeCreatedAsync(comment.Creator.Id, comment.TimeCreated); Assert.AreEqual(comment.Id, resultComment.Id, "GetCommentByIssuerAndTimeCreatedAsync does not return the corect comment when it exists"); } @@ -81,10 +81,11 @@ namespace DevHive.Data.Tests #region HelperMethods private async Task AddEntity(string name = COMMENT_MESSAGE) { + User creator = new User { Id = Guid.NewGuid() }; Comment comment = new Comment { Message = COMMENT_MESSAGE, - CreatorId = Guid.NewGuid(), + Creator = creator, TimeCreated = DateTime.Now }; diff --git a/src/DevHive.Tests/DevHive.Data.Tests/FeedRepository.Tests.cs b/src/DevHive.Tests/DevHive.Data.Tests/FeedRepository.Tests.cs index e38b31c..62d6455 100644 --- a/src/DevHive.Tests/DevHive.Data.Tests/FeedRepository.Tests.cs +++ b/src/DevHive.Tests/DevHive.Data.Tests/FeedRepository.Tests.cs @@ -44,8 +44,8 @@ namespace DevHive.Data.Tests DateTime dateTime = new DateTime(3000, 05, 09, 9, 15, 0); - Post dummyPost = this.CreateDummyPost(dummyUser.Id); - Post anotherDummnyPost = this.CreateDummyPost(dummyUser.Id); + Post dummyPost = this.CreateDummyPost(dummyUser); + Post anotherDummnyPost = this.CreateDummyPost(dummyUser); const int PAGE_NUMBER = 1; const int PAGE_SIZE = 10; @@ -96,16 +96,15 @@ namespace DevHive.Data.Tests }; } - private Post CreateDummyPost(Guid posterId) + private Post CreateDummyPost(User poster) { const string POST_MESSAGE = "random message"; Guid id = Guid.NewGuid(); - Post post = new Post { Id = id, Message = POST_MESSAGE, - CreatorId = posterId + Creator = poster }; this.Context.Posts.Add(post); diff --git a/src/DevHive.Tests/DevHive.Data.Tests/PostRepository.Tests.cs b/src/DevHive.Tests/DevHive.Data.Tests/PostRepository.Tests.cs index 27b7c32..113780b 100644 --- a/src/DevHive.Tests/DevHive.Data.Tests/PostRepository.Tests.cs +++ b/src/DevHive.Tests/DevHive.Data.Tests/PostRepository.Tests.cs @@ -62,7 +62,7 @@ namespace DevHive.Data.Tests { Post post = await this.AddEntity(); - Post resultPost = await this.PostRepository.GetPostByCreatorAndTimeCreatedAsync(post.CreatorId, post.TimeCreated); + Post resultPost = await this.PostRepository.GetPostByCreatorAndTimeCreatedAsync(post.Creator.Id, post.TimeCreated); Assert.AreEqual(post.Id, resultPost.Id, "GetPostByCreatorAndTimeCreatedAsync does not return the corect post when it exists"); } @@ -101,11 +101,12 @@ namespace DevHive.Data.Tests #region HelperMethods private async Task AddEntity(string name = POST_MESSAGE) { + User creator = new User { Id = Guid.NewGuid() }; Post post = new Post { Message = POST_MESSAGE, Id = Guid.NewGuid(), - CreatorId = Guid.NewGuid(), + Creator = creator, TimeCreated = DateTime.Now }; diff --git a/src/DevHive.Tests/DevHive.Data.Tests/UserRepositoryTests.cs b/src/DevHive.Tests/DevHive.Data.Tests/UserRepositoryTests.cs index 6cc7b87..0d262f5 100644 --- a/src/DevHive.Tests/DevHive.Data.Tests/UserRepositoryTests.cs +++ b/src/DevHive.Tests/DevHive.Data.Tests/UserRepositoryTests.cs @@ -60,6 +60,22 @@ namespace DevHive.Data.Tests } #endregion + #region EditAsync + [Test] + public async Task EditAsync_ReturnsTrue_WhenUserIsUpdatedSuccessfully() + { + User oldUser = this.CreateDummyUser(); + this._context.Users.Add(oldUser); + await this._context.SaveChangesAsync(); + + oldUser.UserName = "SuperSecretUserName"; + bool result = await this._userRepository.EditAsync(oldUser.Id, oldUser); + + Assert.IsTrue(result, "EditAsync does not return true when User is updated successfully"); + Assert.Fail("Docurshi drugite"); + } + #endregion + #region GetByIdAsync [Test] public async Task GetByIdAsync_ReturnsTheUse_WhenItExists() @@ -188,8 +204,10 @@ namespace DevHive.Data.Tests { User dummyUser = this.CreateDummyUser(); User anotherDummyUser = this.CreateAnotherDummyUser(); - HashSet friends = new HashSet(); - friends.Add(anotherDummyUser); + HashSet friends = new HashSet + { + anotherDummyUser + }; dummyUser.Friends = friends; this._context.Users.Add(dummyUser); diff --git a/src/DevHive.Tests/DevHive.Services.Tests/PostService.Tests.cs b/src/DevHive.Tests/DevHive.Services.Tests/PostService.Tests.cs index 2f59376..b47c8bc 100644 --- a/src/DevHive.Tests/DevHive.Services.Tests/PostService.Tests.cs +++ b/src/DevHive.Tests/DevHive.Services.Tests/PostService.Tests.cs @@ -39,6 +39,7 @@ namespace DevHive.Services.Tests public async Task AddComment_ReturnsNonEmptyGuid_WhenEntityIsAddedSuccessfully() { Guid id = Guid.NewGuid(); + User creator = new User { Id = Guid.NewGuid() }; CreateCommentServiceModel createCommentServiceModel = new CreateCommentServiceModel { Message = MESSAGE @@ -46,12 +47,13 @@ namespace DevHive.Services.Tests Comment comment = new Comment { Message = MESSAGE, - Id = id + Id = id, }; this.CommentRepositoryMock.Setup(p => p.AddAsync(It.IsAny())).Returns(Task.FromResult(true)); this.CommentRepositoryMock.Setup(p => p.GetCommentByIssuerAndTimeCreatedAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(comment)); this.PostRepositoryMock.Setup(p => p.DoesPostExist(It.IsAny())).Returns(Task.FromResult(true)); + this.UserRepositoryMock.Setup(p => p.GetByIdAsync(It.IsAny())).Returns(Task.FromResult(creator)); this.MapperMock.Setup(p => p.Map(It.IsAny())).Returns(comment); Guid result = await this.PostService.AddComment(createCommentServiceModel); @@ -101,10 +103,11 @@ namespace DevHive.Services.Tests public async Task GetCommentById_ReturnsTheComment_WhenItExists() { Guid creatorId = new Guid(); + User creator = new User { Id = creatorId }; Comment comment = new Comment { Message = MESSAGE, - CreatorId = creatorId + Creator = creator }; ReadCommentServiceModel commentServiceModel = new ReadCommentServiceModel { @@ -129,10 +132,11 @@ namespace DevHive.Services.Tests { const string EXCEPTION_MESSAGE = "The user does not exist"; Guid creatorId = new Guid(); + User creator = new User { Id = creatorId }; Comment comment = new Comment { Message = MESSAGE, - CreatorId = creatorId + Creator = creator }; this.CommentRepositoryMock.Setup(p => p.GetByIdAsync(It.IsAny())).Returns(Task.FromResult(comment)); @@ -268,6 +272,7 @@ namespace DevHive.Services.Tests public async Task CreatePost_ReturnsIdOfThePost_WhenItIsSuccessfullyCreated() { Guid postId = Guid.NewGuid(); + User creator = new User { Id = Guid.NewGuid() }; CreatePostServiceModel createPostServiceModel = new CreatePostServiceModel { }; @@ -280,6 +285,7 @@ namespace DevHive.Services.Tests this.PostRepositoryMock.Setup(p => p.AddAsync(It.IsAny())).Returns(Task.FromResult(true)); this.PostRepositoryMock.Setup(p => p.GetPostByCreatorAndTimeCreatedAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(post)); this.UserRepositoryMock.Setup(p => p.DoesUserExistAsync(It.IsAny())).Returns(Task.FromResult(true)); + this.UserRepositoryMock.Setup(p => p.GetByIdAsync(It.IsAny())).Returns(Task.FromResult(creator)); this.MapperMock.Setup(p => p.Map(It.IsAny())).Returns(post); Guid result = await this.PostService.CreatePost(createPostServiceModel); @@ -330,10 +336,11 @@ namespace DevHive.Services.Tests public async Task GetPostById_ReturnsThePost_WhenItExists() { Guid creatorId = new Guid(); + User creator = new User { Id = creatorId }; Post post = new Post { Message = MESSAGE, - CreatorId = creatorId + Creator = creator }; ReadPostServiceModel readPostServiceModel = new ReadPostServiceModel { @@ -358,10 +365,11 @@ namespace DevHive.Services.Tests { const string EXCEPTION_MESSAGE = "The user does not exist!"; Guid creatorId = new Guid(); + User creator = new User { Id = creatorId }; Post post = new Post { Message = MESSAGE, - CreatorId = creatorId + Creator = creator }; this.PostRepositoryMock.Setup(p => p.GetByIdAsync(It.IsAny())).Returns(Task.FromResult(post)); diff --git a/src/DevHive.Tests/DevHive.Services.Tests/UserService.Tests.cs b/src/DevHive.Tests/DevHive.Services.Tests/UserService.Tests.cs new file mode 100644 index 0000000..f9a0f71 --- /dev/null +++ b/src/DevHive.Tests/DevHive.Services.Tests/UserService.Tests.cs @@ -0,0 +1,173 @@ +using System; +using System.Collections.Generic; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; +using System.Threading.Tasks; +using AutoMapper; +using DevHive.Common.Models.Identity; +using DevHive.Common.Models.Misc; +using DevHive.Data.Interfaces.Repositories; +using DevHive.Data.Models; +using DevHive.Services.Models.Identity.User; +using DevHive.Services.Options; +using DevHive.Services.Services; +using Microsoft.IdentityModel.Tokens; +using Moq; +using NUnit.Framework; + +namespace DevHive.Services.Tests +{ + [TestFixture] + public class UserServiceTests + { + private Mock UserRepositoryMock { get; set; } + private Mock RoleRepositoryMock { get; set; } + private Mock LanguageRepositoryMock { get; set; } + private Mock TechnologyRepositoryMock { get; set; } + private Mock MapperMock { get; set; } + private JWTOptions JWTOptions { get; set; } + private UserService UserService { get; set; } + + #region SetUps + [SetUp] + public void Setup() + { + this.UserRepositoryMock = new Mock(); + this.RoleRepositoryMock = new Mock(); + this.LanguageRepositoryMock = new Mock(); + this.TechnologyRepositoryMock = new Mock(); + this.JWTOptions = new JWTOptions("gXfQlU6qpDleFWyimscjYcT3tgFsQg3yoFjcvSLxG56n1Vu2yptdIUq254wlJWjm"); + this.MapperMock = new Mock(); + this.UserService = new UserService(this.UserRepositoryMock.Object, this.LanguageRepositoryMock.Object, this.RoleRepositoryMock.Object, this.TechnologyRepositoryMock.Object, this.MapperMock.Object, JWTOptions); + } + #endregion + + #region LoginUser + [Test] + public async Task LoginUser_ReturnsTokenModel_WhenLoggingUserIn() + { + string somePassword = "GoshoTrapovImaGolemChep"; + string hashedPassword = PasswordModifications.GeneratePasswordHash(somePassword); + LoginServiceModel loginServiceModel = new LoginServiceModel + { + Password = somePassword + }; + User user = new User + { + Id = Guid.NewGuid(), + PasswordHash = hashedPassword + }; + + this.UserRepositoryMock.Setup(p => p.DoesUsernameExistAsync(It.IsAny())).Returns(Task.FromResult(true)); + this.UserRepositoryMock.Setup(p => p.GetByUsernameAsync(It.IsAny())).Returns(Task.FromResult(user)); + + string JWTSecurityToken = this.WriteJWTSecurityToken(user.Id, user.Roles); + + TokenModel tokenModel = await this.UserService.LoginUser(loginServiceModel); + + Assert.AreEqual(JWTSecurityToken, tokenModel.Token, "LoginUser does not return the correct token"); + } + + [Test] + public void LoginUser_ThrowsException_WhenUserNameDoesNotExist() + { + const string EXCEPTION_MESSAGE = "Invalid username!"; + LoginServiceModel loginServiceModel = new LoginServiceModel + { + }; + + this.UserRepositoryMock.Setup(p => p.DoesUsernameExistAsync(It.IsAny())).Returns(Task.FromResult(false)); + + Exception ex = Assert.ThrowsAsync(() => this.UserService.LoginUser(loginServiceModel)); + + Assert.AreEqual(EXCEPTION_MESSAGE, ex.Message, "Incorect Exception message"); + } + + [Test] + public void LoginUser_ThroiwsException_WhenPasswordIsIncorect() + { + const string EXCEPTION_MESSAGE = "Incorrect password!"; + string somePassword = "GoshoTrapovImaGolemChep"; + LoginServiceModel loginServiceModel = new LoginServiceModel + { + Password = somePassword + }; + User user = new User + { + Id = Guid.NewGuid(), + PasswordHash = "InvalidPasswordHas" + }; + + this.UserRepositoryMock.Setup(p => p.DoesUsernameExistAsync(It.IsAny())).Returns(Task.FromResult(true)); + this.UserRepositoryMock.Setup(p => p.GetByUsernameAsync(It.IsAny())).Returns(Task.FromResult(user)); + + Exception ex = Assert.ThrowsAsync(() => this.UserService.LoginUser(loginServiceModel)); + + Assert.AreEqual(EXCEPTION_MESSAGE, ex.Message, "Incorect Exception message"); + } + #endregion + + #region RegisterUser + [Test] + public async Task RegisterUser_ReturnsTokenModel_WhenUserIsSuccessfull() + { + string somePassword = "GoshoTrapovImaGolemChep"; + RegisterServiceModel registerServiceModel = new RegisterServiceModel + { + Password = somePassword + }; + User user = new User + { + Id = Guid.NewGuid() + }; + Role role = new Role { Name = Role.DefaultRole }; + HashSet roles = new HashSet { role }; + + this.UserRepositoryMock.Setup(p => p.DoesUsernameExistAsync(It.IsAny())).Returns(Task.FromResult(false)); + this.UserRepositoryMock.Setup(p => p.DoesEmailExistAsync(It.IsAny())).Returns(Task.FromResult(false)); + this.RoleRepositoryMock.Setup(p => p.DoesNameExist(It.IsAny())).Returns(Task.FromResult(true)); + this.RoleRepositoryMock.Setup(p => p.GetByNameAsync(It.IsAny())).Returns(Task.FromResult(role)); + this.MapperMock.Setup(p => p.Map(It.IsAny())).Returns(user); + this.UserRepositoryMock.Setup(p => p.AddAsync(It.IsAny())).Verifiable(); + + string JWTSecurityToken = this.WriteJWTSecurityToken(user.Id, roles); + + TokenModel tokenModel = await this.UserService.RegisterUser(registerServiceModel); + + Mock.Verify(); + Assert.AreEqual(JWTSecurityToken, tokenModel.Token, "RegisterUser does not return the correct token"); + } + #endregion + + #region HelperMethods + private string WriteJWTSecurityToken(Guid userId, HashSet roles) + { + byte[] signingKey = Encoding.ASCII.GetBytes(this.JWTOptions.Secret); + + HashSet claims = new() + { + new Claim("ID", $"{userId}"), + }; + + foreach (var role in roles) + { + claims.Add(new Claim(ClaimTypes.Role, role.Name)); + } + + SecurityTokenDescriptor tokenDescriptor = new() + { + Subject = new ClaimsIdentity(claims), + Expires = DateTime.Today.AddDays(7), + SigningCredentials = new SigningCredentials( + new SymmetricSecurityKey(signingKey), + SecurityAlgorithms.HmacSha512Signature) + }; + + JwtSecurityTokenHandler tokenHandler = new(); + SecurityToken token = tokenHandler.CreateToken(tokenDescriptor); + return tokenHandler.WriteToken(token); + } + #endregion + } +} -- cgit v1.2.3