public async void get_notifications_should_return_all_notifications_per_user() { var options = new DbContextOptionsBuilder <DatabaseContext>().UseInMemoryDatabase(databaseName: "NotificationTest").Options; string userId = "1"; using (var context = new DatabaseContext(options)) { // Act var controller = new NotificationsController(context); AddUserClaim(controller, userId); context.Users.Add(new User() { FacebookId = userId }); context.Notifications.Add(new Notification() { ReceiverId = "1", MessageType = 1, Id = 1 }); context.Notifications.Add(new Notification() { ReceiverId = "2", MessageType = 1, Id = 2 }); context.SaveChanges(); var notifications = await controller.GetNotifications(); // Assert var notificationsCount = notifications.Value.Count(); Assert.Equal(1, notificationsCount); } }
public async void ConfirmNotification_OkResult() { // Arrange Notification notification = new Notification { Id = 1 }; Mock <GenericRepository <Notification> > mockNotificationRepository = new Mock <GenericRepository <Notification> >(); mockNotificationRepository .Setup(nr => nr.GetAsync(It.IsAny <int>(), It.IsAny <string>())) .Returns(Task.FromResult(notification)); Mock <IUnitOfWork> mockUnitOfWork = new Mock <IUnitOfWork>(); mockUnitOfWork .Setup(u => u.GetRepository <Notification, GenericRepository <Notification> >()) .Returns(mockNotificationRepository.Object); NotificationsController controller = new NotificationsController(mockUnitOfWork.Object); // Act IActionResult result = await controller.ConfirmNotification(notification.Id); // Assert Assert.NotNull(result); Assert.IsType <OkResult>(result); }
public async Task <ActionResult> NewEmployee(CreateEmployeeViewModel employee) { if (ModelState.IsValid) { var res = await createEmployeeCommand.Create(employee); if (res.Successful) { NotificationsController.AddNotification(this.User.SafeUserName(), $"{employee.Email} has been created."); return(RedirectToAction(nameof(NewEmployee))); } else { foreach (var err in res.Errors) { ModelState.AddModelError(string.Empty, err); } } } employee.AvailableJobs = await jobService.GetAsync(); employee.AvailableRoles = await employeeService.GetAllRoles(); return(View("NewEmployee", employee)); }
public async void AddNotification_ReturnsCreatedAtRouteResult_WithNotificationData() { //Arrange _mockUserService.Setup(Service => Service.CheckIfUserExists(It.IsAny <Guid>())) .ReturnsAsync(true) .Verifiable(); _mockNotificationService.Setup(Service => Service.AddNotificationAsync(It.IsAny <Guid>(), It.IsAny <NotificationToAddDto>())) .ReturnsAsync(_mapper.Map <NotificationDto>(_notificationToAdd)) .Verifiable(); var controller = new NotificationsController(_loggerMock.Object, _mockNotificationService.Object, _mockUserService.Object); //Act var result = await controller.AddNotification(ConstIds.ExampleUserId, _notificationToAdd); //Assert var redirectToActionResult = Assert.IsType <CreatedAtRouteResult>(result.Result); Assert.Equal(ConstIds.ExampleUserId, redirectToActionResult.RouteValues["userId"].ToString()); Assert.NotNull(redirectToActionResult.RouteValues["notificationId"].ToString()); Assert.Equal("GetNotification", redirectToActionResult.RouteName); _mockUserService.Verify(); _mockNotificationService.Verify(); }
public void GivenACreateAction_ThenItSendsAMessage() { var notificationServiceMock = new Mock <INotificationService>(); notificationServiceMock .Setup(m => m.SendAsync(It.IsAny <string>())) .ReturnsAsync(MessageResource.FromJson("{}")); HttpContext.Current = new HttpContext( new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null)); var controller = new NotificationsController(notificationServiceMock.Object); var lead = new Lead { HouseTitle = "La Maison", Name = "Alice", Phone = "555-5555", Message = "Welcome back!" }; controller .WithCallTo(c => c.Create(lead)) .ShouldRedirectTo <HomeController>(c => c.Index()); const string message = "New lead received for La Maison. " + "Call Alice at 555-5555. Message: Welcome back!"; notificationServiceMock.Verify(c => c.SendAsync(message), Times.Once); }
public NotificationsControllerUnitTests() { _mockRepo = new Mock <IUnitOfWork <Main_MadPayDbContext> >(); _mockMapper = new Mock <IMapper>(); _mockLogger = new Mock <ILogger <NotificationsController> >(); _controller = new NotificationsController(_mockRepo.Object, _mockLogger.Object, _mockMapper.Object); }
public async Task Add_user_Notification_success() { //Arrange var model = new NotificationEventModel { Data = new NotificationData { AppointmentDateTime = "23/01/2020", FirstName = "Romio", OrganisationName = "Little Runners", Reason = "Healthy" }, Type = "AppointmentCancelled", UserId = Guid.NewGuid() }; //Act var catalogContext = new NotificationsDbContext(_dbOptions); var accessServ = new NotificationsAccess(catalogContext); var NotificationServ = new NotificationsService(accessServ); var testController = new NotificationsController(NotificationServ); var actionResult = await testController.AddUserNotification(model).ConfigureAwait(false); //Assert Assert.IsType <OkObjectResult>(actionResult); var result = Assert.IsAssignableFrom <NotificationModel>(((OkObjectResult)actionResult).Value); Assert.Contains("Healthy", result.Message); }
public async Task <IActionResult> Index([FromRoute(Name = "week-id")] int weekid, [FromRoute(Name = "employee-id")] int employeeId, [FromRoute(Name = "job-id")] int jobId, [FromRoute(Name = "task-id")] int taskId) { var currentUserId = await _sessionAdapter.EmployeeIdAsync(); if (!User.IsInRole(UserRoleName.Admin) && employeeId != currentUserId) { var msg = "You are not allowed to edit another users effort selection."; return(CreateErrorResponse(msg)); } var removeResult = await _removeRowCommand.RemoveRow(employeeId, weekid, taskId, jobId); if (removeResult.Successful) { NotificationsController.AddNotification(User.SafeUserName(), "The selected effort was removed."); return(new ObjectResult(new ApiResult <string>() { Data = "The selected effort was removed." }) { StatusCode = StatusCodes.Status200OK }); } else { return(CreateErrorResponse(string.Join(", ", removeResult.Errors))); } }
public static void NotifyMatchPeople(IDbConnection c, IDbTransaction t, Match m) { var text = GetSpanishMessage(m); var title = "Horario de partido"; NotificationsController.NotifyMatch(c, t, m, title, text); }
public void Given_SyncActionIsCalled_When_ANonExistingBlockHashIsSpecified_Then_ABadRequestErrorIsReturned() { // Set up string hashLocation = "000000000000000000c03dbe6ee5fedb25877a12e32aa95bc1d3bd480d7a93f9"; var chain = new Mock <ConcurrentChain>(); chain.Setup(c => c.GetBlock(uint256.Parse(hashLocation))).Returns((ChainedBlock)null); var blockNotification = new Mock <BlockNotification>(this.LoggerFactory.Object, chain.Object, new Mock <ILookaheadBlockPuller>().Object, new Signals.Signals(), new AsyncLoopFactory(new LoggerFactory()), new NodeLifetime()); // Act var notificationController = new NotificationsController(blockNotification.Object, chain.Object); // Assert IActionResult result = notificationController.SyncFrom(hashLocation); ErrorResult errorResult = Assert.IsType <ErrorResult>(result); ErrorResponse errorResponse = Assert.IsType <ErrorResponse>(errorResult.Value); Assert.Single(errorResponse.Errors); ErrorModel error = errorResponse.Errors[0]; Assert.Equal(400, error.Status); }
public async Task <ActionResult> Create([Bind(Include = "ID,NauczycielID,naglowek,tresc,data")] Ogloszenie ogloszenie) { if (((string)Session["Status"] != "Nauczyciel") && ((string)Session["Status"] != "Admin")) { return(RedirectToAction("Index", "Home")); } if (ModelState.IsValid) { db.Ogloszenia.Add(ogloszenie); ogloszenie.data = DateTime.Now; var user = Session["UserID"]; string ide = user.ToString(); int id1 = Convert.ToInt32(ide); ogloszenie.NauczycielID = id1; db.SaveChanges(); var notiContrl = new NotificationsController(); var noti = new Notification(ogloszenie); noti.OnClickLink = Url.Content("~"); await notiContrl.PostNotificationAsync(noti); return(RedirectToAction("Index")); } ViewBag.NauczycielID = Session["UserID"]; ViewBag.data = DateTime.Now; return(View(ogloszenie)); }
public async Task DeleteListener(Boolean mediatorResult) { Random random = new Random(); Guid pipelineId = random.NextGuid(); Mock <IMediator> mediatorMock = new Mock <IMediator>(MockBehavior.Strict); mediatorMock.Setup(x => x.Send(It.Is <DeleteNotificationPipelineCommand>(y => y.PipelineId == pipelineId ), It.IsAny <CancellationToken>())).ReturnsAsync(mediatorResult).Verifiable(); var controller = new NotificationsController( Mock.Of <INotificationEngine>(MockBehavior.Strict), mediatorMock.Object, Mock.Of <ILogger <NotificationsController> >()); var actionResult = await controller.DeletePipeline(pipelineId); if (mediatorResult == true) { actionResult.EnsureNoContentResult(); } else { actionResult.EnsureBadRequestObjectResult("unable to delete the pipeline"); } mediatorMock.Verify(); }
public void Given_SyncActionIsCalled_When_HeightNotOnChain_Then_ABadRequestErrorIsReturned() { // Set up var chain = new Mock <ChainIndexer>(); chain.Setup(c => c.GetHeader(15)).Returns((ChainedHeader)null); ConsensusManager consensusManager = ConsensusManagerHelper.CreateConsensusManager(this.network); var loggerFactory = new Mock <LoggerFactory>(); var signals = new Signals.Signals(loggerFactory.Object, null); var nodeLifetime = new NodeLifetime(); var asyncProvider = new AsyncProvider(loggerFactory.Object, signals, nodeLifetime); var blockNotification = new Mock <BlockNotification>(this.LoggerFactory.Object, chain.Object, consensusManager, signals, asyncProvider, nodeLifetime); // Act var notificationController = new NotificationsController(blockNotification.Object, chain.Object); // Assert IActionResult result = notificationController.SyncFrom("15"); var errorResult = Assert.IsType <ErrorResult>(result); var errorResponse = Assert.IsType <ErrorResponse>(errorResult.Value); Assert.Single(errorResponse.Errors); ErrorModel error = errorResponse.Errors[0]; Assert.Equal(400, error.Status); }
public void Given_SyncActionIsCalled_When_ABlockHashIsSpecified_Then_TheChainIsSyncedFromTheHash() { // Set up int heightLocation = 480946; var header = this.network.Consensus.ConsensusFactory.CreateBlockHeader(); uint256 hash = header.GetHash(); string hashLocation = hash.ToString(); var chainedHeader = new ChainedHeader(this.network.Consensus.ConsensusFactory.CreateBlockHeader(), hash, null); var chain = new Mock <ChainIndexer>(); chain.Setup(c => c.GetHeader(uint256.Parse(hashLocation))).Returns(chainedHeader); ConsensusManager consensusManager = ConsensusManagerHelper.CreateConsensusManager(this.network); var loggerFactory = new Mock <LoggerFactory>(); var signals = new Signals.Signals(loggerFactory.Object, null); var nodeLifetime = new NodeLifetime(); var asyncProvider = new AsyncProvider(loggerFactory.Object, signals, nodeLifetime); var blockNotification = new Mock <BlockNotification>(this.LoggerFactory.Object, chain.Object, consensusManager, signals, asyncProvider, nodeLifetime); // Act var notificationController = new NotificationsController(blockNotification.Object, chain.Object); IActionResult result = notificationController.SyncFrom(hashLocation); // Assert chain.Verify(c => c.GetHeader(heightLocation), Times.Never); blockNotification.Verify(b => b.SyncFrom(hash), Times.Once); }
public async Task <ActionResult> EditClient(ClientModel client) { await _clientRepository.Save(_mapper.Map <ClientDTO>(client)); NotificationsController.AddNotification(this.User.SafeUserName(), $"{client.ClientName} was updated"); return(RedirectToAction(nameof(ListClients))); }
public void Given_SyncActionIsCalled_When_ANonExistingBlockHashIsSpecified_Then_ABadRequestErrorIsReturned() { // Set up string hashLocation = "000000000000000000c03dbe6ee5fedb25877a12e32aa95bc1d3bd480d7a93f9"; var chain = new Mock <ChainIndexer>(); chain.Setup(c => c.GetHeader(uint256.Parse(hashLocation))).Returns((ChainedHeader)null); ConsensusManager consensusManager = ConsensusManagerHelper.CreateConsensusManager(this.network); var loggerFactory = new Mock <LoggerFactory>(); var signals = new Signals.Signals(loggerFactory.Object, null); var nodeLifetime = new NodeLifetime(); var asyncProvider = new AsyncProvider(loggerFactory.Object, signals, nodeLifetime); var blockNotification = new Mock <BlockNotification>(this.LoggerFactory.Object, chain.Object, consensusManager, signals, asyncProvider, nodeLifetime); // Act var notificationController = new NotificationsController(blockNotification.Object, chain.Object); // Assert IActionResult result = notificationController.SyncFrom(hashLocation); var errorResult = Assert.IsType <ErrorResult>(result); var errorResponse = Assert.IsType <ErrorResponse>(errorResult.Value); Assert.Single(errorResponse.Errors); ErrorModel error = errorResponse.Errors[0]; Assert.Equal(400, error.Status); }
public async void ConfirmNotificationNotificationIsNull_BadRequest() { // Arrange Notification notification = new Notification { Id = 1 }; Mock <GenericRepository <Notification> > mockNotificationRepository = new Mock <GenericRepository <Notification> >(); mockNotificationRepository .Setup(nr => nr.GetAsync(It.IsAny <int>(), It.IsAny <string>())) .Returns(Task.FromResult(null as Notification)); Mock <IUnitOfWork> mockUnitOfWork = new Mock <IUnitOfWork>(); mockUnitOfWork .Setup(u => u.GetRepository <Notification, GenericRepository <Notification> >()) .Returns(mockNotificationRepository.Object); NotificationsController controller = new NotificationsController(mockUnitOfWork.Object); // Act IActionResult result = await controller.ConfirmNotification(notification.Id); // Assert Assert.NotNull(result); BadRequestObjectResult badRequestObjectResult = Assert.IsType <BadRequestObjectResult>(result); Assert.Equal("No such notification", badRequestObjectResult.Value.ToString()); }
public void Ctor_ValidInput() { this.SetupBase(); var controller = new NotificationsController(this.NotificationsManagerMock.Object, this.LoggerMock.Object); Assert.IsTrue(controller.GetType().FullName.Equals(typeof(NotificationsController).FullName, StringComparison.Ordinal)); }
public ActionResult Unfollow(int id, int loggedId) { repo.Follow(id, loggedId); //TODO: use notificatoins repository; NotificationsController.RemoveFollowNotification(loggedId, id); return(RedirectToAction($"Details/{id}")); }
public async void GetNotification_ReturnsOkObjectResult_WithNotificationData() { //Arrange var notification = GetTestNotificationData().ElementAt(0); _mockUserService.Setup(Service => Service.CheckIfUserExists(It.IsAny <Guid>())) .ReturnsAsync(true) .Verifiable(); _mockNotificationService.Setup(Service => Service.GetNotification(It.IsAny <Guid>())) .Returns(notification) .Verifiable(); var controller = new NotificationsController(_loggerMock.Object, _mockNotificationService.Object, _mockUserService.Object); //Act var result = await controller.GetNotification(ConstIds.ExampleUserId, ConstIds.ExampleNotificationId); //Assert var actionResult = Assert.IsType <OkObjectResult>(result.Result); var model = Assert.IsType <NotificationDto>(actionResult.Value); Assert.Equal(notification, model); _mockUserService.Verify(); _mockNotificationService.Verify(); }
public void GivenACreateAction_ThenRendersDefaultView() { var controller = new NotificationsController(); controller.WithCallTo(c => c.Create()) .ShouldRenderDefaultView(); }
public async Task getAnnouncementsTest() { IConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.AddJsonFile("AppSettings.json"); IConfiguration configuration = configurationBuilder.Build(); GymRepository gym = new GymRepository(DbContext); await gym.addGym(new Gym { GymName = "testName", GymBranch = "testBranch" }); NotificationsRepository notif = new NotificationsRepository(DbContext); await notif.addNotification(new Notifications { Body = "body", Date = DateTime.Now, Heading = "heading", GymIdForeignKey = 1 }); var controller = new NotificationsController(new NotificationSettingsRepository(DbContext), notif, gym, new Mailer(configuration)); var okObjectResult = Assert.IsType <Task <ActionResult <Notifications[]> > >(controller.getAllAnnouncements(1)); //Assert.IsNotType<string>(okObjectResult.Value); }
public void WindowsPhoneTest() { var controller = new NotificationsController(null, null); var result = controller.WindowsPhone(); Assert.IsFalse(result.IsSuccessful); Assert.AreEqual("Method is not implemented yet", result.Message); }
public void List_ViewResult() { // Arrange int userId = 1; IEnumerable <Notification> notifications = new List <Notification> { new Notification { Id = 1 }, new Notification { Id = 2 } }; Mock <GenericRepository <Notification> > mockNotificationRepository = new Mock <GenericRepository <Notification> >(); mockNotificationRepository .Setup(nr => nr.Get(It.IsAny <Expression <Func <Notification, bool> > >(), It.IsAny <Func <IQueryable <Notification>, IOrderedQueryable <Notification> > >(), It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>())) .Returns(notifications); Mock <IUnitOfWork> mockUnitOfWork = new Mock <IUnitOfWork>(); mockUnitOfWork .Setup(u => u.GetRepository <Notification, GenericRepository <Notification> >()) .Returns(mockNotificationRepository.Object); ControllerBase controller = new NotificationsController(mockUnitOfWork.Object); Mock <ClaimsPrincipal> userMock = new Mock <ClaimsPrincipal>(); userMock .Setup(p => p.FindFirst(It.IsAny <string>())) .Returns(new Claim(nameof(User.Id), userId.ToString())); controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext() { User = userMock.Object } }; // Act IActionResult result = (controller as NotificationsController)?.List(); // Assert Assert.NotNull(result); ViewResult viewResult = Assert.IsType <ViewResult>(result); Assert.NotNull(viewResult.Model); ListViewModel listViewModel = Assert.IsType <ListViewModel>(viewResult.Model); Assert.Same(notifications, listViewModel.Notifications); Assert.Null(viewResult.ViewName); }
public NotificationListbox(NotificationsController viewModel) { InitializeComponent(); this.DataContext = viewModel; //this.HorizontalAlignment = HorizontalAlignment.Left; this.HorizontalContentAlignment = HorizontalAlignment.Left; }
void SaveToggle() { NotificationsController nc = new NotificationsController(); bool allNotifications = varselSwitch.IsToggled; bool jobNotifications = stillingSwitch.IsToggled; bool projectNotification = oppgaveSwitch.IsToggled; nc.UpdateStudentsNotificationsPref(allNotifications, projectNotification, jobNotifications); }
public void Has_GetAll() { // arrange var controller = new NotificationsController(_notificationService.Object); // act var result = controller.GetAll(); // assert result.Should().NotBeNull(); }
public async Task <ActionResult> CloseJob(int id) { var job = await _jobsRepository.GetForJobId(id); job.CoreInfo.JobStatusId = JobStatus.Archived; await _jobsRepository.Update(job.CoreInfo); NotificationsController.AddNotification(User.Identity.Name, $"Job {job.CoreInfo.FullJobCodeWithName} has been closed"); return(RedirectToAction(nameof(List))); }
public void SetUp() { _mockNotificationRepository = new Mock <INotificationRepository>(); _mockUnitOfWork = new Mock <IUnitOfWork>(); _mockUnitOfWork.SetupGet(u => u.Notifications).Returns(_mockNotificationRepository.Object); _controller = new NotificationsController(_mockUnitOfWork.Object); _controller.MockCurrentUser(_UserId, _UserName); }
public ActionResult UnlikePicture(int id, int loggedId) { var pic = db.Pictures.Find(id); var user = db.Users.Find(loggedId); pic.Likes.Remove(user); db.SaveChanges(); NotificationsController.RemoveLikeNotification(loggedId, id); return(RedirectToAction($"Details/{id}")); }