public async Task ResetPassword_GivenUsedPasswordReset_RequestRejected()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            Guid resetToken;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john  = ContextUtilities.CreateJohnDoe();
                var  reset = new PasswordReset {
                    Requested = DateTime.UtcNow, User = john, Used = true
                };
                context.PasswordResets.Add(reset);

                await context.SaveChangesAsync();

                resetToken = reset.Token;
            }

            // Act
            (ResetPasswordController controller, _, _) = CreateController(getContext, null);

            IActionResult response = await controller.ResetPassword(new ResetPasswordDto { NewPassword = "******", PasswordResetToken = resetToken });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var badRequestResponse = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.ResetCodeAlreadyUsedOrExpired, badRequestResponse.Value);
        }
        public async Task GetChatMessage_GivenNotParticipatingUser_ErrorReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event privateEvent = DummyEvent(john.Entity);
                context.Events.Add(privateEvent);

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
                eventId   = privateEvent.Id;
            }

            // Act
            (EventChatController eventChatController, _) = CreateController(getContext, johnDoeId);

            IActionResult response = await eventChatController.GetChatMessages(new GetChatMessagesDto { EventId = eventId });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.UserNotPartOfEvent, objectResult.Value);
        }
Ejemplo n.º 3
0
        public async Task DeleteAccount_GivenUserWithSimpleRelations_UserAndRelationsDeleted()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john = ContextUtilities.CreateJohnDoe();

                context.PasswordResets.Add(new PasswordReset {
                    Requested = DateTime.UtcNow, User = john
                });
                context.Sessions.Add(new Session {
                    Created = DateTime.UtcNow, User = john
                });

                await context.SaveChangesAsync();

                johnDoeId = john.Id;
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, johnDoeId);
            IActionResult response = await controller.DeleteAccount();

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                Assert.Empty(context.Users);
                Assert.Empty(context.Sessions);
                Assert.Empty(context.PasswordResets);
            }
        }
        public async Task Register_GivenExistingEmail_UserNotRegistered()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Arrange
            var data = new RegisterDto {
                Email = "*****@*****.**", FullName = "New User", Password = "******"
            };

            using (IDatabaseContext context = getContext())
            {
                context.Users.Add(new User
                {
                    Email        = data.Email,
                    FullName     = "Some other name",
                    PasswordHash = "Some hashed password"
                });

                await context.SaveChangesAsync();
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, null);
            IActionResult response = await controller.Register(data);

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.EmailAlreadyInUse, objectResult.Value);
        }
Ejemplo n.º 5
0
        public async Task SetNewPassword_GivenCorrectCurrentPassword_ChangesPassword()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            User         john;
            const string CorrectCurrentPassword = "******";
            const string NewPassword            = "******";
            const string NewPasswordHash        = "Néw P@ssw0rd";

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                john = context.Users.Add(ContextUtilities.CreateJohnDoe()).Entity;

                await context.SaveChangesAsync();
            }

            // Act
            (UserController controller, _, Mock <IPasswordService> passwordServiceMock, _) = CreateController(getContext, john.Id);
            passwordServiceMock.Setup(p => p.VerifyPassword(CorrectCurrentPassword, john.PasswordHash)).Returns(true);
            passwordServiceMock.Setup(p => p.HashPassword(NewPassword)).Returns(NewPasswordHash);

            IActionResult response = await controller.SetNewPassword(new SetPasswordDto { CurrentPassword = CorrectCurrentPassword, NewPassword = NewPassword });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                User loadedUser = context.Users.Single();
                Assert.Equal(NewPasswordHash, loadedUser.PasswordHash);
            }
        }
        public async Task ConfigureNotifications_GivenNonexistentEvent_ErrorReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                await context.SaveChangesAsync();

                johnId = john.Entity.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnId);

            IActionResult response = await participateEventController.ConfigureNotifications(new NotificationConfigurationDto { EventId = 42, SendReminderEmail = true, SendSummaryEmail = true, SendLastMinuteChangesEmail = true });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.UserNotPartOfEvent, objectResult.Value);
        }
Ejemplo n.º 7
0
        private static IContext CreateContext(string contextName)
        {
            ContextFactory factory      = new ContextFactory();
            var            contextSetup = factory.Create(contextName, null);

            contextSetup.EnablePayloadDefinitionHash();

            List <IPayloadComponentId> payloadIds = new List <IPayloadComponentId>();

            Assembly currentAssembly = Assembly.GetAssembly(typeof(TestPayload));
            var      payloads        = ContextUtilities.FindPayloadComponents(currentAssembly);

            foreach (var payload in payloads)
            {
                var id = contextSetup.RegisterPayloadComponent(payload);
                payloadIds.Add(id);
            }

            IContext context = contextSetup.EndSetup();

            var           hash       = contextSetup.GetPayloadDefinitionHash();
            StringBuilder hashString = new StringBuilder(64);

            foreach (byte hashByte in hash)
            {
                hashString.Append(hashByte.ToString("x2"));
            }
            Console.WriteLine("Hash: {0}", hashString.ToString());

            TestPayload.SetId(context.FindPayloadId(nameof(TestPayload)));
            return(context);
        }
        public async Task JoinEvent_GivenPrivateEvent_UserCanNotJoin()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event privateEvent = DummyEvent(ContextUtilities.CreateRichardRoe(), true);
                context.Events.Add(privateEvent);

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
                eventId   = privateEvent.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnDoeId);

            IActionResult response = await participateEventController.JoinEvent(new JoinEventDto
            {
                EventId = eventId
            });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.InvitationRequired, objectResult.Value);
        }
Ejemplo n.º 9
0
        public async Task SetNewUserData_GivenAlreadyUsedEmail_ErrorReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int          johnId;
            const string NewName = "New Fancy Name";
            string       usedEmail;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john = context.Users.Add(ContextUtilities.CreateJohnDoe()).Entity;

                User richard = context.Users.Add(ContextUtilities.CreateRichardRoe()).Entity;
                usedEmail = richard.Email;

                await context.SaveChangesAsync();

                johnId = john.Id;
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, johnId);

            IActionResult response = await controller.SetNewUserData(new SetUserDataDto { NewEmail = usedEmail, NewFullName = NewName });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.EmailAlreadyInUse, objectResult.Value);
        }
Ejemplo n.º 10
0
        public async Task SetNewUserData_GivenValidData_UserUpdated()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int          johnId;
            const string NewName = "New Fancy Name";
            const string NewMail = "*****@*****.**";

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john = context.Users.Add(ContextUtilities.CreateJohnDoe()).Entity;

                await context.SaveChangesAsync();

                johnId = john.Id;
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, johnId);

            IActionResult response = await controller.SetNewUserData(new SetUserDataDto { NewEmail = NewMail, NewFullName = NewName });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                User loadedUser = context.Users.Single();
                Assert.Equal(NewName, loadedUser.FullName);
                Assert.Equal(NewMail, loadedUser.Email);
            }
        }
Ejemplo n.º 11
0
        public async Task CreateSession_GivenIsActiveFalse_SessionIsNotActivated()
        {
            (GetDatabaseContext getContext, SessionService sessionService) = SetupSessionService();
            int johnDoeId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> userEntry = context.Users.Add(ContextUtilities.CreateJohnDoe());
                await context.SaveChangesAsync();

                johnDoeId = userEntry.Entity.Id;
            }

            // Act
            Guid sessionId = await sessionService.CreateSessionAsync(johnDoeId, false);

            // Assert
            using (IDatabaseContext context = getContext())
            {
                Session createdSession = await context.Sessions.FindAsync(sessionId);

                Assert.NotNull(createdSession);
                Assert.InRange(createdSession.Created, DateTime.UtcNow - TimeSpan.FromMinutes(1), DateTime.UtcNow);
                Assert.Null(createdSession.ValidUntil);
            }
        }
Ejemplo n.º 12
0
        public async Task InvalidateSession_GivenInvalidSession_SessionUnchanged()
        {
            (GetDatabaseContext getContext, SessionService sessionService) = SetupSessionService();
            Session invalidUserSession;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> userEntry = context.Users.Add(ContextUtilities.CreateJohnDoe());

                invalidUserSession = new Session
                {
                    Created    = DateTime.UtcNow - TimeSpan.FromHours(10),
                    ValidUntil = DateTime.UtcNow - TimeSpan.FromHours(5),
                    User       = userEntry.Entity
                };
                context.Sessions.Add(invalidUserSession);
                await context.SaveChangesAsync();
            }

            // Act
            await sessionService.InvalidateSessionAsync(invalidUserSession.Token);

            // Assert
            using (IDatabaseContext context = getContext())
            {
                Session newlyLoadedSession = await context.Sessions.FindAsync(invalidUserSession.Token);

                Assert.NotNull(newlyLoadedSession);
                Assert.Equal(invalidUserSession.ValidUntil, newlyLoadedSession.ValidUntil);
            }
        }
Ejemplo n.º 13
0
        public async Task GetSession_GivenExpiredUnusedSession_SessionUnchanged()
        {
            _configuration.TimeSpans.UpdateValidUntilTimeSpan = TimeSpan.Zero;
            (GetDatabaseContext getContext, SessionService sessionService) = SetupSessionService();
            Session invalidUserSession;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> userEntry = context.Users.Add(ContextUtilities.CreateJohnDoe());

                invalidUserSession = new Session
                {
                    Created    = DateTime.UtcNow - _configuration.TimeSpans.UnusedSessionExpirationTimeout,
                    ValidUntil = null,
                    User       = userEntry.Entity
                };
                context.Sessions.Add(invalidUserSession);
                await context.SaveChangesAsync();
            }

            // Act
            Session loadedSession = await sessionService.GetAndExtendSessionAsync(invalidUserSession.Token);

            // Assert
            using (IDatabaseContext context = getContext())
            {
                Assert.Null(loadedSession);

                Session newlyLoadedSession = await context.Sessions.FindAsync(invalidUserSession.Token);

                Assert.NotNull(newlyLoadedSession);
                Assert.Null(newlyLoadedSession.ValidUntil);
            }
        }
Ejemplo n.º 14
0
        private (GetDatabaseContext, SessionService) SetupSessionService()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            var sessionService            = new SessionService(_configuration, getContext, DummyLogger <SessionService>());

            return(getContext, sessionService);
        }
Ejemplo n.º 15
0
        [InlineData(Email, "PASSWORD", false)]          // Password casing
        public async Task Authenticate_GivenCredentials_VerifiesPasswordAndEmail(string email, string password, bool shouldWork)
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> userEntry = context.Users.Add(ContextUtilities.CreateJohnDoe());

                userEntry.Entity.Email        = Email;
                userEntry.Entity.PasswordHash = PasswordHash;

                await context.SaveChangesAsync();
            }

            // Act
            var passwordServiceMock = new Mock <IPasswordService>();

            passwordServiceMock.Setup(p => p.NeedsRehash(PasswordHash)).Returns(false);
            passwordServiceMock.Setup(p => p.VerifyPassword(Password, PasswordHash)).Returns(true);

            var authenticationService = new AuthenticationService(passwordServiceMock.Object, getContext, DummyLogger <AuthenticationService>());

            (bool isAuthenticated, _) = await authenticationService.AuthenticateAsync(email, password);

            // Assert
            passwordServiceMock.Verify(p => p.VerifyPassword(password, PasswordHash), Times.AtMostOnce);
            if (shouldWork)
            {
                passwordServiceMock.Verify(p => p.NeedsRehash(PasswordHash), Times.Once);
            }

            Assert.Equal(shouldWork, isAuthenticated);
        }
        public async Task JoinEvent_GivenPrivateEvent_OrganizerCanJoin()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int organizerId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                Event @event = DummyEvent(ContextUtilities.CreateJohnDoe(), true);
                context.Events.Add(@event);

                await context.SaveChangesAsync();

                organizerId = @event.OrganizerId;
                eventId     = @event.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, organizerId);

            IActionResult response = await participateEventController.JoinEvent(new JoinEventDto
            {
                EventId = eventId
            });

            // Assert
            Assert.IsType <OkResult>(response);
        }
Ejemplo n.º 17
0
 static async Task P_DoSingleMessagePostingAsync(LocalPostingToken token, ILocalSubscription subscription, CancellationToken ct)
 {
     token.EnsureNotNull(nameof(token));
     subscription.EnsureNotNull(nameof(subscription));
     //
     if (subscription.IsActive)
     {
         ILocalSubscriber subscriber;
         try {
             subscriber = subscription.Subscriber;
         }
         catch (ObjectDisposedException) {
             if (subscription.IsActive)
             {
                 throw;
             }
             else
             {
                 return;
             }
         }
         //
         using (var context = ContextUtilities.Create(ct: ct))
             await subscriber.ProcessMessagePostAsync(subscription : subscription, message : token.Message, ctx : context).ConfigureAwait(false);
         //
         token.NotifySubscriptionPosted();
     }
 }
Ejemplo n.º 18
0
        public async Task SetNewPassword_GivenWrongCurrentPassword_DoesNotChangePassword()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            User         john;
            const string WrongCurrentPassword = "******";

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                john = context.Users.Add(ContextUtilities.CreateJohnDoe()).Entity;

                await context.SaveChangesAsync();
            }

            // Act
            (UserController controller, _, Mock <IPasswordService> passwordServiceMock, _) = CreateController(getContext, john.Id);
            passwordServiceMock.Setup(p => p.VerifyPassword(WrongCurrentPassword, john.PasswordHash)).Returns(false);

            IActionResult response = await controller.SetNewPassword(new SetPasswordDto { CurrentPassword = WrongCurrentPassword, NewPassword = "******" });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.CurrentPasswordWrong, objectResult.Value);
        }
        public async Task GetDetails_GivenPublicEvent_DetailsReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int publicEventId;
            int johnId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());
                User  richard           = ContextUtilities.CreateRichardRoe();
                Event publicEvent       = DummyEvent(richard);
                context.Events.Add(publicEvent);

                await context.SaveChangesAsync();

                publicEventId = publicEvent.Id;
                johnId        = john.Entity.Id;
            }

            // Act
            (ParticipateEventController participateEventController, _) = CreateController(getContext, johnId);

            IActionResult response = await participateEventController.GetDetails(publicEventId);

            // Assert
            Assert.IsType <OkObjectResult>(response);
        }
        private static async Task <Event> CreateTestDataAsync(GetDatabaseContext getContext, DateTime lastReadJohn, DateTime lastReadRichard, Func <User, User, IEnumerable <ChatMessage> > createMessagesFunc)
        {
            using (IDatabaseContext context = getContext())
            {
                User john    = ContextUtilities.CreateJohnDoe();
                User richard = ContextUtilities.CreateRichardRoe();

                var @event = new Event
                {
                    Title        = "Chatty event",
                    Description  = "An event with an active chat",
                    MeetingPlace = "Somewhere",
                    Organizer    = john,
                    ReminderTimeWindowInHours = 42,
                    SummaryTimeWindowInHours  = 24,
                    EventParticipations       = new List <EventParticipation>
                    {
                        new EventParticipation {
                            Participant = john, LastReadMessageSentDate = lastReadJohn
                        },
                        new EventParticipation {
                            Participant = richard, LastReadMessageSentDate = lastReadRichard
                        }
                    },
                    ChatMessages = createMessagesFunc(john, richard).ToList()
                };

                context.Events.Add(@event);

                await context.SaveChangesAsync();

                return(@event);
            }
        }
        public async Task DeleteEvent_GivenNonExistingEvent_ErrorReturned()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john    = ContextUtilities.CreateJohnDoe();
                User richard = ContextUtilities.CreateRichardRoe();

                Event @event = DummyEvent(richard, true);

                await context.SaveChangesAsync();

                johnDoeId = john.Id;
                eventId   = @event.Id;
            }

            // Act
            (OrganizeEventController controller, _) = CreateController(getContext, johnDoeId);

            IActionResult response = await controller.DeleteEvent(eventId);

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var objectResult = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.EventNotFound, objectResult.Value);
        }
Ejemplo n.º 22
0
        public async Task DeleteAccount_GivenSimpleUser_UserDeleted()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
            }

            // Act
            (UserController controller, _, _, _) = CreateController(getContext, johnDoeId);
            IActionResult response = await controller.DeleteAccount();

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                Assert.Empty(context.Users);
            }
        }
Ejemplo n.º 23
0
        public async Task GetSession_GivenValidSessionWhichWasRecentlyUpdated_SessionUnchanged()
        {
            _configuration.TimeSpans.UpdateValidUntilTimeSpan = TimeSpan.FromHours(1);
            (GetDatabaseContext getContext, SessionService sessionService) = SetupSessionService();
            Guid     sessionToken;
            DateTime originalSessionValidUntil = DateTime.UtcNow + _configuration.TimeSpans.InactiveSessionTimeout;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> userEntry = context.Users.Add(ContextUtilities.CreateJohnDoe());

                var validUserSession = new Session
                {
                    Created    = DateTime.UtcNow,
                    ValidUntil = originalSessionValidUntil,
                    User       = userEntry.Entity
                };
                context.Sessions.Add(validUserSession);
                await context.SaveChangesAsync();

                sessionToken = validUserSession.Token;
            }

            // Act
            await Task.Delay(1);

            Session loadedSession = await sessionService.GetAndExtendSessionAsync(sessionToken);

            // Assert
            Assert.NotNull(loadedSession);
            Assert.Equal(originalSessionValidUntil, loadedSession.ValidUntil);
        }
        public override void InitialiseSystemUnderTest()
        {
            SUT = new EmptyParameterFilterAttribute(_parameterName);
            var request = new HttpRequestMessage();

            _actionContext = ContextUtilities.GetHttpActionContext(request);
            _actionContext.ActionArguments[_parameterName] = null;
        }
        public async Task RemoveFromEvent_GivenParticipatingUser_UserLeavesEventAndAppointments()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;
            int appointmentId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event @event = DummyEvent(ContextUtilities.CreateRichardRoe());

                context.EventParticipations.Add(new EventParticipation {
                    Participant = john.Entity, Event = @event
                });

                var appointment = new Appointment
                {
                    Event     = @event,
                    StartTime = DateTime.UtcNow + TimeSpan.FromDays(1)
                };

                context.AppointmentParticipations.Add(new AppointmentParticipation {
                    Appointment = appointment, Participant = john.Entity, AppointmentParticipationAnswer = AppointmentParticipationAnswer.Accepted
                });

                await context.SaveChangesAsync();

                johnDoeId     = john.Entity.Id;
                eventId       = @event.Id;
                appointmentId = appointment.Id;
            }

            // Act
            (ParticipateEventController participateEventController, Mock <AssertingNotificationService> notificationServiceMock) = CreateController(getContext, johnDoeId);
            Expression <Func <AssertingNotificationService, Task> > sendLastMinuteChangeExpression = n => n.SendLastMinuteChangeIfRequiredAsync(It.Is <Appointment>(a => a.Id == appointmentId));

            notificationServiceMock.Setup(sendLastMinuteChangeExpression).CallBase();

            IActionResult response = await participateEventController.RemoveFromEvent(new RemoveFromEventDto
            {
                EventId = eventId,
                UserId  = johnDoeId
            });

            // Assert
            Assert.IsType <OkResult>(response);
            notificationServiceMock.Verify(sendLastMinuteChangeExpression, Times.Once);
            using (IDatabaseContext context = getContext())
            {
                Assert.Single(context.Events);
                Assert.Empty(context.EventParticipations);
                Assert.Single(context.Appointments);
                Assert.Empty(context.AppointmentParticipations);
            }
        }
        public async Task RemoveFromEvent_GivenDeclinedUser_NoUpdateSent()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                EntityEntry <User> john = context.Users.Add(ContextUtilities.CreateJohnDoe());

                Event @event = DummyEvent(ContextUtilities.CreateRichardRoe());

                context.EventParticipations.Add(new EventParticipation {
                    Participant = john.Entity, Event = @event
                });

                var appointment = new Appointment
                {
                    Event     = @event,
                    StartTime = DateTime.UtcNow + TimeSpan.FromDays(1)
                };

                context.AppointmentParticipations.Add(new AppointmentParticipation {
                    Appointment = appointment, Participant = john.Entity, AppointmentParticipationAnswer = AppointmentParticipationAnswer.Declined
                });
                context.AppointmentParticipations.Add(new AppointmentParticipation {
                    Appointment = appointment, Participant = john.Entity, AppointmentParticipationAnswer = null
                });

                await context.SaveChangesAsync();

                johnDoeId = john.Entity.Id;
                eventId   = @event.Id;
            }

            // Act
            (ParticipateEventController participateEventController, Mock <AssertingNotificationService> _) = CreateController(getContext, johnDoeId);

            IActionResult response = await participateEventController.RemoveFromEvent(new RemoveFromEventDto
            {
                EventId = eventId,
                UserId  = johnDoeId
            });

            // Assert
            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                Assert.Single(context.Events);
                Assert.Empty(context.EventParticipations);
                Assert.Single(context.Appointments);
                Assert.Empty(context.AppointmentParticipations);
            }
        }
Ejemplo n.º 27
0
        public async Task DeleteAccount_GivenUserWithEvents_UserAndEventsDeleted()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);
            int johnDoeId;
            int eventId1;
            int eventId2;

            // Arrange
            using (IDatabaseContext context = getContext())
            {
                User john = ContextUtilities.CreateJohnDoe();

                Event event1 = DummyEvent(john);
                Event event2 = DummyEvent(john, true);
                context.EventParticipations.Add(new EventParticipation {
                    Event = event1, Participant = john
                });
                context.EventParticipations.Add(new EventParticipation {
                    Event = event2, Participant = john
                });

                context.EventInvitations.Add(new EventInvitation {
                    Event = event1, Requested = DateTime.UtcNow
                });
                context.EventInvitations.Add(new EventInvitation {
                    Event = event2, Requested = DateTime.UtcNow
                });

                await context.SaveChangesAsync();

                johnDoeId = john.Id;
                eventId1  = event1.Id;
                eventId2  = event2.Id;
            }

            // Act
            (UserController controller, _, _, Mock <AssertingNotificationService> notificationMock) = CreateController(getContext, johnDoeId);

            notificationMock.Setup(n => n.NotifyEventDeletedAsync(It.Is <EventNotificationInformation>(e => e.Id == eventId1))).CallBase();
            notificationMock.Setup(n => n.NotifyEventDeletedAsync(It.Is <EventNotificationInformation>(e => e.Id == eventId2))).CallBase();

            IActionResult response = await controller.DeleteAccount();

            // Assert
            notificationMock.Verify(n => n.NotifyEventDeletedAsync(It.Is <EventNotificationInformation>(e => e.Id == eventId1)), Times.Once);
            notificationMock.Verify(n => n.NotifyEventDeletedAsync(It.Is <EventNotificationInformation>(e => e.Id == eventId2)), Times.Once);

            Assert.IsType <OkResult>(response);
            using (IDatabaseContext context = getContext())
            {
                Assert.Empty(context.Users);
                Assert.Empty(context.Events);
                Assert.Empty(context.EventParticipations);
            }
        }
        public async Task ResetPassword_GivenInvalidPasswordReset_RequestRejected()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Act
            (ResetPasswordController controller, _, _) = CreateController(getContext, null);

            IActionResult response = await controller.ResetPassword(new ResetPasswordDto { NewPassword = "******", PasswordResetToken = Guid.NewGuid() });

            // Assert
            Assert.IsType <BadRequestObjectResult>(response);
            var badRequestResponse = (BadRequestObjectResult)response;

            Assert.Equal(RequestStringMessages.ResetCodeInvalid, badRequestResponse.Value);
        }
        public async Task RunAsync_GivenFutureAppointments_SendsReminder()
        {
            GetDatabaseContext getContext = ContextUtilities.CreateInMemoryContext(_output);

            // Arrange
            Appointment appointment = await CreateTestDataAsync(getContext, DateTime.UtcNow + TimeSpan.FromHours(ReminderTimeWindowInHours));

            // Act
            (CronSendReminderAndSummaryService service, Mock <AssertingNotificationService> notificationServiceMock) = CreateService(getContext);
            notificationServiceMock.Setup(n => n.SendAndUpdateRemindersAsync(It.Is <Appointment>(a => a.Id == appointment.Id))).CallBase();
            await service.RunAsync(CancellationToken.None);

            // Assert
            notificationServiceMock.Verify(n => n.SendAndUpdateRemindersAsync(It.Is <Appointment>(a => a.Id == appointment.Id)), Times.Once);
        }
        private static async Task <Appointment> CreateTestDataAsync(GetDatabaseContext getContext, DateTime startTime)
        {
            using (IDatabaseContext context = getContext())
            {
                User john    = ContextUtilities.CreateJohnDoe();
                User richard = ContextUtilities.CreateRichardRoe();

                var @event = new Event
                {
                    Title        = "Upcoming event",
                    Description  = "An event with upcoming appointments",
                    MeetingPlace = "Somewhere",
                    Organizer    = john,
                    ReminderTimeWindowInHours = ReminderTimeWindowInHours,
                    SummaryTimeWindowInHours  = SummaryTimeWindowInHours,
                    EventParticipations       = new List <EventParticipation>
                    {
                        new EventParticipation {
                            Participant = john
                        },
                        new EventParticipation {
                            Participant = richard
                        }
                    }
                };

                var appointment = new Appointment
                {
                    Event = @event,
                    AppointmentParticipations = new List <AppointmentParticipation>
                    {
                        new AppointmentParticipation {
                            Participant = john
                        },
                        new AppointmentParticipation {
                            Participant = richard
                        }
                    },
                    StartTime = startTime
                };

                context.Appointments.Add(appointment);

                await context.SaveChangesAsync();

                return(appointment);
            }
        }