public void CreateNewPhoto() { // arrange var mockUserRep = new Mock <IUserRepository>(); var mockPhotoRep = new Mock <IPhotoRepository>(); var mockLogger = new Mock <INRAKOLogger>(); var mockS3Amazon = new Mock <AmazonS3Tools>(); var mockMutation = new Mock <IMutationActionFactorySelector>(); CreatePhotoViewModel photoVM = new CreatePhotoViewModel() { Description = "Test", DoConversion = false, DoResize = false, HashtagsString = "Test", OriginalImageExtension = "png" }; mockUserRep.Setup(x => x.GetUser(null)).Returns((NRAKOUser)null); mockLogger.Setup(x => x.Log(null, null)); mockPhotoRep.Setup(x => x.SavePhoto(photoVM, null)).Returns(new Photo { Size = 0, Width = 0, Height = 0 }); var controller = new PhotosController(mockUserRep.Object, mockPhotoRep.Object, mockLogger.Object, mockS3Amazon.Object, mockMutation.Object); // act var result = controller.CreateNewPhoto(photoVM); // assert var redirectToActionResult = Assert.IsType <RedirectToActionResult>(result); Assert.Equal("Index", redirectToActionResult.ActionName); Assert.Null(redirectToActionResult.ControllerName); }
public async Task WhenGetByIdIsCalledAPhotoMustBeReturned() { var photoId = "1234"; var photoStoreMock = new Mock <Domain.IPhotoStore>(); photoStoreMock.Setup(m => m.GetPhotoDetailsAsync(photoId)).Returns( Task.FromResult <Domain.IPhotoMetadata>(new Models.PhotoMetadata { Id = photoId, Title = "Hi" })); var sut = new PhotosController(photoStoreMock.Object); //sut.ControllerContext.HttpContext = ; var response = await sut.Get(photoId); Assert.IsType <ActionResult <Domain.IPhotoMetadata> >(response); Assert.NotNull(response.Result); Assert.IsType <OkObjectResult>(response.Result); var statusCode = ((OkObjectResult)response.Result).StatusCode; var value = ((OkObjectResult)response.Result).Value as Domain.IPhotoMetadata; Assert.Equal(statusCode, (int)System.Net.HttpStatusCode.OK); Assert.NotNull(value); Assert.True(string.Equals(value.Id, photoId, System.StringComparison.InvariantCultureIgnoreCase)); Assert.True(string.Equals(value.Title, "Hi", System.StringComparison.InvariantCultureIgnoreCase)); }
public async Task NotGetPhoto_NotFound() { // Arrange var seedIds = new List <int> { new Random().Next(1, 50), new Random().Next(51, 100) }; var notFoundId = GetRandomIntExcept(seedIds); var mockPhotoRepository = new Mock <IPhotoRepository>(); mockPhotoRepository.Setup(m => m.GetAsync(notFoundId, true)).ReturnsAsync((Photo)null); var mockCommentRepository = new Mock <ICommentRepository>(); var mockCategoryRepository = new Mock <ICategoryRepository>(); var mockUserRepository = new Mock <IUserRepository>(); var mockAlbumRepository = new Mock <IAlbumRepository>(); var mockUnitOfWork = new Mock <IUnitOfWork>(); var mockPhotoUploadService = new Mock <IPhotoUploadService>(); var mockHost = new Mock <IWebHostEnvironment>(); mockHost.SetupGet(m => m.WebRootPath).Returns(string.Empty); var mockObjectDetectionService = new Mock <IObjectDetectionService>(); PhotosController controller = new PhotosController(this._mapper, mockPhotoRepository.Object, mockCategoryRepository.Object, mockUserRepository.Object, mockCommentRepository.Object, mockAlbumRepository.Object, mockUnitOfWork.Object, mockPhotoUploadService.Object, mockHost.Object, mockObjectDetectionService.Object); // Act var result = await controller.GetPhoto(notFoundId); // Assert Assert.IsType <NotFoundResult>(result); }
public async Task DeleteAlbumShouldReturnBadRequestIfUserTriesToDeleteForeignAlbum() { // Arrange var pictureService = new Mock <IPictureService>(); var userManager = MockManager.GetMockUserManger(); pictureService .Setup(s => s.AlbumOwnerId(It.IsAny <int>())). ReturnsAsync(Guid.NewGuid().ToString()); userManager .Setup(s => s.GetUserId(It.IsAny <ClaimsPrincipal>())) .Returns(Guid.NewGuid().ToString()); var controller = new PhotosController(pictureService.Object, null, userManager.Object); controller.LoginMockUser(); // Act var result = await controller.DeleteAlbum(1); // Assert result .Should() .BeOfType <BadRequestObjectResult>(); }
public void Index() { // arrange var mockUserRep = new Mock <IUserRepository>(); var mockPhotoRep = new Mock <IPhotoRepository>(); var mockLogger = new Mock <INRAKOLogger>(); var mockS3Amazon = new Mock <AmazonS3Tools>(); var mockMutation = new Mock <IMutationActionFactorySelector>(); mockUserRep.Setup(x => x.GetUser(null)).Returns((NRAKOUser)null); mockPhotoRep.Setup(x => x.GetPhotos()).Returns(GetPhotos()); mockPhotoRep.Setup(x => x.PhotoDefaultIfEmpty()).Returns(new List <Photo>() { new Photo { Size = 0, Width = 0, Height = 0 } }); var controller = new PhotosController(mockUserRep.Object, mockPhotoRep.Object, mockLogger.Object, mockS3Amazon.Object, mockMutation.Object); // act var result = controller.Index(); // assert var viewResult = Assert.IsType <ViewResult>(result); var model = Assert.IsAssignableFrom <List <PhotoViewModel> >( viewResult.ViewData.Model); Assert.Equal(2, model.Count); }
public async Task DeleteAlbumShouldReturnOkIfTheUserDeletesOwnPicture() { // Arrange var userId = Guid.NewGuid().ToString(); var pictureService = new Mock <IPictureService>(); var userManager = MockManager.GetMockUserManger(); pictureService .Setup(s => s.AlbumOwnerId(It.IsAny <int>())). ReturnsAsync(userId); pictureService .Setup(s => s.DeleteAlbumByIdAsync(It.IsAny <int>())) .ReturnsAsync(true); userManager .Setup(s => s.GetUserId(It.IsAny <ClaimsPrincipal>())) .Returns(userId); var controller = new PhotosController(pictureService.Object, null, userManager.Object); controller.LoginMockUser(); // Act var result = await controller.DeleteAlbum(1); // Assert result .Should() .BeOfType <OkResult>(); }
public async Task CreateAlbumShouldReturnOkIfTitleAndDescriptionAreProvided() { // Arrange var pictureService = new Mock <IPictureService>(); var userManager = MockManager.GetMockUserManger(); pictureService .Setup(s => s.CreateAlbumAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync(true); userManager .Setup(s => s.GetUserId(It.IsAny <ClaimsPrincipal>())) .Returns(Guid.NewGuid().ToString()); var controller = new PhotosController(pictureService.Object, null, userManager.Object); controller.LoginMockUser(); // Act var result = await controller.CreateAlbum("fakeTitle", "fakeDescription"); // Assert result .Should() .BeOfType <OkResult>(); }
public static PhotosController GetPhotosController(IRepository <Photo> photos, IRepository <Album> albums, bool validUser = true) { var controller = new PhotosController(photos, albums); SetUser(controller, validUser); return(controller); }
public void GetPaginationPhotos_EmptyContainerOfPhotos_ThrowInvalidOperationException() { var authServiceMock = new Mock <IAuthService>(); var dataServiceMock = new Mock <IDataService>(); var paginationPhotosRequestDto = new PaginationPhotosRequestDto() { PageNumber = 2, PageSize = 10 }; dataServiceMock.Setup(u => u.GetPaginationPhotos((paginationPhotosRequestDto.PageNumber - 1) * paginationPhotosRequestDto.PageSize, paginationPhotosRequestDto.PageSize)) .Throws(new InvalidDataException("Photos don`t exist.")); var controller = new PhotosController(dataServiceMock.Object, authServiceMock.Object); var result = controller.GetPaginationPhotos(paginationPhotosRequestDto); var statusCode = ((BadRequestObjectResult)result).StatusCode; var jsonValue = JsonConvert.SerializeObject(((BadRequestObjectResult)result).Value); var dictionary = JsonConvert.DeserializeObject <Dictionary <object, object> >(jsonValue); Assert.True(statusCode == 400); Assert.Equal("Photos don`t exist.", dictionary["Message"]); dataServiceMock.VerifyAll(); }
public void SetUp() { _repo = new Mock <IBookstoreRepository>(); var mapper = new Mock <IMapper>(); var cloudinaryConfig = new Mock <ICloudinaryConfig>(); _controller = new PhotosController(_repo.Object, mapper.Object, cloudinaryConfig.Object); _photo1 = new Photo { Id = 1, IsMain = true }; _photo2 = new Photo { Id = 2, IsMain = false }; _book = new Book { Id = 1, Title = "a", Photos = new List <Photo> { _photo1, _photo2 } }; _repo.Setup(r => r.GetBook(1)).Returns(Task.FromResult(_book)); _repo.Setup(r => r.GetPhoto(1)).Returns(Task.FromResult(_photo1)); _repo.Setup(r => r.GetPhoto(2)).Returns(Task.FromResult(_photo2)); _repo.Setup(r => r.GetMainPhotoForBook(_book.Id)).Returns(Task.FromResult(_photo1)); }
public async Task Upload_GivenFileName_ReturnsDisplayAction() { // Arrange var session = Mock.Of <ISession>(); session.Set("User", Encoding.UTF8.GetBytes("*****@*****.**")); var context = Mock.Of <HttpContext>(x => x.Session == session); var accessor = Mock.Of <IHttpContextAccessor>(x => x.HttpContext == context); var fileStorage = Mock.Of <IFileStorage>(); var keyGen = Mock.Of <IKeyGenerator>(); var photoMetaData = Mock.Of <IPhotoMetaData>(); var fromFile = Mock.Of <IFormFile>(); var model = Mock.Of <PhotoUploadViewModel>(x => x.File == fromFile); var controller = new PhotosController(keyGen, accessor, photoMetaData, fileStorage); // Act var result = await controller.Upload(model) as RedirectToActionResult; // Assert Assert.Equal("Display", result.ActionName, ignoreCase: true); }
public async Task GetPhoto_InvalidIdPassed_ReturnsOkResult() { var photo = new Photo() { Id = 1 }; var photoToReturn = new PhotoForReturnDto() { Id = 1 }; var mapperMock = new Mock <IMapper>(); mapperMock.Setup(m => m.Map <PhotoForReturnDto>(photo)).Returns(photoToReturn); var cloudinaryConfigMock = Options.Create <CloudinarySettings>(new CloudinarySettings { ApiKey = "test", ApiSecret = "test", CloudName = "test" }); var repositoryMock = new Mock <IRepositoryWrapper>(); repositoryMock.Setup(r => r.PhotoRepository.GetPhotoAsync(It.IsAny <int>())).ReturnsAsync(photo); var controllerMock = new PhotosController(repositoryMock.Object, mapperMock.Object, cloudinaryConfigMock); var result = await controllerMock.GetPhoto(2); Assert.IsType <OkObjectResult>(result); }
public async Task AddPhotoForUser_UnauthorizedUserIdPassed_ReturnsUnauthorizedResult() { var photo = new Photo() { Id = 1, IsMain = true, }; var photoToMain = new Photo() { Id = 2, IsMain = false, }; var user = new User() { Id = 2, Photos = new List <Photo> { photo, photoToMain } }; var photoForCreation = new PhotoForCreationDto { File = new FormFile(null, 0, 0, "", ""), Url = "test", PublicId = "test" }; var userClaims = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "1"), })); var mapperMock = new Mock <IMapper>(); var cloudinaryConfigMock = Options.Create <CloudinarySettings>(new CloudinarySettings { ApiKey = "test", ApiSecret = "test", CloudName = "test" }); var repositoryMock = new Mock <IRepositoryWrapper>(); repositoryMock.Setup(r => r.UserRepository.GetUserAsync(It.IsAny <int>())).ReturnsAsync(() => user); repositoryMock.Setup(r => r.SaveAllAsync()).ReturnsAsync(true); mapperMock.Setup(m => m.Map <PhotoForReturnDto>(It.IsAny <Photo>())).Returns(new PhotoForReturnDto()); mapperMock.Setup(m => m.Map <Photo>(It.IsAny <PhotoForCreationDto>())).Returns(new Photo()); var controllerMock = new PhotosController(repositoryMock.Object, mapperMock.Object, cloudinaryConfigMock); controllerMock.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = userClaims } }; var result = await controllerMock.AddPhotoForUser(user.Id, photoForCreation); Assert.IsType <UnauthorizedResult>(result); }
public void UserPhotos() { // arrange var mockUserRep = new Mock <IUserRepository>(); var mockPhotoRep = new Mock <IPhotoRepository>(); var mockLogger = new Mock <INRAKOLogger>(); var mockS3Amazon = new Mock <AmazonS3Tools>(); var mockMutation = new Mock <IMutationActionFactorySelector>(); var id = "testID"; mockUserRep.Setup(x => x.GetUser(null)).Returns((NRAKOUser)null); mockPhotoRep.Setup(x => x.GetphotosByUserID(id)).Returns(GetPhotos()); var controller = new PhotosController(mockUserRep.Object, mockPhotoRep.Object, mockLogger.Object, mockS3Amazon.Object, mockMutation.Object); // act var result = controller.UserPhotos(id); // assert var viewResult = Assert.IsType <ViewResult>(result); var model = Assert.IsAssignableFrom <List <PhotoViewModel> >( viewResult.ViewData.Model); Assert.Equal(2, model.Count); }
public void SetupContext() { var substituteDbSet = Substitute.For <IDbSet <Photo> >(); var photosList = new List <Photo>() { new Photo() { AlbumId = 1, PhotoTitle = "New1", PhotoId = 1, Album = new Album() { AlbumId = 1, AlbumTitle = "New1", Public = true, UserId = "NewUserId1" } }, new Photo() { AlbumId = 1, PhotoTitle = "New2", PhotoId = 2, Album = new Album() { AlbumId = 1, AlbumTitle = "New1", Public = true, UserId = "NewUserId1" } }, new Photo() { AlbumId = 2, PhotoTitle = "New3", PhotoId = 3, Album = new Album() { AlbumId = 2, AlbumTitle = "New2", Public = true, UserId = "NewUserId2" } } }.AsQueryable(); substituteDbSet.Provider.Returns(photosList.Provider); substituteDbSet.Expression.Returns(photosList.Expression); substituteDbSet.ElementType.Returns(photosList.ElementType); substituteDbSet.GetEnumerator().Returns(photosList.GetEnumerator()); _photoRepository = Substitute.For <IGenericRepository <Photo> >(); _photoRepository.AsQueryable().Returns(substituteDbSet.AsQueryable()); _unitOfWork = Substitute.For <IUnitOfWork>(); var config = new MapperConfiguration(cfg => { cfg.CreateMap <Photo, NewPhotoViewModel>().ReverseMap(); cfg.CreateMap <Photo, PhotoViewModel>() .ForMember(dest => dest.Content, o => o.MapFrom( src => "data:image/png;base64," + Convert.ToBase64String(src.Content.ToArray()))); cfg.CreateMap <PhotoViewModel, Photo>() .ForMember(x => x.Content, o => o.Ignore()); }); var mapper = config.CreateMapper(); _photosController = new PhotosController(_unitOfWork, _photoRepository, mapper) { GetUserId = () => "NewUserId1" }; _file = Substitute.For <HttpPostedFileBase>(); }
public void PhotosGet() { PhotosController photosController = new PhotosController(); Photos photos = photosController.Get(3); Assert.AreEqual(photos.Id, 3); }
public void PhotosGetAll() { PhotosController photosController = new PhotosController(); List <Photos> photos = photosController.Get(); int first = photos[0].Id; Assert.AreEqual(first, 3); }
public void PhotosDelete() { PhotosController photosController = new PhotosController(); HttpResponseMessage i = photosController.Delete(2); Assert.AreEqual(i.RequestMessage, "No content."); //Assert.AreEqual(1, 1); }
public PhotosControllerUnitTests() { _mockRepo = new Mock <IUnitOfWork <MadpayDbContext> >(); _mockMapper = new Mock <IMapper>(); _mockWebHostEnvironment = new Mock <IWebHostEnvironment>(); _mockUploadService = new Mock <IUploadService>(); _mockLogger = new Mock <ILogger <PhotosController> >(); _controller = new PhotosController(_mockRepo.Object, _mockMapper.Object, _mockUploadService.Object, _mockWebHostEnvironment.Object, _mockLogger.Object); }
public static bool DeletePhoto(int photoId) { var photo = PhotosDAL.GetPhoto(photoId); if (photo == null) { return(false); } return(PhotosController.DeletePhoto(photo)); }
public void Init() { var fileName = @"..\..\TestFiles\Run For The Next Generation 2011 001.JPG"; fakeDataSource = new FakeDataSource(); target = new PhotosController(fakeDataSource, provider); target.ControllerContext = new FakeControllerContext(); target.ControllerContext.Request = SetupContent(fileName); target.context = new FakeHttpContext(); }
public void Init() { var db = new FakeDataSource(); var testRecords = ObjectMother.ReturnPhotoDataRecord(3); testRecords.ForEach(r => db.Photos.Add(r)); db.SaveChanges(); target = new PhotosController(db, provider); target.context = new FakeHttpContext(); }
public async Task SetMainPhoto_NotMainPhotoPassed_ReturnsBadRequest() { var photo = new Photo() { Id = 1, IsMain = true, }; var photoToMain = new Photo() { Id = 2, IsMain = false, }; var user = new User() { Id = 1, Photos = new List <Photo> { photo, photoToMain } }; var userClaims = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.NameIdentifier, "1"), })); var mapperMock = new Mock <IMapper>(); var cloudinaryConfigMock = Options.Create <CloudinarySettings>(new CloudinarySettings { ApiKey = "test", ApiSecret = "test", CloudName = "test" }); var repositoryMock = new Mock <IRepositoryWrapper>(); repositoryMock.Setup(r => r.UserRepository.GetUserAsync(It.IsAny <int>())).ReturnsAsync(() => user); repositoryMock.Setup(r => r.PhotoRepository.GetPhotoAsync(It.IsAny <int>())).ReturnsAsync(() => photoToMain); repositoryMock.Setup(r => r.PhotoRepository.GetMainPhotoForUserAsync(It.IsAny <int>())).ReturnsAsync(() => photo); repositoryMock.Setup(r => r.SaveAllAsync()).ReturnsAsync(true); var controllerMock = new PhotosController(repositoryMock.Object, mapperMock.Object, cloudinaryConfigMock); controllerMock.ControllerContext = new ControllerContext() { HttpContext = new DefaultHttpContext() { User = userClaims } }; var result = await controllerMock.SetMainPhoto(user.Id, photoToMain.Id); Assert.IsType <NoContentResult>(result); Assert.Equal(true, photoToMain.IsMain); Assert.Equal(false, photo.IsMain); }
public void Init() { fakeDataSource = new FakeDataSource(); var photoRecordList = ObjectMother.ReturnPhotoDataRecord(3); foreach (var photo in photoRecordList) { fakeDataSource.Photos.Add(photo); } fakeDataSource.SaveChanges(); target = new PhotosController(fakeDataSource, provider); }
public override Task StartAsync(CancellationToken cancellationToken) { Client = new HttpClient(); initConnections(); PostsController = new PostsController(Client, ConnectionString); CommentsController = new CommentsController(Client, ConnectionString); AlbumsController = new AlbumsController(Client, ConnectionString); PhotosController = new PhotosController(Client, ConnectionString); TodosController = new TodosController(Client, ConnectionString); UsersController = new UsersController(Client, ConnectionString); return(base.StartAsync(cancellationToken)); }
public PhotosControllerTests() { _fixture = new Fixture(); _fixture.Behaviors.OfType <ThrowingRecursionBehavior>().ToList().ForEach(b => _fixture.Behaviors.Remove(b)); _fixture.Behaviors.Add(new OmitOnRecursionBehavior()); _logger = new Mock <ILogger <PhotosController> >(); _photosService = new Mock <IPhotoService>(); _staticConfig = new Mock <IStaticConfig>(); _staticConfig.SetupGet(p => p.ImagePasscode).Returns("somepasscode"); _photosController = new PhotosController(_logger.Object, _photosService.Object, _staticConfig.Object); }
public TakingPicturePage(TakingPicture tp, Attraction attraction) { InitializeComponent(); pc = PhotosController.GetInstance(); gc = GameController.getInstance(); scoreLabel.Text = AppResources.score + ": " + gc.GetScore(); CameraButton.Clicked += CameraButton_Clicked; subtitles.Source = ServerConection.URL_MEDIA + "subtitles.jpg"; info.Source = ServerConection.URL_MEDIA + "info.jpg"; playVideo.Source = ServerConection.URL_MEDIA + "playVideo.jpg"; how.Source = ServerConection.URL_MEDIA + "how.png"; this.tp = tp; this.attraction = attraction; }
public async Task PostReturnsBadRequestWithNullProfileIdTest() { var command = Substitute.For <IPhotoCommand>(); var sut = new PhotosController(command); using (var tokenSource = new CancellationTokenSource()) { var actual = await sut.Post(null, tokenSource.Token).ConfigureAwait(false); actual.Should().BeOfType <ErrorMessageResult>().Which.StatusCode.Should() .Be((int)HttpStatusCode.BadRequest); } }
public void IndexReturnsView() { var options = CreateNewContextOptions(); // Run the test against one instance of the context using (var context = new PhotoSharingContext(options)) { using (PhotosController controller = new PhotosController(context)) { var result = (controller.Index()) as ViewResult; Assert.Equal(nameof(controller.Index), result.ViewName); } } }
public async Task PostCreatesNewPhotoTest() { var account = Model.Create <Account>(); var user = ClaimsIdentityFactory.BuildPrincipal(account); var photoDetails = Model.Create <PhotoDetails>(); var command = Substitute.For <IPhotoCommand>(); var model = Substitute.For <IFormFile>(); var httpContext = Substitute.For <HttpContext>(); httpContext.User = user; var routerData = new RouteData(); var actionDescriptor = new ControllerActionDescriptor(); var actionContext = new ActionContext(httpContext, routerData, actionDescriptor); var controllerContext = new ControllerContext(actionContext); using (var data = new MemoryStream()) { using (var tokenSource = new CancellationTokenSource()) { model.OpenReadStream().Returns(data); using (var sut = new PhotosController(command)) { sut.ControllerContext = controllerContext; command.CreatePhoto( Arg.Is <Photo>(x => x.ContentType == model.ContentType && x.ProfileId == account.Id && x.Data == data), tokenSource.Token) .Returns(photoDetails); var actual = await sut.Post(model, tokenSource.Token).ConfigureAwait(false); var result = actual.Should().BeOfType <CreatedAtRouteResult>().Which; result.RouteName.Should().Be("ProfilePhoto"); result.RouteValues["profileId"].Should().Be(photoDetails.ProfileId); result.RouteValues["photoId"].Should().Be(photoDetails.Id); var value = result.Value.Should().BeOfType <PhotoDetails>().Which; value.Should().BeEquivalentTo(photoDetails); } } } }
public static PhotosController GetPhotosController(IRepository<Photo> photos, IRepository<Album> albums, bool validUser = true) { var controller = new PhotosController(photos, albums); SetUser(controller, validUser); return controller; }