public static MvcMockContainer SetFakeControllerContext(this Controller controller, string url = "") { MvcMockContainer container = new MvcMockContainer(); var httpContext = FakeHttpContext(container); if (!string.IsNullOrEmpty(url)) { httpContext.Request.SetupRequestUrl(url); } // Routes RouteTable.Routes.Clear(); Routing.Register(RouteTable.Routes); var routeData = new RouteData(); routeData.Values["controller"] = "wiki"; routeData.Values["action"] = "index"; ControllerContext context = new ControllerContext(new RequestContext(httpContext, routeData), controller); controller.ControllerContext = context; controller.Url = new UrlHelper(new RequestContext(httpContext, routeData), RouteTable.Routes); return(container); }
/// <summary> /// Sets up all the Request object's various properties to mock a file being uploaded. This sets the /// file size to 8192 bytes, and writes each file name to disk when SaveAs() is called, with the content "test contents" /// </summary> private void SetupMockPostedFiles(MvcMockContainer container, string destinationFolder, params string[] fileNames) { // Mock the folder the files are saved to container.Request.Setup(x => x.Form).Returns(delegate() { var values = new NameValueCollection(); values.Add("destination_folder", destinationFolder); return(values); }); // Add all the files provided so they save as an empty file to the file path Mock <HttpFileCollectionBase> postedfilesKeyCollection = new Mock <HttpFileCollectionBase>(); container.Request.Setup(req => req.Files).Returns(postedfilesKeyCollection.Object); if (fileNames != null) { List <HttpPostedFileBase> files = new List <HttpPostedFileBase>(); container.Request.Setup(x => x.Files.Count).Returns(fileNames.Length); for (int i = 0; i < fileNames.Length; i++) { Mock <HttpPostedFileBase> postedfile = new Mock <HttpPostedFileBase>(); postedfile.Setup(f => f.ContentLength).Returns(8192); postedfile.Setup(f => f.FileName).Returns(fileNames[i]); postedfile.Setup(f => f.SaveAs(It.IsAny <string>())).Callback <string>(filename => File.WriteAllText(Path.Combine(_applicationSettings.AttachmentsDirectoryPath, filename), "test contents")); container.Request.Setup(x => x.Files[i]).Returns(postedfile.Object); } } }
public static HttpContextBase FakeHttpContext(MvcMockContainer container) { var context = new Mock <HttpContextBase>(); var cache = new Mock <HttpCachePolicyBase>(); var request = new Mock <HttpRequestBase>(); var response = new Mock <HttpResponseBase>(); var session = new Mock <HttpSessionStateBase>(); var server = new Mock <HttpServerUtilityBase>(); request.Setup(r => r.HttpMethod).Returns("POST"); request.Setup(r => r.Headers).Returns(new NameValueCollection()); request.Setup(r => r.Form).Returns(new NameValueCollection()); request.Setup(r => r.QueryString).Returns(new NameValueCollection()); response.Setup(r => r.Cache).Returns(new HttpCachePolicyMock()); response.SetupProperty(r => r.StatusCode); response.Setup(x => x.ApplyAppPathModifier(It.IsAny <string>())).Returns <string>(x => { return(x); }); // UrlHelper support server.Setup(s => s.UrlDecode(It.IsAny <string>())).Returns <string>(s => s); server.Setup(s => s.MapPath(It.IsAny <string>())).Returns <string>(s => { return(s.Replace("~/bin", AppDomain.CurrentDomain.BaseDirectory + @"\").Replace("/", @"\")); }); context.Setup(ctx => ctx.Request).Returns(request.Object); context.Setup(ctx => ctx.Response).Returns(response.Object); context.Setup(ctx => ctx.Session).Returns(session.Object); context.Setup(ctx => ctx.Server).Returns(server.Object); container.Context = context; container.Request = request; container.Response = response; container.SessionState = session; container.ServerUtility = server; return(context.Object); }
public void FileUpload_Should_OverWrite_Existing_File_WhenOverWriteFiles_Setting_Is_True() { // Arrange _repository.SiteSettings.OverwriteExistingFiles = true; CreateTestFileInAttachments("file1.png", "the original file"); MvcMockContainer container = _filesController.SetFakeControllerContext(); SetupMockPostedFiles(container, "/", "file1.png"); string file1FullPath = Path.Combine(_applicationSettings.AttachmentsDirectoryPath, "file1.png"); // Act JsonResult result = _filesController.Upload(); // Assert Assert.That(result, Is.Not.Null, "JsonResult"); Assert.That(result.JsonRequestBehavior, Is.EqualTo(JsonRequestBehavior.DenyGet)); dynamic jsonObject = result.Data; Assert.That(jsonObject.status, Is.EqualTo("ok")); Assert.That(jsonObject.filename, Is.EqualTo("file1.png")); string fileContent = File.ReadAllText(file1FullPath); Assert.That(fileContent, Is.EqualTo("test contents")); }
public static HttpContextBase FakeHttpContext(string url) { MvcMockContainer container = new MvcMockContainer(); HttpContextBase context = FakeHttpContext(container); context.Request.SetupRequestUrl(url); return(context); }
protected HttpContextBase GetHttpContext(PrincipalStub principal) { MvcMockContainer container = new MvcMockContainer(); HttpContextBase context = MvcMockHelpers.FakeHttpContext(container); container.Context.SetupProperty(x => x.User, principal); return(context); }
public void FileUpload_With_Bad_Folder_Path_Should_Throw_Exception() { // Arrange MvcMockContainer container = _filesController.SetFakeControllerContext(); SetupMockPostedFiles(container, "/../../bad/path"); // Act JsonResult result = _filesController.Upload(); // Assert }
public void AttachmentsRoutePath_Should_Use_AttachmentsRoutePath_And_Prepend_ApplicationPath() { // Arrange MvcMockContainer container = new MvcMockContainer(); HttpContextBase httpContext = MvcMockHelpers.FakeHttpContext(container); container.Request.Setup(x => x.ApplicationPath).Returns("/wiki"); ApplicationSettings appSettings = new ApplicationSettings(httpContext); appSettings.AttachmentsRoutePath = "Folder1/Folder2"; // Act string actualUrlPath = appSettings.AttachmentsUrlPath; // Assert Assert.That(actualUrlPath, Is.EqualTo(@"/wiki/Folder1/Folder2")); }
public void AttachmentsDirectoryPath_Should_Map_AttachmentsFolder_And_End_With_Slash() { // Arrange string attachmentsFolder = @"~/myfolder"; MvcMockContainer container = new MvcMockContainer(); HttpContextBase httpContext = MvcMockHelpers.FakeHttpContext(container); container.ServerUtility.Setup(x => x.MapPath(attachmentsFolder)).Returns(@"c:\inetpub\myfolder"); ApplicationSettings appSettings = new ApplicationSettings(httpContext); appSettings.AttachmentsFolder = attachmentsFolder; // Act string actualPath = appSettings.AttachmentsDirectoryPath; // Assert Assert.That(actualPath, Is.EqualTo(@"c:\inetpub\myfolder\")); }
public void Setup() { _container = new MocksAndStubsContainer(); _applicationSettings = _container.ApplicationSettings; _repository = _container.Repository; _pluginFactory = _container.PluginFactory; _settingsService = _container.SettingsService; _userService = _container.UserService; _historyService = _container.HistoryService; _markupConverter = _container.MarkupConverter; _searchService = _container.SearchService; // Use a stub instead of the MocksAndStubsContainer's default _contextStub = new UserContextStub(); // Customise the page service so we can verify what was called _pageServiceMock = new Mock <IPageService>(); _pageServiceMock.Setup(x => x.GetMarkupConverter()).Returns(new MarkupConverter(_applicationSettings, _repository, _pluginFactory)); _pageServiceMock.Setup(x => x.GetById(It.IsAny <int>(), false)).Returns <int, bool>((int id, bool loadContent) => { Page page = _repository.GetPageById(id); return(new PageViewModel(page)); }); _pageServiceMock.Setup(x => x.GetById(It.IsAny <int>(), true)).Returns <int, bool>((int id, bool loadContent) => { PageContent content = _repository.GetLatestPageContent(id); if (content != null) { return(new PageViewModel(content, _markupConverter)); } else { return(null); } }); _pageServiceMock.Setup(x => x.FindByTag(It.IsAny <string>())); _pageService = _pageServiceMock.Object; _pagesController = new PagesController(_applicationSettings, _userService, _settingsService, _pageService, _searchService, _historyService, _contextStub); _mocksContainer = _pagesController.SetFakeControllerContext(); }
public void Upload_Should_Return_Ok_Json_Status_And_Last_Filename_Uploaded_With_Text_Plain_Content_Type() { // Arrange MvcMockContainer container = _filesController.SetFakeControllerContext(); SetupMockPostedFiles(container, "/", "file1.png"); // Act JsonResult result = _filesController.Upload() as JsonResult; // Assert Assert.That(result, Is.Not.Null, "JsonResult"); Assert.That(result.ContentType, Is.EqualTo("text/plain"), "JsonResult content type"); Assert.That(result.JsonRequestBehavior, Is.EqualTo(JsonRequestBehavior.DenyGet)); dynamic jsonObject = result.Data; Assert.That(jsonObject.status, Is.EqualTo("ok")); Assert.That(jsonObject.filename, Is.EqualTo("file1.png")); }
public void Setup() { _container = new MocksAndStubsContainer(); _applicationSettings = _container.ApplicationSettings; _context = _container.UserContext; _settingsService = _container.SettingsService; _userService = _container.UserService; _controller = new ControllerBaseStub(_applicationSettings, _userService, _context, _settingsService); MvcMockContainer container = _controller.SetFakeControllerContext("~/"); // Used by InstallController _repository = _container.Repository; _pluginFactory = _container.PluginFactory; _historyService = _container.HistoryService; _pageService = _container.PageService; _searchService = _container.SearchService; _configReaderWriter = new ConfigReaderWriterStub(); }
public void Setup() { _container = new MocksAndStubsContainer(); _applicationSettings = _container.ApplicationSettings; _applicationSettings.AttachmentsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "attachments"); _repository = _container.Repository; _settingsService = _container.SettingsService; _userService = _container.UserService; _userContext = _container.UserContext; _emailClientMock = _container.EmailClient; _userService.AddUser(AdminEmail, AdminUsername, AdminPassword, true, true); _userService.Users[0].IsActivated = true; _userService.Users[0].Firstname = "Firstname"; _userService.Users[0].Lastname = "LastnameNotSurname"; _userController = new UserController(_applicationSettings, _userService, _userContext, _settingsService, null, null); _mvcMockContainer = _userController.SetFakeControllerContext(); }
public void Upload_Should_Return_Json_Error_Status_When_FileException_Is_Thrown() { // Arrange MvcMockContainer container = _filesController.SetFakeControllerContext(); SetupMockPostedFiles(container, "/", "file1.png"); _fileService.CustomException = new FileException("It didn't upload a file", null); // Act JsonResult result = _filesController.NewFolder("currentfolder", "newfolder") as JsonResult; // Assert Assert.That(result, Is.Not.Null, "JsonResult"); Assert.That(result.JsonRequestBehavior, Is.EqualTo(JsonRequestBehavior.DenyGet)); dynamic jsonObject = result.Data; Assert.That(jsonObject.status, Is.EqualTo("error")); Assert.That(jsonObject.message, Is.EqualTo("It didn't upload a file")); }
public void Setup() { _container = new MocksAndStubsContainer(); _applicationSettings = _container.ApplicationSettings; _context = _container.UserContext; _repository = _container.Repository; _pluginFactory = _container.PluginFactory; _settingsService = _container.SettingsService; _userService = _container.UserService; _historyService = _container.HistoryService; _pageService = _container.PageService; _attachmentFileHandler = new AttachmentFileHandler(_applicationSettings, _container.FileService); _fileService = _container.FileService as FileServiceMock; try { // Delete any existing attachments folder DirectoryInfo directoryInfo = new DirectoryInfo(_applicationSettings.AttachmentsFolder); if (directoryInfo.Exists) { directoryInfo.Attributes = FileAttributes.Normal; directoryInfo.Delete(true); } Directory.CreateDirectory(_applicationSettings.AttachmentsFolder); } catch (IOException e) { Assert.Fail("Unable to delete the attachments folder " + _applicationSettings.AttachmentsFolder + ", does it have a lock/explorer window open, or Mercurial open?" + e.ToString()); } catch (ArgumentException e) { Assert.Fail("Unable to delete the attachments folder " + _applicationSettings.AttachmentsFolder + ", is EasyMercurial open?" + e.ToString()); } _filesController = new FileManagerController(_applicationSettings, _userService, _context, _settingsService, _attachmentFileHandler, _fileService); _mvcMockContainer = _filesController.SetFakeControllerContext(); }
public void Setup() { _container = new MocksAndStubsContainer(); _applicationSettings = _container.ApplicationSettings; _context = _container.UserContext; _repository = _container.Repository; _pluginFactory = _container.PluginFactory; _settingsService = _container.SettingsService; _userService = _container.UserService; _historyService = _container.HistoryService; _pageService = _container.PageService; _attachmentFileHandler = new AttachmentFileHandler(_applicationSettings,_container.FileService); _fileService = _container.FileService as FileServiceMock; try { // Delete any existing attachments folder DirectoryInfo directoryInfo = new DirectoryInfo(_applicationSettings.AttachmentsFolder); if (directoryInfo.Exists) { directoryInfo.Attributes = FileAttributes.Normal; directoryInfo.Delete(true); } Directory.CreateDirectory(_applicationSettings.AttachmentsFolder); } catch (IOException e) { Assert.Fail("Unable to delete the attachments folder " + _applicationSettings.AttachmentsFolder + ", does it have a lock/explorer window open, or Mercurial open?" + e.ToString()); } catch (ArgumentException e) { Assert.Fail("Unable to delete the attachments folder " + _applicationSettings.AttachmentsFolder + ", is EasyMercurial open?" + e.ToString()); } _filesController = new FileManagerController(_applicationSettings, _userService, _context, _settingsService, _attachmentFileHandler, _fileService); _mvcMockContainer = _filesController.SetFakeControllerContext(); }
public void Setup() { _container = new MocksAndStubsContainer(); _applicationSettings = _container.ApplicationSettings; _repository = _container.Repository; _pluginFactory = _container.PluginFactory; _settingsService = _container.SettingsService; _userService = _container.UserService; _historyService = _container.HistoryService; _markupConverter = _container.MarkupConverter; _searchService = _container.SearchService; // Use a stub instead of the MocksAndStubsContainer's default _contextStub = new UserContextStub(); // Customise the page service so we can verify what was called _pageServiceMock = new Mock<IPageService>(); _pageServiceMock.Setup(x => x.GetMarkupConverter()).Returns(new MarkupConverter(_applicationSettings, _repository, _pluginFactory)); _pageServiceMock.Setup(x => x.GetById(It.IsAny<int>(), false)).Returns<int, bool>((int id, bool loadContent) => { Page page = _repository.GetPageById(id); return new PageViewModel(page); }); _pageServiceMock.Setup(x => x.GetById(It.IsAny<int>(), true)).Returns<int,bool>((int id, bool loadContent) => { PageContent content = _repository.GetLatestPageContent(id); if (content != null) return new PageViewModel(content, _markupConverter); else return null; }); _pageServiceMock.Setup(x => x.FindByTag(It.IsAny<string>())); _pageService = _pageServiceMock.Object; _pagesController = new PagesController(_applicationSettings, _userService, _settingsService, _pageService, _searchService, _historyService, _contextStub); _mocksContainer = _pagesController.SetFakeControllerContext(); }
/// <summary> /// Sets up all the Request object's various properties to mock a file being uploaded. This sets the /// file size to 8192 bytes, and writes each file name to disk when SaveAs() is called, with the content "test contents" /// </summary> private void SetupMockPostedFiles(MvcMockContainer container, string destinationFolder, params string[] fileNames) { // Mock the folder the files are saved to container.Request.Setup(x => x.Form).Returns(delegate() { var values = new NameValueCollection(); values.Add("destination_folder", destinationFolder); return values; }); // Add all the files provided so they save as an empty file to the file path Mock<HttpFileCollectionBase> postedfilesKeyCollection = new Mock<HttpFileCollectionBase>(); container.Request.Setup(req => req.Files).Returns(postedfilesKeyCollection.Object); if (fileNames != null) { List<HttpPostedFileBase> files = new List<HttpPostedFileBase>(); container.Request.Setup(x => x.Files.Count).Returns(fileNames.Length); for (int i = 0; i < fileNames.Length; i++) { Mock<HttpPostedFileBase> postedfile = new Mock<HttpPostedFileBase>(); postedfile.Setup(f => f.ContentLength).Returns(8192); postedfile.Setup(f => f.FileName).Returns(fileNames[i]); postedfile.Setup(f => f.SaveAs(It.IsAny<string>())).Callback<string>(filename => File.WriteAllText(Path.Combine(_applicationSettings.AttachmentsDirectoryPath, filename), "test contents")); container.Request.Setup(x => x.Files[i]).Returns(postedfile.Object); } } }
protected HttpContextBase GetHttpContext(PrincipalStub principal) { MvcMockContainer container = new MvcMockContainer(); HttpContextBase context = MvcMockHelpers.FakeHttpContext(container); container.Context.SetupProperty(x => x.User, principal); return context; }