Example #1
0
        public async Task performs_multiple_transactions_transactional()
        {
            (IBank <TestUser> bank, IMongoCollection <TestUser> usersCollection) = CreateDbObjects(new MockClock());
            TestUser knownUser = new TestUser {
                Money = 10
            };
            TestUser unknownUser = new TestUser {
                Money = 20
            };
            await usersCollection.InsertOneAsync(knownUser);

            UserNotFoundException <TestUser> userNotFound = Assert.ThrowsAsync <UserNotFoundException <TestUser> >(() =>
                                                                                                                   bank.PerformTransactions(new[]
            {
                new Transaction <TestUser>(knownUser, 3, "test"),
                new Transaction <TestUser>(unknownUser, -3, "test")
            })
                                                                                                                   );

            Assert.AreEqual(unknownUser, userNotFound.User);
            // ensure neither user's balance was modified
            Assert.AreEqual(10, knownUser.Money);
            Assert.AreEqual(20, unknownUser.Money);
            TestUser knownUserAfterwards = await usersCollection.Find(u => u.Id == knownUser.Id).FirstAsync();

            Assert.AreEqual(10, knownUserAfterwards.Money);
        }
Example #2
0
        public async Task resetpassword_endpoint_should_return_error_when_user_does_not_exist()
        {
            var id            = new AggregateId();
            var email         = "*****@*****.**";
            var fullname      = "fullname";
            var password      = "******";
            var newPassword   = "******";
            var pic           = "test.nl/image";
            var role          = Role.User;
            var securityStamp = new Guid().ToString();


            // generate reset token
            var token = await _dataProtectorTokenProvider.GenerateAsync(Purpose, id, securityStamp);

            var command = new ResetPassword(id, newPassword, token);


            var response = await Act(command);

            response.Should().NotBeNull();
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);

            var content = await response.Content.ReadAsStringAsync();

            var exception = new UserNotFoundException(id);

            content.Should().Contain(exception.Code);
        }
        public void CreateCommentByNoExistingUser()
        {
            //Arrange.
            ControllerContext fakeContext = GetFakeControllerContext();

            controller.ControllerContext = fakeContext;
            CommentModelIn input = new CommentModelIn()
            {
                Text = "this is a comment"
            };
            Exception internalEx = new UserNotFoundException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.ENTITY_NOT_FOUND);

            matchService.Setup(ms => ms.CommentOnEncounter(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>())).Throws(toThrow);

            //Act.
            IActionResult        result     = controller.CommentOnMatch(3, input);
            NotFoundObjectResult badRequest = result as NotFoundObjectResult;
            ErrorModelOut        error      = badRequest.Value as ErrorModelOut;

            //Assert.
            matchService.Verify(ms => ms.CommentOnEncounter(3, "username", input.Text), Times.Once);
            Assert.IsNotNull(result);
            Assert.IsNotNull(badRequest);
            Assert.AreEqual(404, badRequest.StatusCode);
            Assert.IsNotNull(error);
            Assert.AreEqual(error.ErrorMessage, toThrow.Message);
        }
Example #4
0
        public void Delete(User user)
        {
            if (ReferenceEquals(user, null))
            {
                var ex = new ArgumentNullException($"{nameof(user)} is null");
                this.logger?.Error(ex, ex.Message);
                throw ex;
            }

            if (!this.storage.Contains(user))
            {
                var ex = new UserNotFoundException($"{nameof(user)} not found");
                this.logger?.Error(ex, ex.Message);
                throw ex;
            }

            rwLockSlim.EnterWriteLock();
            try
            {
                this.logger?.Info($"Deleted {nameof(user)} with fields:\n ID:{user.Identifier}\n FirstName:{user.FirstName}\n LastName:{user.LastName}\n Age:{user.Age}");

                this.storage.Remove(user);
            }
            finally
            {
                rwLockSlim.ExitWriteLock();
            }

            Notify(new Message {
                Action = Action.Delete, User = user.Clone()
            });
        }
Example #5
0
        public async Task Should_Throw_UserNotFoundException_For_Invalid_User_Id()
        {
            UserNotFoundException exception = await Assert.ThrowsAsync <UserNotFoundException>(
                async() => await BotClient.PromoteChatMemberAsync(Fixture.SupergroupChat.Id, 123456)
                );

            Assert.Equal(400, exception.ErrorCode);
            Assert.Contains("user not found", exception.Message);
        }
Example #6
0
        public async Task Should_Throw_UserNotFoundException()
        {
            UserNotFoundException exception = await Assert.ThrowsAsync <UserNotFoundException>(
                async() => await BotClient.GetChatMemberAsync("@testchannel111112", 100120232)
                );

            Assert.Equal(400, exception.ErrorCode);
            Assert.Contains("user not found", exception.Message);
        }
Example #7
0
        public void fails_check_money_for_unknown_user()
        {
            (IBank <TestUser> bank, IMongoCollection <TestUser> _) = CreateDbObjects(new MockClock());
            TestUser unknownUser = new TestUser {
                Money = 0
            };                                                 // not persisted
            UserNotFoundException <TestUser> userNotFound = Assert.ThrowsAsync <UserNotFoundException <TestUser> >(
                () => bank.GetAvailableMoney(unknownUser));

            Assert.AreEqual(unknownUser, userNotFound.User);
        }
        public void Login_WithNonExistingUsername_TrowsInvalidPasswordExceptionForUsername()
        {
            string exceptedUsername = "******";
            string password         = "******";

            _mockPasswordHasher.Setup(s => s.VerifyHashedPassword(It.IsAny <string>(), password)).Returns(PasswordVerificationResult.Failed);

            UserNotFoundException exeption = Assert.ThrowsAsync <UserNotFoundException>(() => _autenticationService.Login(exceptedUsername, password));

            string actualUsername = exeption.Username;

            Assert.AreEqual(exceptedUsername, actualUsername);
        }
Example #9
0
        public void fails_transaction_if_user_not_found()
        {
            (IBank <TestUser> bank, IMongoCollection <TestUser> _) = CreateDbObjects(new MockClock());
            var user = new TestUser {
                Money = 10
            };                                      // user not persisted

            var transaction = new Transaction <TestUser>(user, 1, "test");
            UserNotFoundException <TestUser> userNotFound = Assert.ThrowsAsync <UserNotFoundException <TestUser> >(
                () => bank.PerformTransaction(transaction));

            Assert.AreEqual(user, userNotFound.User);
        }
        public void Login_WithNonExistingUsername_ThrowsUserNotFoundException()
        {
            string expectedUsername = "******";
            string password         = "******";

            _mockUnitOfWork.Setup(s => s.UserRepository.GetByUsername(expectedUsername)).ReturnsAsync((User)null);
            _mockPasswordHasher.Setup(s => s.VerifyHashedPassword(It.IsAny <string>(), password)).Returns(PasswordVerificationResult.Failed);

            UserNotFoundException exception = Assert.ThrowsAsync <UserNotFoundException>(() => _authenticationService.Login(expectedUsername, password));

            string actualUsername = exception.Username;

            Assert.AreEqual(expectedUsername, actualUsername);
        }
 private Exception CatchException(Exception ex)
 {
     throw ex switch
           {
               UsernameExistsException _ => new BusinessException(ErrorCode.UsernameAlreadyExists, ex),
               NotAuthorizedException _ => new BusinessException(ErrorCode.NotAuthorized, ex),
               TooManyRequestsException _ => new BusinessException(ErrorCode.TooManyRequests, ex),
               PasswordResetRequiredException _ => new BusinessException(ErrorCode.PasswordResetRequired, ex),
               UserNotFoundException _ => new BusinessException(ErrorCode.UserNotFound, ex),
               UserNotConfirmedException _ => new BusinessException(ErrorCode.UserNotConfirmed, ex),
               InvalidPasswordException _ => new BusinessException(ErrorCode.InvalidPassword, ex),
               CodeMismatchException _ => new BusinessException(ErrorCode.CodeMismatch, ex),
               ExpiredCodeException _ => new BusinessException(ErrorCode.ExpiredCode, ex),
               LimitExceededException _ => new BusinessException(ErrorCode.LimitExceeded, ex),
               BusinessException _ => ex,
               _ => new CriticalException(ErrorCode.InternalServerError, ex),
           };
 }
Example #12
0
        public async Task Login_WithNonExistingUsername_ThrowsNotFoundExceptionForUsername()
        {
            // Arrange
            string expectedUsername = "******";
            string password         = "******";
            User   user             = new User()
            {
                Username = expectedUsername
            };

            _mockPwdHash.Setup(s => s.VerifyHashedPassword(user, It.IsAny <string>(), password)).Returns(PasswordVerificationResult.Failed);

            // Act
            UserNotFoundException exception = await Assert.ThrowsAsync <UserNotFoundException>(() => _authenticationSvc.Login(expectedUsername, password));

            // Assert
            string actualUsername = exception.Username;

            Assert.Equal(expectedUsername, actualUsername);
        }
Example #13
0
        public void DeleteNotExistentTest()
        {
            //Arrange.
            Exception internalEx = new UserNotFoundException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.ENTITY_NOT_FOUND);

            service.Setup(ms => ms.DeleteUser("notExistent")).Throws(toThrow);

            //Act.
            IActionResult        result   = controller.Delete("notExistent");
            NotFoundObjectResult notFound = result as NotFoundObjectResult;
            ErrorModelOut        error    = notFound.Value as ErrorModelOut;

            //Assert.
            Assert.IsNotNull(result);
            Assert.IsNotNull(notFound);
            Assert.AreEqual(404, notFound.StatusCode);
            Assert.IsNotNull(error);
            Assert.AreEqual(error.ErrorMessage, toThrow.Message);
        }
Example #14
0
        public void GetNotExistentTest()
        {
            //Arrange.
            Exception internalEx = new UserNotFoundException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.ENTITY_NOT_FOUND);

            service.Setup(us => us.GetUser(It.IsAny <string>())).Throws(toThrow);

            //Act.
            IActionResult        result   = controller.Get("username");
            NotFoundObjectResult notFound = result as NotFoundObjectResult;
            ErrorModelOut        error    = notFound.Value as ErrorModelOut;

            //Assert.
            service.Verify(us => us.GetUser("username"), Times.Once);
            Assert.IsNotNull(result);
            Assert.IsNotNull(notFound);
            Assert.AreEqual(404, notFound.StatusCode);
            Assert.IsNotNull(error);
            Assert.AreEqual(error.ErrorMessage, toThrow.Message);
        }
Example #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="predicate"></param>
        /// <returns></returns>
        public IEnumerable <User> Search(Predicate <User> predicate)
        {
            if (ReferenceEquals(predicate, null))
            {
                var ex = new ArgumentNullException($"{nameof(predicate)} is null");
                this.logger?.Error(ex, ex.Message);
                throw ex;
            }

            var result = this.storage.Where(user => predicate(user));

            if (result.Count() < 0)
            {
                var ex = new UserNotFoundException("User(s) not found");
                this.logger?.Error(ex, ex.Message);
                throw ex;
            }

            this.logger?.Info($"Requested {result.Count()} users: Id's {string.Concat(" ",result.Select(user => user.Identifier))}");

            return(result.ToList());
        }
Example #16
0
        public void LoginNotFoundTest()
        {
            //Arrange.
            Exception internalEx = new UserNotFoundException();
            Exception toThrow    = new ServiceException(internalEx.Message, ErrorType.ENTITY_NOT_FOUND);

            loginService.Setup(l => l.Login("otherUsername", "aPassword")).Throws(toThrow);

            //Act.
            LoginModelIn credentials = new LoginModelIn()
            {
                Username = "******", Password = "******"
            };
            IActionResult          result           = controllerToTest.Authenticate(credentials);
            BadRequestObjectResult badRequestResult = result as BadRequestObjectResult;
            ErrorModelOut          error            = badRequestResult.Value as ErrorModelOut;

            //Assert.
            loginService.VerifyAll();
            Assert.IsNotNull(badRequestResult);
            Assert.IsNotNull(error);
            Assert.AreEqual(toThrow.Message, error.ErrorMessage);
        }
Example #17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            /*
             * if (env.IsDevelopment())
             * {
             *  app.UseDeveloperExceptionPage();
             * }
             * else
             * {
             *  // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
             *  app.UseHsts();
             * }
             */
            app.UseExceptionHandler(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    var exceptionHandlerPathFeature =
                        context.Features.Get <IExceptionHandlerPathFeature>();

                    string text = exceptionHandlerPathFeature?.Error switch
                    {
                        UserNotFoundException e => "User not found",
                        UserNotHaveEnoughRightsException e => "User not have enough rights",
                        UserAlreadyInChatException e => "User already in chat",
                        ChatNotFoundException e => "Chat not found",
                        UsernameAlreadyExistsException e => "Username already exists",
                        _ => "Unknown error"
                    };
                    context.Response.ContentType = MediaTypeNames.Application.Json;
                    context.Response.StatusCode  = 400;
                    await context.Response.WriteAsync(JsonConvert.SerializeObject(new ApiError {
                        Error = text
                    }));
                });
            });

            app.UseOpenApi(settings =>
            {
                settings.Path         = $"{ApiConstant.Prefix}openapi/swagger.json";
                settings.DocumentName = "openapi";
            });

            app.UseSwaggerUi3(options =>
            {
                options.Path         = $"{ApiConstant.Prefix}openapi";
                options.DocumentPath = $"{ApiConstant.Prefix}openapi/swagger.json";
            });

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
Example #18
0
        public void UserNotFound_Instantiate()
        {
            UserNotFoundException ex = new UserNotFoundException();

            Assert.NotNull(ex);
        }